From 1e57a46299244793beb27e74be171d1540606999 Mon Sep 17 00:00:00 2001 From: oliviermartin Date: Fri, 25 Jan 2013 11:28:06 +0000 Subject: ARM Packages: Fixed line endings This large code change only modifies the line endings to be CRLF to be compliant with the EDK2 coding convention document. git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@14088 6f19259b-4bc3-4df7-8a09-765794883524 --- ArmPkg/Application/LinuxLoader/LinuxConfig.c | 706 ++-- ArmPkg/Application/LinuxLoader/LinuxInternal.h | 98 +- ArmPkg/ArmPkg.dsc | 262 +- ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S | 382 +-- ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm | 304 +- ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S | 594 ++-- ArmPkg/Drivers/CpuPei/CpuPei.inf | 2 +- ArmPkg/Drivers/PL390Gic/PL390GicDxe.c | 850 ++--- ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf | 114 +- ArmPkg/Drivers/TimerDxe/TimerDxe.c | 760 ++--- ArmPkg/Drivers/TimerDxe/TimerDxe.inf | 118 +- ArmPkg/Filesystem/SemihostFs/SemihostFs.inf | 92 +- ArmPkg/Include/Library/ArmCpuLib.h | 56 +- ArmPkg/Include/Library/ArmDisassemblerLib.h | 82 +- ArmPkg/Include/Library/ArmLib.h | 1122 +++--- ArmPkg/Include/Library/ArmV7ArchTimerLib.h | 230 +- .../Include/Library/DefaultExceptionHandlerLib.h | 62 +- ArmPkg/Include/Library/SemihostLib.h | 200 +- .../Include/Library/UncachedMemoryAllocationLib.h | 1330 ++++---- .../ArmCacheMaintenanceLib.c | 250 +- .../ArmCacheMaintenanceLib.inf | 74 +- ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf | 2 +- ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c | 266 +- ArmPkg/Library/ArmLib/Arm11/Arm11Support.S | 524 +-- ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm | 314 +- ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c | 262 +- ArmPkg/Library/ArmLib/Arm9/Arm9Support.S | 306 +- ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm | 306 +- ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c | 550 +-- ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c | 528 +-- ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm | 122 +- ArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm | 140 +- ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S | 2 +- ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm | 4 +- ArmPkg/Library/BdsLib/BdsAppLoader.c | 288 +- ArmPkg/Library/BdsLib/BdsFilePath.c | 1812 +++++----- ArmPkg/Library/BdsLib/BdsHelper.c | 694 ++-- ArmPkg/Library/BdsLib/BdsInternal.h | 196 +- ArmPkg/Library/BdsLib/BdsLib.inf | 154 +- ArmPkg/Library/BdsLib/BdsLinuxAtag.c | 346 +- ArmPkg/Library/BdsLib/BdsLinuxLoader.c | 548 +-- ArmPkg/Library/BdsLib/BdsLinuxLoader.h | 312 +- ArmPkg/Library/BdsLib/BdsLoadOption.c | 540 +-- .../CompilerIntrinsicsLib/Arm/Llvm_int_lib.h | 198 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S | 70 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c | 166 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S | 72 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c | 168 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S | 114 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c | 192 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S | 98 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c | 196 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S | 306 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm | 310 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S | 98 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c | 154 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S | 64 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c | 156 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm | 82 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S | 118 +- .../Library/CompilerIntrinsicsLib/Arm/ldivmod.asm | 116 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm | 86 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm | 88 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S | 70 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c | 166 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S | 68 +- .../Library/CompilerIntrinsicsLib/Arm/memcpy.asm | 80 +- .../Library/CompilerIntrinsicsLib/Arm/memcpy4.asm | 122 +- .../Library/CompilerIntrinsicsLib/Arm/memmove.asm | 108 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S | 76 +- .../Library/CompilerIntrinsicsLib/Arm/memset.asm | 118 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S | 92 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c | 154 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S | 54 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c | 140 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S | 116 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c | 196 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm | 98 +- .../Library/CompilerIntrinsicsLib/Arm/switch.asm | 58 +- .../Library/CompilerIntrinsicsLib/Arm/switch16.S | 62 +- .../Library/CompilerIntrinsicsLib/Arm/switch32.S | 60 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S | 56 +- .../Library/CompilerIntrinsicsLib/Arm/switchu8.S | 58 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S | 76 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c | 164 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S | 54 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c | 142 +- .../Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S | 484 +-- .../Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c | 574 ++-- ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S | 114 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c | 222 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S | 534 +-- ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm | 536 +-- .../Library/CompilerIntrinsicsLib/Arm/uldivmod.c | 86 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S | 58 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c | 144 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S | 56 +- ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c | 136 +- .../Library/CompilerIntrinsicsLib/Arm/uwrite.asm | 136 +- .../CompilerIntrinsicsLib.inf | 204 +- .../DebugAgentSymbolsBaseLib/DebugAgentException.S | 552 +-- .../DebugPeCoffExtraActionLib.inf | 78 +- .../DebugUncachedMemoryAllocationLib.inf | 2 +- .../RvdPeCoffExtraActionLib.inf | 82 +- ArmPkg/Library/SemihostLib/Arm/GccSemihost.S | 78 +- ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h | 368 +- ArmPkg/Library/SemihostLib/SemihostLib.inf | 6 +- .../UncachedMemoryAllocationLib.inf | 2 +- ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc | 714 ++-- ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf | 490 +-- ArmPlatformPkg/ArmPlatformPkg.fdf | 604 ++-- .../ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf | 620 ++-- .../Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c | 292 +- .../ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c | 152 +- .../NorFlashArmRealViewEbLib.inf | 70 +- .../PL111LcdArmRealViewEbLib.inf | 130 +- .../SysConfigArmRealViewEbLib.inf | 68 +- .../ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf | 636 ++-- .../ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf | 636 ++-- .../ArmVExpressLibCTA9x4/ArmVExpressLib.inf | 110 +- .../Library/ArmVExpressLibCTA9x4/CTA9x4.c | 428 +-- .../Library/ArmVExpressLibRTSM/RTSM.c | 326 +- .../Library/ArmVExpressLibRTSM/RTSMMem.c | 2 +- .../Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c | 296 +- .../ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf | 104 +- .../Library/ArmVExpressSecLibRTSM/RTSMSec.c | 166 +- .../ArmVExpressSysConfigLib.inf | 70 +- .../HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf | 2 +- .../NorFlashArmVExpressLib.inf | 64 +- .../PL111LcdArmVExpressLib.inf | 86 +- .../Library/ResetSystemLib/ResetSystemLib.c | 162 +- .../Library/ResetSystemLib/ResetSystemLib.inf | 70 +- ArmPlatformPkg/Bds/Bds.inf | 150 +- ArmPlatformPkg/Bds/BdsHelper.c | 634 ++-- .../LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c | 1764 +++++----- .../LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c | 752 ++--- .../PL111LcdGraphicsOutputDxe.inf | 112 +- .../Drivers/NorFlashDxe/NorFlashBlockIoDxe.c | 238 +- ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c | 1602 ++++----- ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h | 632 ++-- ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf | 136 +- .../Drivers/NorFlashDxe/NorFlashFvbDxe.c | 1624 ++++----- ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c | 688 ++-- .../Drivers/PL061GpioDxe/PL061GpioDxe.inf | 100 +- ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c | 790 ++--- .../Drivers/SP804TimerDxe/SP804TimerDxe.inf | 118 +- .../Drivers/SP805WatchdogDxe/SP805Watchdog.c | 774 ++--- .../Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf | 104 +- ArmPlatformPkg/Include/Drivers/PL111Lcd.h | 280 +- ArmPlatformPkg/Include/Drivers/PL301Axi.h | 42 +- ArmPlatformPkg/Include/Drivers/PL341Dmc.h | 672 ++-- ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h | 96 +- .../Include/Library/ArmPlatformGlobalVariableLib.h | 76 +- ArmPlatformPkg/Include/Library/ArmPlatformLib.h | 262 +- ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h | 176 +- .../Include/Library/ArmPlatformSysConfigLib.h | 126 +- .../Dxe/DxeArmPlatformGlobalVariableLib.c | 152 +- .../Dxe/DxeArmPlatformGlobalVariableLib.inf | 88 +- .../Pei/PeiArmPlatformGlobalVariableLib.c | 168 +- .../Pei/PeiArmPlatformGlobalVariableLib.inf | 80 +- .../PrePi/PrePiArmPlatformGlobalVariableLib.c | 210 +- .../Sec/SecArmPlatformGlobalVariableLib.c | 162 +- .../ArmPlatformLibNull/ArmPlatformLibNull.c | 328 +- .../ArmPlatformSecLibNull/ArmPlatformLibNullSec.c | 148 +- .../DebugSecExtraActionLib.inf | 110 +- .../PL011SerialPortLib/PL011SerialPortLib.c | 368 +- .../Library/SP804TimerLib/SP804TimerLib.c | 520 +-- .../Library/SP804TimerLib/SP804TimerLib.inf | 88 +- ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf | 132 +- ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf | 106 +- ArmPlatformPkg/Scripts/Ds5/build_report.py | 108 +- ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py | 434 +-- ArmPlatformPkg/Scripts/Ds5/firmware_volume.py | 602 ++-- ArmPlatformPkg/Scripts/Ds5/system_table.py | 258 +- ArmPlatformPkg/Sec/Sec.c | 390 +-- BeagleBoardPkg/BeagleBoardPkg.dec | 72 +- .../Library/BeagleBoardLib/BeagleBoard.c | 270 +- .../Library/BeagleBoardLib/BeagleBoardLib.inf | 106 +- BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c | 206 +- .../Library/GdbSerialLib/GdbSerialLib.inf | 82 +- BeagleBoardPkg/Sec/Cache.c | 2 +- BeagleBoardPkg/Sec/Sec.inf | 146 +- BeagleBoardPkg/Tools/generate_image.c | 816 ++--- EmbeddedPkg/Ebl/Ebl.h | 414 +-- EmbeddedPkg/EmbeddedPkg.dsc | 524 +-- EmbeddedPkg/GdbStub/GdbStub.c | 2526 +++++++------- EmbeddedPkg/GdbStub/GdbStubInternal.h | 1492 ++++---- EmbeddedPkg/GdbStub/Ia32/Processor.c | 1986 +++++------ EmbeddedPkg/GdbStub/SerialIo.c | 1102 +++--- EmbeddedPkg/Include/Library/DebugAgentTimerLib.h | 2 +- EmbeddedPkg/Include/Library/DmaLib.h | 144 +- .../Include/Library/EblAddExternalCommandLib.h | 244 +- EmbeddedPkg/Include/Library/EblCmdLib.h | 96 +- EmbeddedPkg/Include/Library/EblNetworkLib.h | 136 +- EmbeddedPkg/Include/Library/GdbSerialLib.h | 214 +- EmbeddedPkg/Include/Library/PrePiLib.h | 1580 ++++----- EmbeddedPkg/Include/Library/SerialPortExtLib.h | 132 +- EmbeddedPkg/Include/Protocol/EblAddCommand.h | 10 +- .../Include/Protocol/EmbeddedExternalDevice.h | 188 +- EmbeddedPkg/Include/Protocol/EmbeddedGpio.h | 334 +- EmbeddedPkg/Include/fdt.h | 148 +- EmbeddedPkg/Include/libfdt.h | 2956 ++++++++-------- EmbeddedPkg/Include/libfdt_env.h | 154 +- .../DebugAgentTimerLibNull/DebugAgentTimerLib.c | 2 +- .../EblAddExternalCommandLib.inf | 2 +- .../Library/EblCmdLibNull/EblCmdLibNull.inf | 2 +- EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c | 346 +- .../Library/EblNetworkLib/EblNetworkLib.inf | 2 +- EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c | 3556 ++++++++++---------- EmbeddedPkg/Library/FdtLib/fdt.c | 444 +-- EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c | 168 +- EmbeddedPkg/Library/FdtLib/fdt_ro.c | 1150 +++---- EmbeddedPkg/Library/FdtLib/fdt_rw.c | 990 +++--- EmbeddedPkg/Library/FdtLib/fdt_strerror.c | 192 +- EmbeddedPkg/Library/FdtLib/fdt_sw.c | 512 +-- EmbeddedPkg/Library/FdtLib/fdt_wip.c | 236 +- EmbeddedPkg/Library/FdtLib/libfdt_internal.h | 190 +- .../GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S | 516 +-- .../GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm | 518 +-- EmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c | 104 +- EmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h | 1398 ++++---- EmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c | 1824 +++++----- EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf | 2 +- EmbeddedPkg/Library/PrePiHobLib/Hob.c | 1704 +++++----- .../PrePiHobListPointerLib/PrePiHobListPointer.c | 10 +- .../PrePiHobListPointerLib.inf | 2 +- EmbeddedPkg/Library/PrePiLib/FwVol.c | 1684 ++++----- EmbeddedPkg/Library/PrePiLib/PrePi.h | 92 +- EmbeddedPkg/Library/PrePiLib/PrePiLib.c | 452 +-- EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c | 654 ++-- .../TemplateRealTimeClockLib.inf | 2 +- .../TemplateResetSystemLib.inf | 2 +- EmbeddedPkg/TemplateSec/TemplateSec.inf | 130 +- EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf | 2 +- Omap35xxPkg/Flash/Flash.c | 1560 ++++----- Omap35xxPkg/Flash/Flash.h | 212 +- Omap35xxPkg/Flash/Flash.inf | 96 +- Omap35xxPkg/Gpio/Gpio.c | 270 +- Omap35xxPkg/Gpio/Gpio.inf | 90 +- Omap35xxPkg/Include/Library/OmapDmaLib.h | 94 +- Omap35xxPkg/Include/Library/OmapLib.h | 88 +- Omap35xxPkg/Include/Omap3530/Omap3530.h | 80 +- Omap35xxPkg/Include/Omap3530/Omap3530Dma.h | 260 +- Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h | 262 +- Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h | 214 +- Omap35xxPkg/Include/Omap3530/Omap3530I2c.h | 124 +- Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h | 96 +- Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h | 428 +-- .../Include/Omap3530/Omap3530PadConfiguration.h | 606 ++-- Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h | 330 +- Omap35xxPkg/Include/Omap3530/Omap3530Timer.h | 164 +- Omap35xxPkg/Include/Omap3530/Omap3530Usb.h | 86 +- Omap35xxPkg/Include/TPS65950.h | 160 +- .../LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c | 890 ++--- .../LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c | 806 ++--- .../LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h | 314 +- .../LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf | 104 +- .../DebugAgentTimerLib/DebugAgentTimerLib.c | 100 +- .../DebugAgentTimerLib/DebugAgentTimerLib.inf | 8 +- Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c | 204 +- Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf | 82 +- Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf | 2 +- .../Library/RealTimeClockLib/RealTimeClockLib.c | 594 ++-- .../Library/RealTimeClockLib/RealTimeClockLib.inf | 76 +- Omap35xxPkg/MMCHSDxe/MMCHS.c | 2990 ++++++++-------- Omap35xxPkg/MMCHSDxe/MMCHS.h | 54 +- Omap35xxPkg/MMCHSDxe/MMCHS.inf | 108 +- Omap35xxPkg/MmcHostDxe/MmcHostDxe.c | 1354 ++++---- Omap35xxPkg/MmcHostDxe/MmcHostDxe.h | 88 +- Omap35xxPkg/MmcHostDxe/MmcHostDxe.inf | 106 +- Omap35xxPkg/Omap35xxPkg.dsc | 376 +-- Omap35xxPkg/PciEmulation/PciEmulation.c | 1048 +++--- Omap35xxPkg/PciEmulation/PciEmulation.h | 2 +- Omap35xxPkg/PciEmulation/PciEmulation.inf | 2 +- Omap35xxPkg/SmbusDxe/Smbus.c | 650 ++-- Omap35xxPkg/SmbusDxe/Smbus.inf | 90 +- Omap35xxPkg/TPS65950Dxe/TPS65950.c | 232 +- Omap35xxPkg/TPS65950Dxe/TPS65950.inf | 96 +- Omap35xxPkg/TimerDxe/Timer.c | 752 ++--- Omap35xxPkg/TimerDxe/TimerDxe.inf | 114 +- 280 files changed, 48863 insertions(+), 48863 deletions(-) diff --git a/ArmPkg/Application/LinuxLoader/LinuxConfig.c b/ArmPkg/Application/LinuxLoader/LinuxConfig.c index b95d0a4dc0..0d0b8b4746 100644 --- a/ArmPkg/Application/LinuxLoader/LinuxConfig.c +++ b/ArmPkg/Application/LinuxLoader/LinuxConfig.c @@ -1,353 +1,353 @@ -/** @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; + + 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/LinuxInternal.h b/ArmPkg/Application/LinuxLoader/LinuxInternal.h index e486273520..28673b561e 100644 --- a/ArmPkg/Application/LinuxLoader/LinuxInternal.h +++ b/ArmPkg/Application/LinuxLoader/LinuxInternal.h @@ -1,49 +1,49 @@ -/** @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 -#include -#include -#include -#include -#include -#include -#include - -#include - -#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, 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 +#include +#include +#include +#include +#include +#include +#include + +#include + +#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 abc25a69ab..a2433df869 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 diff --git a/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S b/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S index 96bd68246f..2b439f3331 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4af58339b7..2ea8d65f15 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 86d2a7135f..948ad69946 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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 - -/* - -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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 + +/* + +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 3d1665aabd..ec8b9f5c53 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 1a8239e73a..590cdb7056 100644 --- a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c +++ b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c @@ -1,425 +1,425 @@ -/*++ - -Copyright (c) 2009, Hewlett-Packard Company. All rights reserved.
-Portions copyright (c) 2010, Apple Inc. All rights reserved.
-Portions copyright (c) 2011-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. - -Module Name: - - Gic.c - -Abstract: - - Driver implementing the GIC interrupt controller protocol - ---*/ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#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< 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.
+Portions copyright (c) 2010, Apple Inc. All rights reserved.
+Portions copyright (c) 2011-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. + +Module Name: + + Gic.c + +Abstract: + + Driver implementing the GIC interrupt controller protocol + +--*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#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< 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; +} diff --git a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf index b63216ee98..422fd414b7 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.
-# 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. -# -#**/ - -[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.
+# 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. +# +#**/ + +[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/TimerDxe/TimerDxe.c b/ArmPkg/Drivers/TimerDxe/TimerDxe.c index 50de7668ea..cbc34e8e41 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -// 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// 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 4fe2e2f0bf..061fcbc688 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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/SemihostFs.inf b/ArmPkg/Filesystem/SemihostFs/SemihostFs.inf index 25b7289483..30ce6665f0 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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/Library/ArmCpuLib.h b/ArmPkg/Include/Library/ArmCpuLib.h index 6f92b111d6..0c415992df 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 038f2ddfa2..757c95ec79 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 23beb24274..1e55284317 100644 --- a/ArmPkg/Include/Library/ArmLib.h +++ b/ArmPkg/Include/Library/ArmLib.h @@ -1,561 +1,561 @@ -/** @file - - Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
- Copyright (c) 2011 - 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 __ARM_LIB__ -#define __ARM_LIB__ - -#include - -#ifdef ARM_CPU_ARMv6 -#include -#else -#include -#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.
+ Copyright (c) 2011 - 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 __ARM_LIB__ +#define __ARM_LIB__ + +#include + +#ifdef ARM_CPU_ARMv6 +#include +#else +#include +#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__ diff --git a/ArmPkg/Include/Library/ArmV7ArchTimerLib.h b/ArmPkg/Include/Library/ArmV7ArchTimerLib.h index d2f4a46c66..983184810f 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 cf3fe0cca0..7166dbb36e 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 68f4b772eb..2ced7f107c 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 ac77fbc699..4161fc7c62 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 0dd453003c..2557a2cf09 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include + +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 12470480d3..7a43bfe9bc 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# 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 5c809ba3a3..5465695115 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 86427035ed..c683861cbb 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include + +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 7ff377c023..2f4be7e93f 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.
-# 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 - -.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.
+# 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 + +.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 fb3e91b7ed..8c27093045 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 7c3a384a97..c92f9159c6 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include + +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 49e266dd38..28cc5b6e6c 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 dfee136b2b..fc87828e20 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 7835b414c0..478a5da695 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 -#include -#include -#include -#include -#include -#include -#include "ArmV7Lib.h" -#include "ArmLibPrivate.h" -#include - -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 +#include +#include +#include +#include +#include +#include +#include "ArmV7Lib.h" +#include "ArmLibPrivate.h" +#include + +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 d9cf8826ce..cc5074bfc2 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#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/BaseMemoryLibStm/Arm/CopyMem.asm b/ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm index ca8d06a550..d0faa00d1e 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 e7cbdf1ed0..5df7c6b794 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 d5c50cbef4..0415ed7091 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 bbab580cf1..de438d6c56 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 2d7f96e28b..2b88bf1e05 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 - -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 + +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 a8b77a3d22..2c93243795 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 -#include -#include - -#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 +#include +#include + +#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 29cc12bd33..5016bedcd4 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 -#include -#include -#include -#include - -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 +#include +#include +#include +#include + +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 85f9f41598..5ae46f86e8 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +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 9dee03a795..a79f166b40 100644 --- a/ArmPkg/Library/BdsLib/BdsLib.inf +++ b/ArmPkg/Library/BdsLib/BdsLib.inf @@ -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. -# -#*/ - -[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-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 diff --git a/ArmPkg/Library/BdsLib/BdsLinuxAtag.c b/ArmPkg/Library/BdsLib/BdsLinuxAtag.c index b59df07622..8946b14236 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 901781f2f8..e3249e1307 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 - ArmDisableDataCache(); - ArmCleanInvalidateDataCache(); - - // 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); -} - +/** @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 + ArmDisableDataCache(); + ArmCleanInvalidateDataCache(); + + // 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 a9b7037d19..a3ecddc4f1 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 8abbc9b5cd..3f4566ffab 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 eb0a650624..6e42dcd14e 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + +#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 5578797125..cec0c55f1e 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 80ec5a6008..526fcab65c 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 defd1f081c..09c927ca6b 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 703a37fd72..229531ed26 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 11ea95cef4..942344674a 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 196f23f8cc..50ae87a6cc 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 0c8e78d961..d530025a1d 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 425d8b9e44..71f303b344 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.
- This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 3534eaba23..faf70dbf45 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 e38105dd63..13f701358e 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 342f376bb0..7be2e2886a 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4d790b8f9c..e86bd1361e 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 3976fda148..b74cbb6439 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4a19e15a30..b322f9a57a 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 1821816ab7..069438c920 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 02ecdfe8d7..510778ab07 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 32b65df521..0059c2f6f9 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm index 099693949f..43d9e729cf 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm index 8f1af0ed44..de9a2186c2 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 73d83599ba..efec070c01 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4353be9dec..47c80c2d23 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 18299326ca..07e0cd6bb4 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 aef8a5c11c..e01b80d4bc 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 a3cd58aba1..9780060c1c 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 d84429ef7f..ae5c990f57 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 35783620c7..7b1cf8d972 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 d567cd54e7..74e0243048 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 75572c82b6..e058ea4468 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 f9e5afe912..972fc065e9 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 eb698d604f..07f8ef72f7 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 68373d9c20..9bdf077fbe 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 36956c24e2..e8ac1ffffc 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 d48bd22b43..67d0e4eed5 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#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 5d369e9afb..4897636489 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 8d34c5de52..2c8a0318d5 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 97ebf79351..ce6904e0c1 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 e0fd100aa5..63aed6e6b0 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 ea3340c9a5..688e106a96 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http)://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http)://opensource.org/licenses/bsd-license.php +# +# 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 83636e1f50..254b054353 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http)://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http)://opensource.org/licenses/bsd-license.php +# +# 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 e85be6cae0..f448ed58cc 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 25a821ef8f..70d5a531b9 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 a8b9702707..f274901fa4 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 b24606f09c..a8d9b09671 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 cadc1d291a..1c0f2eae67 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 de22647400..829482ddf5 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 92c9cad960..a9223d7fb5 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 aec1a1ccbf..020b3fadc5 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 6b55135f33..75b0bb93a0 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 d792342e1f..393794c13a 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 4876743339..feac60195d 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + + +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 75bb240888..6e23057c25 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 125af09b64..ebd769755a 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 9d0f17e6e9..bd32fd1244 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 5e302d6193..e3aa4da87c 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 a456ea2500..0b79e3416b 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 9b116f8901..e6e728af65 100644 --- a/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf +++ b/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf @@ -1,102 +1,102 @@ -#/** @file -# Base Library implementation. -# -# Copyright (c) 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. -# -# -#**/ - -[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.
+# 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] + diff --git a/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S b/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S index 3c17386766..d92acfeacb 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.
-# Copyright (c) 2011 - 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. -# -#------------------------------------------------------------------------------ - -#include - -/* - -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.
+# Copyright (c) 2011 - 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. +# +#------------------------------------------------------------------------------ + +#include + +/* + +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 ab57bbd567..c1f717e5bd 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.
-# Portions copyright (c) 2010, Apple Inc. 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 = 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.
+# Portions copyright (c) 2010, Apple Inc. 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 = 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 d1f815828d..b5e9fd8e90 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 e634d39b9e..3be0237a36 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.
-# Portions copyright (c) 2010, Apple Inc. 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 = 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.
+# Portions copyright (c) 2010, Apple Inc. 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 = 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 2d33664f7d..4aa886182f 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 f8a76528f1..02836ca281 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 f575a35f05..5ec7fef3a6 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 4037b77941..a48d94eef4 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 02778a807f..b6090431fd 100644 --- a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc +++ b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc @@ -1,357 +1,357 @@ -# -# 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 { - - 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-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 { + + 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 + diff --git a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf index b669947125..a88818ecbd 100644 --- a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf +++ b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf @@ -1,245 +1,245 @@ -# -# 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 -# -################################################################################ - -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, 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 +# +################################################################################ + +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 + } diff --git a/ArmPlatformPkg/ArmPlatformPkg.fdf b/ArmPlatformPkg/ArmPlatformPkg.fdf index d829d4043e..be7dfa1879 100644 --- a/ArmPlatformPkg/ArmPlatformPkg.fdf +++ b/ArmPlatformPkg/ArmPlatformPkg.fdf @@ -1,302 +1,302 @@ -# -# 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 -# -################################################################################ - -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 -# -################################################################################ - -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, 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 +# +################################################################################ + +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 +# +################################################################################ + +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 + } diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf b/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf index 558e304f52..70fc87bcf5 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 -# -################################################################################ - -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 +# +################################################################################ + +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 a5fb26a327..77d48acce1 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 -#include -#include -#include -#include - -#include -#include - -#include - -#include - -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 +#include +#include +#include +#include + +#include +#include + +#include + +#include + +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 10dcef92ad..033c9d7ea0 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 -#include -#include -#include -#include - -#include -#include - -#include - -/** - 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 +#include +#include +#include +#include + +#include +#include + +#include + +/** + 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 9a68da96ac..48dd960cf6 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 fda59de7fd..b44e868c04 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 b45c20b5b0..e1a735345e 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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-RTSM-A15.fdf b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf index 4be620c3f3..c961897d00 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 -# -################################################################################ - -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 +# +################################################################################ + +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 4718c18595..58170490ac 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 -# -################################################################################ - -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 +# +################################################################################ + +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 f20db58d6a..a255c40b3e 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 b7e7b37000..862a51aaf1 100644 --- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c +++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c @@ -1,214 +1,214 @@ -/** @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 -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include - -#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; -} - +/** @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 +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include + +#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 69ffd45fdf..f055608abc 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 -#include -#include -#include - -#include - -#include - -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 +#include +#include +#include + +#include + +#include + +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 f3e8cafc0f..cb6376f65e 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 ce9bc8b271..228a0fb0f8 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 -#include -#include -#include -#include - -#include -#include - -#include - -/** - 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 +#include +#include +#include +#include + +#include +#include + +#include + +/** + 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 4a1e056af0..ff8476718f 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 4ae6301603..92df56cd57 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 -#include -#include -#include - -#include -#include - -#include - -/** - 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 +#include +#include +#include + +#include +#include + +#include + +/** + 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 3dfa756ddb..8d4f52c52e 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 73a17fb818..6a1814e095 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 45af92126b..af227d5e65 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 c9b6a98c2c..2440ea99cf 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 a471eb2602..f858317550 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include - -#include - -/** - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include + +#include + +/** + 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 3965e211ec..8dbd1c869b 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# 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.inf b/ArmPlatformPkg/Bds/Bds.inf index 164e2ae526..5027041211 100644 --- a/ArmPlatformPkg/Bds/Bds.inf +++ b/ArmPlatformPkg/Bds/Bds.inf @@ -1,75 +1,75 @@ -#/** @file -# -# Component description file for Bds module -# -# Copyright (c) 2011-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. -# -#**/ - - -[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.PcdPlatformBootTimeOut - gArmPlatformTokenSpaceGuid.PcdDefaultConInPaths - gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths - -[Depex] - TRUE +#/** @file +# +# Component description file for Bds module +# +# Copyright (c) 2011-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. +# +#**/ + + +[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.PcdPlatformBootTimeOut + gArmPlatformTokenSpaceGuid.PcdDefaultConInPaths + gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths + +[Depex] + TRUE diff --git a/ArmPlatformPkg/Bds/BdsHelper.c b/ArmPlatformPkg/Bds/BdsHelper.c index 28d02c6620..459ebc39fc 100644 --- a/ArmPlatformPkg/Bds/BdsHelper.c +++ b/ArmPlatformPkg/Bds/BdsHelper.c @@ -1,317 +1,317 @@ -/** @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 - ) -{ - 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; - } -} - +/** @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 + ) +{ + 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/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c index 3c267df4da..e998a195ff 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.
- This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include - -#include - -#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, 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. + + **/ + +#include +#include +#include +#include +#include +#include + +#include + +#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; +} diff --git a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c index 229d2a6aa2..34a56b3d8d 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.
- This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include - -#include - -#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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include + +#include + +#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 a267a538cd..5387e53c4a 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 d4dabeaefe..21fceac1dc 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + +#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 8464a98fd1..d1506c7217 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include + +#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; WordIndexRestoreTPL (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; WordIndexRestoreTPL (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 a284c151a9..959c0c1905 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - -#include -#include - -#include -#include -#include -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + +#include +#include + +#include +#include +#include +#include + +#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 d32f0f79dd..97c66008f6 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 29de964829..0c138a5ab2 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#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-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. + + --*/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#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; +} diff --git a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c index cb811d89d6..ff05662b88 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 b5adda3a89..49284d0a07 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 71b7a32d6d..839d34d414 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.
- Copyright (c) 2011 - 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. - -**/ - - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#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.
+ Copyright (c) 2011 - 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. + +**/ + + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#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 405563b86f..8e87adcf07 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 5b78b2b3f4..d1da60b5ac 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 ffcd501aae..5ec35188c9 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 d68acd83b3..8c1c29de6c 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.
- This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 1bf936ff78..ae941839f0 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 0227ced454..268b6da5c0 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 7414b10050..f61036840d 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 02ef1ea832..b1a080c00a 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 9f2de60a4a..7bbd966470 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 -// -// The protocols, PPI and GUID defintions for this module -// -#include -#include -#include - -#include - -/** - 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 +// +// The protocols, PPI and GUID defintions for this module +// +#include +#include +#include + +#include + +/** + 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 32f1eb5088..ece8064903 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 3c59bcc390..39a0cc7f73 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -/* 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +/* 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 278138759f..511d0f69de 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 -#include -#include -#include -#include -#include - -#include - -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 +#include +#include +#include +#include +#include + +#include + +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 f2284ce4ca..a0835d25f9 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 63aa3199fe..df3e12944d 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 -#include -#include -#include -#include -#include - -// 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 +#include +#include +#include +#include +#include + +// 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 a14f933221..8eea9d3821 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 563e405f66..47430e302b 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 -#include -#include -#include -#include -#include - -#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 +#include +#include +#include +#include +#include + +#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 42d903f3d6..978ba33369 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 -#include -#include -#include -#include -#include - -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 +#include +#include +#include +#include +#include + +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/ArmPlatformLibNull.c b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c index 235eb673f7..f3a7efcae0 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 -#include - -#include - - -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 +#include + +#include + + +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/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c b/ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c index c548d8b3f9..1a83882030 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 -#include -#include - -/** - 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 +#include +#include + +/** + 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/DebugSecExtraActionLib/DebugSecExtraActionLib.inf b/ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf index 2962ffe5d8..26afb34b23 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/PL011SerialPortLib/PL011SerialPortLib.c b/ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c index 7ccd09bd48..20e8882713 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.
- 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. - -**/ - -#include - -#include -#include -#include -#include - -#include - - -/** - - 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.
+ 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. + +**/ + +#include + +#include +#include +#include +#include + +#include + + +/** + + 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/SP804TimerLib/SP804TimerLib.c b/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c index fcaa23edde..a042dac9a3 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.
- 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 - -#include -#include -#include -#include -#include -#include - -#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.
+ 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 + +#include +#include +#include +#include +#include +#include + +#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 0928cae53b..d9bce48b93 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 8c8d610883..fb77e4db5d 100755 --- a/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf +++ b/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf @@ -1,66 +1,66 @@ -#/** @file -# -# Copyright (c) 2011, 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. -# -#**/ - -[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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 01f9359522..5cddeccb68 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/Scripts/Ds5/build_report.py b/ArmPlatformPkg/Scripts/Ds5/build_report.py index 3805c0b43b..e59230090f 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/edk2_debugger.py b/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py index 71e5a3ccd5..87e82b68d6 100644 --- a/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py +++ b/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py @@ -1,217 +1,217 @@ -# -# 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('= 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-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('= 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 diff --git a/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py b/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py index c4e02ece24..a13d1433eb 100644 --- a/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py +++ b/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py @@ -1,301 +1,301 @@ -# -# 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(">= 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-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(">= 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()) diff --git a/ArmPlatformPkg/Scripts/Ds5/system_table.py b/ArmPlatformPkg/Scripts/Ds5/system_table.py index f489e466ad..8dec591e63 100644 --- a/ArmPlatformPkg/Scripts/Ds5/system_table.py +++ b/ArmPlatformPkg/Scripts/Ds5/system_table.py @@ -1,129 +1,129 @@ -# -# 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("= 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(" -#include -#include -#include -#include -#include - -#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 +#include +#include +#include +#include +#include + +#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/BeagleBoardPkg/BeagleBoardPkg.dec b/BeagleBoardPkg/BeagleBoardPkg.dec index a6ee2740bb..496442a627 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.
-# -# This program and the accompanying materials are licensed and made available under -# the terms and conditions of the BSD License which accompanies this distribution. -# The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials are licensed and made available under +# the terms and conditions of the BSD License which accompanies this distribution. +# The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 ff4c556872..4e58f36042 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 -#include -#include -#include - -#include -#include - -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 +#include +#include +#include + +#include +#include + +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 e076500b81..7ca98c2bbb 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 2f9a3202e3..7634ee174c 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include +#include + +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 8627442eea..df96e8b756 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4256b0e99b..193004a8e8 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 a3fc192c2f..7fc4ec12d4 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 fa4cdcc497..9426ca3337 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include - - - -//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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include + + + +//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 03b4ba29fb..44c44fb0fc 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.
- Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_H__ -#define __EBL_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -// -// 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.
+ Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_H__ +#define __EBL_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// +// 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 8862f3d1ec..e1a4c225e6 100644 --- a/EmbeddedPkg/EmbeddedPkg.dsc +++ b/EmbeddedPkg/EmbeddedPkg.dsc @@ -1,262 +1,262 @@ -#/** @file -# Embedded Package -# -# -# Copyright (c) 2007, Intel Corporation. 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 = 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 742de505ca..8a13cc8a19 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - - -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: - - - - - - - - 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: - " \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', "\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), - " \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 entires larger than sizeof (gXferLibraryBuffer) here if - // needed by breaking up into N packets - // " (fixed size) - // - // But right now we just skip any entry that is too big - } - } - } - } - } - } - - - gXferObjectReadResponse ('l', "\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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + + +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: + + + + + + + + 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: + " \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', "\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), + " \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 entires larger than sizeof (gXferLibraryBuffer) here if + // needed by breaking up into N packets + // " (fixed size) + // + // But right now we just skip any entry that is too big + } + } + } + } + } + } + + + gXferObjectReadResponse ('l', "\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 ac04d7b9a5..5f15420f02 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 442faea023..a6aceaef99 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -// -// 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +// +// 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 8fb8610877..2df967a52a 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -// -// 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +// +// 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 6a363e0002..1b9769509b 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 badaf21361..6e876dd26a 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 c00d04f4d4..f760f8e2af 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.
- Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_ADD_EXTERNAL_COMMAND_LIB_H__ -#define __EBL_ADD_EXTERNAL_COMMAND_LIB_H__ - -#include -#include - - -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.
+ Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_ADD_EXTERNAL_COMMAND_LIB_H__ +#define __EBL_ADD_EXTERNAL_COMMAND_LIB_H__ + +#include +#include + + +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 8974463c8c..5c21d05f00 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.
- Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_LIB_H__ -#define __EBL_LIB_H__ - -#include -#include - - -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.
+ Portions copyright (c) 2008 - 2009, Apple Inc. 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 __EBL_LIB_H__ +#define __EBL_LIB_H__ + +#include +#include + + +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 c72973b753..9292cf9b0f 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + + +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 55800b9fc5..6e8eeb4e6f 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 444d7e2885..6144513a86 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -/** - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +/** + 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 74f5e4c58c..a12847ca94 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 -#include - -/** - 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 +#include + +/** + 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 1ce5a8f3bf..a7809b27b3 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 17188f04aa..603dc5ed86 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 97a9a8bd9d..77ea7ad034 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 6e7a8b3973..3b7c37102d 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 73f49759a5..85fe324c4d 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 -#include - -#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 +#include + +#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 d35b8692c6..6cc311fe73 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 -#include - -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 +#include + +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 7ee5609c5b..7fab09bad6 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 1429c37f29..03258751c0 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 3fd8e92dcd..52e343997d 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 0edd5d018d..3b0f6a1c71 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include - -#include -#include - - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include + +#include +#include + + +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 b0d6e80aea..4d66bacb81 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 5e0f9ca117..83a3b7841f 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.
-Portions copyright (c) 2008 - 2009, Apple Inc. 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. - -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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -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 : for example fs1:\ or ROOT:\. -Return TRUE if the 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 -@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.
+Portions copyright (c) 2008 - 2009, Apple Inc. 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. + +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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +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 : for example fs1:\ or ROOT:\. +Return TRUE if the 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 +@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 e56833ae9b..151fcb2ab0 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 -#include - -#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 +#include + +#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 f72d13b1d1..f00a8991d4 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 -#include - -#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 +#include + +#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 95fdbeadd4..9ae6b5ecc5 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 -#include - -#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 +#include + +#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 878a775a7b..1d95a73ec1 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 -#include - -#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 +#include + +#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 e6c3ceee8c..a49793d936 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 -#include - -#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 ""; - else if (errval == 0) - return ""; - else if (errval > -FDT_ERRTABSIZE) { - const char *s = fdt_errtable[-errval].str; - - if (s) - return s; - } - - return ""; -} +/* + * 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 +#include + +#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 ""; + else if (errval == 0) + return ""; + else if (errval > -FDT_ERRTABSIZE) { + const char *s = fdt_errtable[-errval].str; + + if (s) + return s; + } + + return ""; +} diff --git a/EmbeddedPkg/Library/FdtLib/fdt_sw.c b/EmbeddedPkg/Library/FdtLib/fdt_sw.c index 55ebebf1eb..240fabc554 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 -#include - -#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 +#include + +#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 6025fa1fe8..e009a88f51 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 -#include - -#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 +#include + +#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 381133ba81..15456110a3 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 - -#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 + +#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 f8c4e296ca..9c3cc3ce3c 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 c133073f4b..c70fb92482 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.
-// -// This program and the accompanying materials -// are licensed and made available under the terms and conditions of the BSD License -// which accompanies this distribution. The full text of the license may be found at -// http://opensource.org/licenses/bsd-license.php -// -// 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.
+// +// This program and the accompanying materials +// are licensed and made available under the terms and conditions of the BSD License +// which accompanies this distribution. The full text of the license may be found at +// http://opensource.org/licenses/bsd-license.php +// +// 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 e6aabf940a..f22a19dded 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 2d0570e3dc..44c82f3472 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include +/** @file + Private include file for GDB stub + + Copyright (c) 2008 - 2009, Apple Inc. 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 __GCC_DEBUG_AGENT_INTERNAL__ +#define __GCC_DEBUG_AGENT_INTERNAL__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include - -#include -#include - -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 +#include + +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 96a1a596f3..4e4350a0f2 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 - -// -// 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 4897a8a969..8e8ccaee38 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 a92a1de52e..320dddfc25 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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 9f9e9c7d44..bf4f80f4e4 100644 --- a/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c +++ b/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c @@ -17,11 +17,11 @@ #include #include -// -// 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 1ba976780b..fea8f43687 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 75d28a7257..9e4cdd002e 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + + +#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 77fe32898b..d637277d2a 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +#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 e46cafec3b..4cc974f1a9 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -// -// 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +// +// 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 f898808deb..8d60d5ab5d 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include - -#include -#include -#include -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include + +#include +#include +#include +#include + +#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 b88d9abf5c..ce0d13257c 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 446c56b39d..375cb49421 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 a7dad5e329..81f4ac761b 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4a21fb4952..9deceea9c1 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/Omap35xxPkg/Flash/Flash.c b/Omap35xxPkg/Flash/Flash.c index 0056acd6b9..c63e0a3395 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 9bfdba5d03..46ec4db9e1 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#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 1dfd5bcffb..4f12a27485 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 33786aeeee..c64e6be7bb 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include - -#include - -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include + +#include + +#include + +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 c20346a4c0..2069d2d734 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 0dc4468c91..f13b733796 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 4192275157..80e5e0d2cb 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 1cf99eb036..4d37815764 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 242c325331..5db9a07972 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 94822d453c..e45a0f23b5 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 6cdd5f5114..6943d303ec 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 61e1bf5c08..31d4d5ea64 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 9d1036d0dc..774d873015 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 1b3e734d6a..5bebe6c509 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 d23156cf08..1588e1d4d9 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 cd639e306d..3a297d0a98 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 5067aaafca..d66da8dc04 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 9cc17ebf32..5d64cafc57 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 cd708d9793..20df2319e1 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 38c84dd88c..9541e7e902 100644 --- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c +++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c @@ -1,445 +1,445 @@ -/** @file - - Copyright (c) 2011, 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. - - **/ - -#include -#include -#include -#include -#include -#include - -#include - -#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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include + +#include + +#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 6c20575cfe..e30a679d84 100644 --- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c +++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c @@ -1,403 +1,403 @@ -/** @file - - Copyright (c) 2011, 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. - -**/ - -#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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 39e69478a1..520e28e670 100644 --- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h +++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h @@ -1,157 +1,157 @@ -/** @file - - Copyright (c) 2011, 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 __OMAP3_DSS_GRAPHICS__ -#define __OMAP3_DSS_GRAPHICS__ - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include -#include - -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.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +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 f595bb39ed..ac026f4356 100644 --- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf +++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf @@ -1,52 +1,52 @@ -#/** @file -# -# Copyright (c) 2011, 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. -# -#**/ - -[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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 76c13d5527..b3da7366a9 100755 --- a/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c +++ b/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c @@ -13,23 +13,23 @@ **/ #include -#include -#include -#include +#include +#include +#include #include -#include +#include -#include +#include 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 e1685b58ab..551aee5385 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 b306355d5f..54247e42e6 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include -#include -#include -#include -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include +#include +#include +#include +#include +#include + +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 7e949c2f9d..3ab26bb90d 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 4356853bbc..d94ddf9867 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 e1d5c9ca1c..0b9c70bc57 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 - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - - -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 + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + + +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 c62257df7e..7c4911c385 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 786bc88273..7d4e22f524 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 2cda5679be..e19607bae0 100644 --- a/Omap35xxPkg/MMCHSDxe/MMCHS.h +++ b/Omap35xxPkg/MMCHSDxe/MMCHS.h @@ -15,28 +15,28 @@ #ifndef _MMCHS_H_ #define _MMCHS_H_ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include -#include -#include - +#include +#include + #include #include -#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 0931112e95..cc753c2a21 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 17ebf8d708..0cbd82bd44 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 940087f266..ec55234db2 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#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 a15b6f703d..8c95c0f2d9 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 1666a683d5..075dd6ae99 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.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 6b5528cea4..0cc0faa42c 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 7db4f330ca..2a381f2f99 100644 --- a/Omap35xxPkg/PciEmulation/PciEmulation.h +++ b/Omap35xxPkg/PciEmulation/PciEmulation.h @@ -40,7 +40,7 @@ #include #include -#include +#include diff --git a/Omap35xxPkg/PciEmulation/PciEmulation.inf b/Omap35xxPkg/PciEmulation/PciEmulation.inf index 8567b69388..ab37541795 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 86dc65c87f..3b88974ae1 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 -#include - -#include -#include -#include - -#include - -#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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 +#include + +#include +#include +#include + +#include + +#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 6a8a4e9194..5a4e43ea24 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 6b76da5070..ed19389d43 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include - -#include -#include -#include -#include - -#include -#include - -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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include + +#include +#include +#include +#include + +#include +#include + +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 d03326bd1e..5fca7a356f 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 d0ea973509..bc3d9b0aba 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.
- - This program and the accompanying materials - are licensed and made available under the terms and conditions of the BSD License - which accompanies this distribution. The full text of the license may be found at - http://opensource.org/licenses/bsd-license.php - - 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - - -// 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.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + 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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + + +// 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 6cfab77570..2c5a2f7a4a 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.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# 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.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# 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 -- cgit v1.2.3