preliminary include OcQuirks into the project with huge amount of unnecessary dependencies

Signed-off-by: Sergey Isakov <isakov-sl@bk.ru>
This commit is contained in:
Sergey Isakov 2020-07-09 22:06:48 +03:00
parent c1f2f96041
commit 620401dca6
252 changed files with 127249 additions and 3664 deletions

View File

@ -108,6 +108,7 @@
CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
#PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
NetLib|NetworkPkg/Library/DxeNetLib/DxeNetLib.inf
FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
#
# Platform
#
@ -159,7 +160,36 @@
WaveLib|Library/WaveLib/WaveLib.inf
HdaDevicesLib|Library/HdaDevicesLib/HdaDevicesLib.inf
#
# OC libs
#
OcGuardLib|Library/OcGuardLib/OcGuardLib.inf
OcAfterBootCompatLib|Library/OcAfterBootCompatLib/OcAfterBootCompatLib.inf
OcAppleBootPolicyLib|Library/OcAppleBootPolicyLib/OcAppleBootPolicyLib.inf
OcAppleChunklistLib|Library/OcAppleChunklistLib/OcAppleChunklistLib.inf
OcAppleDiskImageLib|Library/OcAppleDiskImageLib/OcAppleDiskImageLib.inf
OcAppleKeyMapLib|Library/OcAppleKeyMapLib/OcAppleKeyMapLib.inf
OcAppleKeysLib|Library/OcAppleKeysLib/OcAppleKeysLib.inf
OcAppleRamDiskLib|Library/OcAppleRamDiskLib/OcAppleRamDiskLib.inf
OcBootManagementLib|Library/OcBootManagementLib/OcBootManagementLib.inf
OcCompressionLib|Library/OcCompressionLib/OcCompressionLib.inf
OcConsoleLib|Library/OcConsoleLib/OcConsoleLib.inf
OcCpuLib|Library/OcCpuLib/OcCpuLib.inf
OcCryptoLib|Library/OcCryptoLib/OcCryptoLib.inf
OcDebugLogLib|Library/OcDebugLogLib/OcDebugLogLib.inf
OcDevicePathLib|Library/OcDevicePathLib/OcDevicePathLib.inf
OcFileLib|Library/OcFileLib/OcFileLib.inf
OcMemoryLib|Library/OcMemoryLib/OcMemoryLib.inf
OcMiscLib|Library/OcMiscLib/OcMiscLib.inf
OcOSInfoLib|Library/OcOSInfoLib/OcOSInfoLib.inf
OcRngLib|Library/OcRngLib/OcRngLib.inf
OcRtcLib|Library/OcRtcLib/OcRtcLib.inf
OcSerializeLib|Library/OcSerializeLib/OcSerializeLib.inf
OcStringLib|Library/OcStringLib/OcStringLib.inf
OcStorageLib|Library/OcStorageLib/OcStorageLib.inf
OcTemplateLib|Library/OcTemplateLib/OcTemplateLib.inf
OcXmlLib|Library/OcXmlLib/OcXmlLib.inf
MachoLib|Library/MachoLib/MachoLib.inf
DeviceTreeLib|Library/DeviceTreeLib/DeviceTreeLib.inf
@ -590,6 +620,7 @@
MemoryFix/OsxLowMemFixDrv/OsxLowMemFixDrv.inf
MemoryFix/AptioMemoryFix/AptioMemoryFix.inf
MemoryFix/OpenRuntime/OpenRuntime.inf
MemoryFix/OcQuirks/OcQuirks.inf
!ifdef DEBUG_ON_SERIAL_PORT
MemoryFix/OsxAptioFixDrv/OsxAptioFixDrv.inf {
#

View File

@ -0,0 +1,743 @@
/** @file
CPUID leaf definitions.
Provides defines for CPUID leaf indexes. Data structures are provided for
registers returned by a CPUID leaf that contain one or more bit fields.
If a register returned is a single 32-bit value, then a data structure is
not provided for that register.
Copyright (c) 2017, Advanced Micro Devices. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
**/
#ifndef __AMD_CPUID_H__
#define __AMD_CPUID_H__
/**
CPUID Signature Information
@param EAX CPUID_SIGNATURE (0x00)
@retval EAX Returns the highest value the CPUID instruction recognizes for
returning basic processor information. The value is returned is
processor specific.
@retval EBX First 4 characters of a vendor identification string.
@retval ECX Last 4 characters of a vendor identification string.
@retval EDX Middle 4 characters of a vendor identification string.
**/
///
/// @{ CPUID signature values returned by AMD processors
///
#define CPUID_SIGNATURE_AUTHENTIC_AMD_EBX SIGNATURE_32 ('A', 'u', 't', 'h')
#define CPUID_SIGNATURE_AUTHENTIC_AMD_EDX SIGNATURE_32 ('e', 'n', 't', 'i')
#define CPUID_SIGNATURE_AUTHENTIC_AMD_ECX SIGNATURE_32 ('c', 'A', 'M', 'D')
///
/// @}
///
/**
CPUID Extended Processor Signature and Features
@param EAX CPUID_EXTENDED_CPU_SIG (0x80000001)
@retval EAX Extended Family, Model, Stepping Identifiers
described by the type CPUID_AMD_EXTENDED_CPU_SIG_EAX.
@retval EBX Brand Identifier
described by the type CPUID_AMD_EXTENDED_CPU_SIG_EBX.
@retval ECX Extended Feature Identifiers
described by the type CPUID_AMD_EXTENDED_CPU_SIG_ECX.
@retval EDX Extended Feature Identifiers
described by the type CPUID_AMD_EXTENDED_CPU_SIG_EDX.
**/
/**
CPUID Extended Processor Signature and Features EAX for CPUID leaf
#CPUID_EXTENDED_CPU_SIG.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 3:0] Stepping.
///
UINT32 Stepping:4;
///
/// [Bits 7:4] Base Model.
///
UINT32 BaseModel:4;
///
/// [Bits 11:8] Base Family.
///
UINT32 BaseFamily:4;
///
/// [Bit 15:12] Reserved.
///
UINT32 Reserved1:4;
///
/// [Bits 19:16] Extended Model.
///
UINT32 ExtModel:4;
///
/// [Bits 27:20] Extended Family.
///
UINT32 ExtFamily:8;
///
/// [Bit 31:28] Reserved.
///
UINT32 Reserved2:4;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_EXTENDED_CPU_SIG_EAX;
/**
CPUID Extended Processor Signature and Features EBX for CPUID leaf
#CPUID_EXTENDED_CPU_SIG.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 27:0] Reserved.
///
UINT32 Reserved:28;
///
/// [Bit 31:28] Package Type.
///
UINT32 PkgType:4;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_EXTENDED_CPU_SIG_EBX;
/**
CPUID Extended Processor Signature and Features ECX for CPUID leaf
#CPUID_EXTENDED_CPU_SIG.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] LAHF/SAHF available in 64-bit mode.
///
UINT32 LAHF_SAHF:1;
///
/// [Bit 1] Core multi-processing legacy mode.
///
UINT32 CmpLegacy:1;
///
/// [Bit 2] Secure Virtual Mode feature.
///
UINT32 SVM:1;
///
/// [Bit 3] Extended APIC register space.
///
UINT32 ExtApicSpace:1;
///
/// [Bit 4] LOCK MOV CR0 means MOV CR8.
///
UINT32 AltMovCr8:1;
///
/// [Bit 5] LZCNT instruction support.
///
UINT32 LZCNT:1;
///
/// [Bit 6] SSE4A instruction support.
///
UINT32 SSE4A:1;
///
/// [Bit 7] Misaligned SSE Mode.
///
UINT32 MisAlignSse:1;
///
/// [Bit 8] ThreeDNow Prefetch instructions.
///
UINT32 PREFETCHW:1;
///
/// [Bit 9] OS Visible Work-around support.
///
UINT32 OSVW:1;
///
/// [Bit 10] Instruction Based Sampling.
///
UINT32 IBS:1;
///
/// [Bit 11] Extended Operation Support.
///
UINT32 XOP:1;
///
/// [Bit 12] SKINIT and STGI support.
///
UINT32 SKINIT:1;
///
/// [Bit 13] Watchdog Timer support.
///
UINT32 WDT:1;
///
/// [Bit 14] Reserved.
///
UINT32 Reserved1:1;
///
/// [Bit 15] Lightweight Profiling support.
///
UINT32 LWP:1;
///
/// [Bit 16] 4-Operand FMA instruction support.
///
UINT32 FMA4:1;
///
/// [Bit 17] Translation Cache Extension.
///
UINT32 TCE:1;
///
/// [Bit 21:18] Reserved.
///
UINT32 Reserved2:4;
///
/// [Bit 22] Topology Extensions support.
///
UINT32 TopologyExtensions:1;
///
/// [Bit 23] Core Performance Counter Extensions.
///
UINT32 PerfCtrExtCore:1;
///
/// [Bit 25:24] Reserved.
///
UINT32 Reserved3:2;
///
/// [Bit 26] Data Breakpoint Extension.
///
UINT32 DataBreakpointExtension:1;
///
/// [Bit 27] Performance Time-Stamp Counter.
///
UINT32 PerfTsc:1;
///
/// [Bit 28] L3 Performance Counter Extensions.
///
UINT32 PerfCtrExtL3:1;
///
/// [Bit 29] MWAITX and MONITORX capability.
///
UINT32 MwaitExtended:1;
///
/// [Bit 31:30] Reserved.
///
UINT32 Reserved4:2;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_EXTENDED_CPU_SIG_ECX;
/**
CPUID Extended Processor Signature and Features EDX for CPUID leaf
#CPUID_EXTENDED_CPU_SIG.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] x87 floating point unit on-chip.
///
UINT32 FPU:1;
///
/// [Bit 1] Virtual-mode enhancements.
///
UINT32 VME:1;
///
/// [Bit 2] Debugging extensions, IO breakpoints, CR4.DE.
///
UINT32 DE:1;
///
/// [Bit 3] Page-size extensions (4 MB pages).
///
UINT32 PSE:1;
///
/// [Bit 4] Time stamp counter, RDTSC/RDTSCP instructions, CR4.TSD.
///
UINT32 TSC:1;
///
/// [Bit 5] MSRs, with RDMSR and WRMSR instructions.
///
UINT32 MSR:1;
///
/// [Bit 6] Physical-address extensions (PAE).
///
UINT32 PAE:1;
///
/// [Bit 7] Machine check exception, CR4.MCE.
///
UINT32 MCE:1;
///
/// [Bit 8] CMPXCHG8B instruction.
///
UINT32 CMPXCHG8B:1;
///
/// [Bit 9] APIC exists and is enabled.
///
UINT32 APIC:1;
///
/// [Bit 10] Reserved.
///
UINT32 Reserved1:1;
///
/// [Bit 11] SYSCALL and SYSRET instructions.
///
UINT32 SYSCALL_SYSRET:1;
///
/// [Bit 12] Memory-type range registers.
///
UINT32 MTRR:1;
///
/// [Bit 13] Page global extension, CR4.PGE.
///
UINT32 PGE:1;
///
/// [Bit 14] Machine check architecture, MCG_CAP.
///
UINT32 MCA:1;
///
/// [Bit 15] Conditional move instructions, CMOV, FCOMI, FCMOV.
///
UINT32 CMOV:1;
///
/// [Bit 16] Page attribute table.
///
UINT32 PAT:1;
///
/// [Bit 17] Page-size extensions.
///
UINT32 PSE36 : 1;
///
/// [Bit 19:18] Reserved.
///
UINT32 Reserved2:2;
///
/// [Bit 20] No-execute page protection.
///
UINT32 NX:1;
///
/// [Bit 21] Reserved.
///
UINT32 Reserved3:1;
///
/// [Bit 22] AMD Extensions to MMX instructions.
///
UINT32 MmxExt:1;
///
/// [Bit 23] MMX instructions.
///
UINT32 MMX:1;
///
/// [Bit 24] FXSAVE and FXRSTOR instructions.
///
UINT32 FFSR:1;
///
/// [Bit 25] FXSAVE and FXRSTOR instruction optimizations.
///
UINT32 FFXSR:1;
///
/// [Bit 26] 1-GByte large page support.
///
UINT32 Page1GB:1;
///
/// [Bit 27] RDTSCP intructions.
///
UINT32 RDTSCP:1;
///
/// [Bit 28] Reserved.
///
UINT32 Reserved4:1;
///
/// [Bit 29] Long Mode.
///
UINT32 LM:1;
///
/// [Bit 30] 3DNow! instructions.
///
UINT32 ThreeDNow:1;
///
/// [Bit 31] AMD Extensions to 3DNow! instructions.
///
UINT32 ThreeDNowExt:1;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_EXTENDED_CPU_SIG_EDX;
/**
CPUID Linear Physical Address Size
@param EAX CPUID_VIR_PHY_ADDRESS_SIZE (0x80000008)
@retval EAX Linear/Physical Address Size described by the type
CPUID_AMD_VIR_PHY_ADDRESS_SIZE_EAX.
@retval EBX Linear/Physical Address Size described by the type
CPUID_AMD_VIR_PHY_ADDRESS_SIZE_EBX.
@retval ECX Linear/Physical Address Size described by the type
CPUID_AMD_VIR_PHY_ADDRESS_SIZE_ECX.
@retval EDX Reserved.
**/
/**
CPUID Linear Physical Address Size EAX for CPUID leaf
#CPUID_VIR_PHY_ADDRESS_SIZE.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Maximum physical byte address size in bits.
///
UINT32 PhysicalAddressBits:8;
///
/// [Bits 15:8] Maximum linear byte address size in bits.
///
UINT32 LinearAddressBits:8;
///
/// [Bits 23:16] Maximum guest physical byte address size in bits.
///
UINT32 GuestPhysAddrSize:8;
///
/// [Bit 31:24] Reserved.
///
UINT32 Reserved:8;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_VIR_PHY_ADDRESS_SIZE_EAX;
/**
CPUID Linear Physical Address Size EBX for CPUID leaf
#CPUID_VIR_PHY_ADDRESS_SIZE.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 0] Clear Zero Instruction.
///
UINT32 CLZERO:1;
///
/// [Bits 1] Instructions retired count support.
///
UINT32 IRPerf:1;
///
/// [Bits 2] Restore error pointers for XSave instructions.
///
UINT32 XSaveErPtr:1;
///
/// [Bit 31:3] Reserved.
///
UINT32 Reserved:29;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_VIR_PHY_ADDRESS_SIZE_EBX;
/**
CPUID Linear Physical Address Size ECX for CPUID leaf
#CPUID_VIR_PHY_ADDRESS_SIZE.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Number of threads - 1.
///
UINT32 NC:8;
///
/// [Bit 11:8] Reserved.
///
UINT32 Reserved1:4;
///
/// [Bits 15:12] APIC ID size.
///
UINT32 ApicIdCoreIdSize:4;
///
/// [Bits 17:16] Performance time-stamp counter size.
///
UINT32 PerfTscSize:2;
///
/// [Bit 31:18] Reserved.
///
UINT32 Reserved2:14;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_VIR_PHY_ADDRESS_SIZE_ECX;
/**
CPUID AMD Processor Topology
@param EAX CPUID_AMD_PROCESSOR_TOPOLOGY (0x8000001E)
@retval EAX Extended APIC ID described by the type
CPUID_AMD_PROCESSOR_TOPOLOGY_EAX.
@retval EBX Core Indentifiers described by the type
CPUID_AMD_PROCESSOR_TOPOLOGY_EBX.
@retval ECX Node Indentifiers described by the type
CPUID_AMD_PROCESSOR_TOPOLOGY_ECX.
@retval EDX Reserved.
**/
#define CPUID_AMD_PROCESSOR_TOPOLOGY 0x8000001E
/**
CPUID AMD Processor Topology EAX for CPUID leaf
#CPUID_AMD_PROCESSOR_TOPOLOGY.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 31:0] Extended APIC Id.
///
UINT32 ExtendedApicId;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_PROCESSOR_TOPOLOGY_EAX;
/**
CPUID AMD Processor Topology EBX for CPUID leaf
#CPUID_AMD_PROCESSOR_TOPOLOGY.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Core Id.
///
UINT32 CoreId:8;
///
/// [Bits 15:8] Threads per core.
///
UINT32 ThreadsPerCore:8;
///
/// [Bit 31:16] Reserved.
///
UINT32 Reserved:16;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_PROCESSOR_TOPOLOGY_EBX;
/**
CPUID AMD Processor Topology ECX for CPUID leaf
#CPUID_AMD_PROCESSOR_TOPOLOGY.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Node Id.
///
UINT32 NodeId:8;
///
/// [Bits 10:8] Nodes per processor.
///
UINT32 NodesPerProcessor:3;
///
/// [Bit 31:11] Reserved.
///
UINT32 Reserved:21;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_AMD_PROCESSOR_TOPOLOGY_ECX;
/**
CPUID Memory Encryption Information
@param EAX CPUID_MEMORY_ENCRYPTION_INFO (0x8000001F)
@retval EAX Returns the memory encryption feature support status.
@retval EBX If memory encryption feature is present then return
the page table bit number used to enable memory encryption support
and reducing of physical address space in bits.
@retval ECX Returns number of encrypted guest supported simultaneously.
@retval EDX Returns minimum SEV enabled and SEV disabled ASID.
<b>Example usage</b>
@code
UINT32 Eax;
UINT32 Ebx;
UINT32 Ecx;
UINT32 Edx;
AsmCpuid (CPUID_MEMORY_ENCRYPTION_INFO, &Eax, &Ebx, &Ecx, &Edx);
@endcode
**/
#define CPUID_MEMORY_ENCRYPTION_INFO 0x8000001F
/**
CPUID Memory Encryption support information EAX for CPUID leaf
#CPUID_MEMORY_ENCRYPTION_INFO.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] Secure Memory Encryption (Sme) Support
///
UINT32 SmeBit:1;
///
/// [Bit 1] Secure Encrypted Virtualization (Sev) Support
///
UINT32 SevBit:1;
///
/// [Bit 2] Page flush MSR support
///
UINT32 PageFlushMsrBit:1;
///
/// [Bit 3] Encrypted state support
///
UINT32 SevEsBit:1;
///
/// [Bit 31:4] Reserved
///
UINT32 ReservedBits:28;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_MEMORY_ENCRYPTION_INFO_EAX;
/**
CPUID Memory Encryption support information EBX for CPUID leaf
#CPUID_MEMORY_ENCRYPTION_INFO.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 5:0] Page table bit number used to enable memory encryption
///
UINT32 PtePosBits:6;
///
/// [Bit 11:6] Reduction of system physical address space bits when
/// memory encryption is enabled
///
UINT32 ReducedPhysBits:5;
///
/// [Bit 31:12] Reserved
///
UINT32 ReservedBits:21;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_MEMORY_ENCRYPTION_INFO_EBX;
/**
CPUID Memory Encryption support information ECX for CPUID leaf
#CPUID_MEMORY_ENCRYPTION_INFO.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 31:0] Number of encrypted guest supported simultaneously
///
UINT32 NumGuests;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_MEMORY_ENCRYPTION_INFO_ECX;
/**
CPUID Memory Encryption support information EDX for CPUID leaf
#CPUID_MEMORY_ENCRYPTION_INFO.
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 31:0] Minimum SEV enabled, SEV-ES disabled ASID
///
UINT32 MinAsid;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
} CPUID_MEMORY_ENCRYPTION_INFO_EDX;
#endif

View File

@ -0,0 +1,62 @@
/** @file
MSR Definitions.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2017, Advanced Micro Devices. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
**/
#ifndef __FAM17_MSR_H__
#define __FAM17_MSR_H__
/**
Secure Encrypted Virtualization (SEV) status register
**/
#define MSR_SEV_STATUS 0xc0010131
/**
MSR information returned for #MSR_SEV_STATUS
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] Secure Encrypted Virtualization (Sev) is enabled
///
UINT32 SevBit:1;
///
/// [Bit 1] Secure Encrypted Virtualization Encrypted State (SevEs) is enabled
///
UINT32 SevEsBit:1;
UINT32 Reserved:30;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_SEV_STATUS_REGISTER;
#endif

View File

@ -0,0 +1,29 @@
/** @file
MSR Definitions.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2017, Advanced Micro Devices. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
AMD64 Architecture Programming Manaul volume 2, March 2017, Sections 15.34
**/
#ifndef __AMD_MSR_H__
#define __AMD_MSR_H__
#include <Register/ArchitecturalMsr.h>
#include <Register/Amd/Fam17Msr.h>
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
/** @file
MSR Definitions.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Chapter 35.
**/
#ifndef __MSR_H__
#define __MSR_H__
#include <Register/ArchitecturalMsr.h>
#include <Register/Msr/Core2Msr.h>
#include <Register/Msr/AtomMsr.h>
#include <Register/Msr/SilvermontMsr.h>
#include <Register/Msr/GoldmontMsr.h>
#include <Register/Msr/NehalemMsr.h>
#include <Register/Msr/Xeon5600Msr.h>
#include <Register/Msr/XeonE7Msr.h>
#include <Register/Msr/SandyBridgeMsr.h>
#include <Register/Msr/IvyBridgeMsr.h>
#include <Register/Msr/HaswellMsr.h>
#include <Register/Msr/HaswellEMsr.h>
#include <Register/Msr/BroadwellMsr.h>
#include <Register/Msr/XeonDMsr.h>
#include <Register/Msr/SkylakeMsr.h>
#include <Register/Msr/XeonPhiMsr.h>
#include <Register/Msr/Pentium4Msr.h>
#include <Register/Msr/CoreMsr.h>
#include <Register/Msr/PentiumMMsr.h>
#include <Register/Msr/P6Msr.h>
#include <Register/Msr/PentiumMsr.h>
#endif

View File

@ -0,0 +1,790 @@
/** @file
MSR Definitions for the Intel(R) Atom(TM) Processor Family.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.3.
**/
#ifndef __ATOM_MSR_H__
#define __ATOM_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Intel(R) Atom(TM) Processor Family?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_ATOM_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x06 && \
( \
DisplayModel == 0x1C || \
DisplayModel == 0x26 || \
DisplayModel == 0x27 || \
DisplayModel == 0x35 || \
DisplayModel == 0x36 \
) \
)
/**
Shared. Model Specific Platform ID (R).
@param ECX MSR_ATOM_PLATFORM_ID (0x00000017)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_PLATFORM_ID_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_PLATFORM_ID_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_PLATFORM_ID_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_PLATFORM_ID);
@endcode
@note MSR_ATOM_PLATFORM_ID is defined as MSR_PLATFORM_ID in SDM.
**/
#define MSR_ATOM_PLATFORM_ID 0x00000017
/**
MSR information returned for MSR index #MSR_ATOM_PLATFORM_ID
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:8;
///
/// [Bits 12:8] Maximum Qualified Ratio (R) The maximum allowed bus ratio.
///
UINT32 MaximumQualifiedRatio:5;
UINT32 Reserved2:19;
UINT32 Reserved3:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_PLATFORM_ID_REGISTER;
/**
Shared. Processor Hard Power-On Configuration (R/W) Enables and disables
processor features; (R) indicates current processor configuration.
@param ECX MSR_ATOM_EBL_CR_POWERON (0x0000002A)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_EBL_CR_POWERON_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_EBL_CR_POWERON_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_EBL_CR_POWERON_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_EBL_CR_POWERON);
AsmWriteMsr64 (MSR_ATOM_EBL_CR_POWERON, Msr.Uint64);
@endcode
@note MSR_ATOM_EBL_CR_POWERON is defined as MSR_EBL_CR_POWERON in SDM.
**/
#define MSR_ATOM_EBL_CR_POWERON 0x0000002A
/**
MSR information returned for MSR index #MSR_ATOM_EBL_CR_POWERON
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:1;
///
/// [Bit 1] Data Error Checking Enable (R/W) 1 = Enabled; 0 = Disabled
/// Always 0.
///
UINT32 DataErrorCheckingEnable:1;
///
/// [Bit 2] Response Error Checking Enable (R/W) 1 = Enabled; 0 = Disabled
/// Always 0.
///
UINT32 ResponseErrorCheckingEnable:1;
///
/// [Bit 3] AERR# Drive Enable (R/W) 1 = Enabled; 0 = Disabled Always 0.
///
UINT32 AERR_DriveEnable:1;
///
/// [Bit 4] BERR# Enable for initiator bus requests (R/W) 1 = Enabled; 0 =
/// Disabled Always 0.
///
UINT32 BERR_Enable:1;
UINT32 Reserved2:1;
UINT32 Reserved3:1;
///
/// [Bit 7] BINIT# Driver Enable (R/W) 1 = Enabled; 0 = Disabled Always 0.
///
UINT32 BINIT_DriverEnable:1;
UINT32 Reserved4:1;
///
/// [Bit 9] Execute BIST (R/O) 1 = Enabled; 0 = Disabled.
///
UINT32 ExecuteBIST:1;
///
/// [Bit 10] AERR# Observation Enabled (R/O) 1 = Enabled; 0 = Disabled
/// Always 0.
///
UINT32 AERR_ObservationEnabled:1;
UINT32 Reserved5:1;
///
/// [Bit 12] BINIT# Observation Enabled (R/O) 1 = Enabled; 0 = Disabled
/// Always 0.
///
UINT32 BINIT_ObservationEnabled:1;
UINT32 Reserved6:1;
///
/// [Bit 14] 1 MByte Power on Reset Vector (R/O) 1 = 1 MByte; 0 = 4 GBytes.
///
UINT32 ResetVector:1;
UINT32 Reserved7:1;
///
/// [Bits 17:16] APIC Cluster ID (R/O) Always 00B.
///
UINT32 APICClusterID:2;
UINT32 Reserved8:2;
///
/// [Bits 21:20] Symmetric Arbitration ID (R/O) Always 00B.
///
UINT32 SymmetricArbitrationID:2;
///
/// [Bits 26:22] Integer Bus Frequency Ratio (R/O).
///
UINT32 IntegerBusFrequencyRatio:5;
UINT32 Reserved9:5;
UINT32 Reserved10:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_EBL_CR_POWERON_REGISTER;
/**
Unique. Last Branch Record n From IP (R/W) One of eight pairs of last branch
record registers on the last branch record stack. The From_IP part of the
stack contains pointers to the source instruction . See also: - Last Branch
Record Stack TOS at 1C9H - Section 17.5.
@param ECX MSR_ATOM_LASTBRANCH_n_FROM_IP
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_LASTBRANCH_0_FROM_IP);
AsmWriteMsr64 (MSR_ATOM_LASTBRANCH_0_FROM_IP, Msr);
@endcode
@note MSR_ATOM_LASTBRANCH_0_FROM_IP is defined as MSR_LASTBRANCH_0_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_1_FROM_IP is defined as MSR_LASTBRANCH_1_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_2_FROM_IP is defined as MSR_LASTBRANCH_2_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_3_FROM_IP is defined as MSR_LASTBRANCH_3_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_4_FROM_IP is defined as MSR_LASTBRANCH_4_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_5_FROM_IP is defined as MSR_LASTBRANCH_5_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_6_FROM_IP is defined as MSR_LASTBRANCH_6_FROM_IP in SDM.
MSR_ATOM_LASTBRANCH_7_FROM_IP is defined as MSR_LASTBRANCH_7_FROM_IP in SDM.
@{
**/
#define MSR_ATOM_LASTBRANCH_0_FROM_IP 0x00000040
#define MSR_ATOM_LASTBRANCH_1_FROM_IP 0x00000041
#define MSR_ATOM_LASTBRANCH_2_FROM_IP 0x00000042
#define MSR_ATOM_LASTBRANCH_3_FROM_IP 0x00000043
#define MSR_ATOM_LASTBRANCH_4_FROM_IP 0x00000044
#define MSR_ATOM_LASTBRANCH_5_FROM_IP 0x00000045
#define MSR_ATOM_LASTBRANCH_6_FROM_IP 0x00000046
#define MSR_ATOM_LASTBRANCH_7_FROM_IP 0x00000047
/// @}
/**
Unique. Last Branch Record n To IP (R/W) One of eight pairs of last branch
record registers on the last branch record stack. The To_IP part of the
stack contains pointers to the destination instruction.
@param ECX MSR_ATOM_LASTBRANCH_n_TO_IP
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_LASTBRANCH_0_TO_IP);
AsmWriteMsr64 (MSR_ATOM_LASTBRANCH_0_TO_IP, Msr);
@endcode
@note MSR_ATOM_LASTBRANCH_0_TO_IP is defined as MSR_LASTBRANCH_0_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_1_TO_IP is defined as MSR_LASTBRANCH_1_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_2_TO_IP is defined as MSR_LASTBRANCH_2_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_3_TO_IP is defined as MSR_LASTBRANCH_3_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_4_TO_IP is defined as MSR_LASTBRANCH_4_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_5_TO_IP is defined as MSR_LASTBRANCH_5_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_6_TO_IP is defined as MSR_LASTBRANCH_6_TO_IP in SDM.
MSR_ATOM_LASTBRANCH_7_TO_IP is defined as MSR_LASTBRANCH_7_TO_IP in SDM.
@{
**/
#define MSR_ATOM_LASTBRANCH_0_TO_IP 0x00000060
#define MSR_ATOM_LASTBRANCH_1_TO_IP 0x00000061
#define MSR_ATOM_LASTBRANCH_2_TO_IP 0x00000062
#define MSR_ATOM_LASTBRANCH_3_TO_IP 0x00000063
#define MSR_ATOM_LASTBRANCH_4_TO_IP 0x00000064
#define MSR_ATOM_LASTBRANCH_5_TO_IP 0x00000065
#define MSR_ATOM_LASTBRANCH_6_TO_IP 0x00000066
#define MSR_ATOM_LASTBRANCH_7_TO_IP 0x00000067
/// @}
/**
Shared. Scalable Bus Speed(RO) This field indicates the intended scalable
bus clock speed for processors based on Intel Atom microarchitecture:.
@param ECX MSR_ATOM_FSB_FREQ (0x000000CD)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_FSB_FREQ_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_FSB_FREQ_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_FSB_FREQ_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_FSB_FREQ);
@endcode
@note MSR_ATOM_FSB_FREQ is defined as MSR_FSB_FREQ in SDM.
**/
#define MSR_ATOM_FSB_FREQ 0x000000CD
/**
MSR information returned for MSR index #MSR_ATOM_FSB_FREQ
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 2:0] - Scalable Bus Speed
///
/// Atom Processor Family
/// ---------------------
/// 111B: 083 MHz (FSB 333)
/// 101B: 100 MHz (FSB 400)
/// 001B: 133 MHz (FSB 533)
/// 011B: 167 MHz (FSB 667)
///
/// 133.33 MHz should be utilized if performing calculation with
/// System Bus Speed when encoding is 001B.
/// 166.67 MHz should be utilized if performing calculation with
/// System Bus Speed when
/// encoding is 011B.
///
UINT32 ScalableBusSpeed:3;
UINT32 Reserved1:29;
UINT32 Reserved2:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_FSB_FREQ_REGISTER;
/**
Shared.
@param ECX MSR_ATOM_BBL_CR_CTL3 (0x0000011E)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_BBL_CR_CTL3_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_BBL_CR_CTL3_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_BBL_CR_CTL3_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_BBL_CR_CTL3);
AsmWriteMsr64 (MSR_ATOM_BBL_CR_CTL3, Msr.Uint64);
@endcode
@note MSR_ATOM_BBL_CR_CTL3 is defined as MSR_BBL_CR_CTL3 in SDM.
**/
#define MSR_ATOM_BBL_CR_CTL3 0x0000011E
/**
MSR information returned for MSR index #MSR_ATOM_BBL_CR_CTL3
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] L2 Hardware Enabled (RO) 1 = If the L2 is hardware-enabled 0 =
/// Indicates if the L2 is hardware-disabled.
///
UINT32 L2HardwareEnabled:1;
UINT32 Reserved1:7;
///
/// [Bit 8] L2 Enabled. (R/W) 1 = L2 cache has been initialized 0 =
/// Disabled (default) Until this bit is set the processor will not
/// respond to the WBINVD instruction or the assertion of the FLUSH# input.
///
UINT32 L2Enabled:1;
UINT32 Reserved2:14;
///
/// [Bit 23] L2 Not Present (RO) 1. = L2 Present 2. = L2 Not Present.
///
UINT32 L2NotPresent:1;
UINT32 Reserved3:8;
UINT32 Reserved4:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_BBL_CR_CTL3_REGISTER;
/**
Shared.
@param ECX MSR_ATOM_PERF_STATUS (0x00000198)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_PERF_STATUS_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_PERF_STATUS_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_PERF_STATUS_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_PERF_STATUS);
AsmWriteMsr64 (MSR_ATOM_PERF_STATUS, Msr.Uint64);
@endcode
@note MSR_ATOM_PERF_STATUS is defined as MSR_PERF_STATUS in SDM.
**/
#define MSR_ATOM_PERF_STATUS 0x00000198
/**
MSR information returned for MSR index #MSR_ATOM_PERF_STATUS
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 15:0] Current Performance State Value.
///
UINT32 CurrentPerformanceStateValue:16;
UINT32 Reserved1:16;
UINT32 Reserved2:8;
///
/// [Bits 44:40] Maximum Bus Ratio (R/O) Indicates maximum bus ratio
/// configured for the processor.
///
UINT32 MaximumBusRatio:5;
UINT32 Reserved3:19;
} Bits;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_PERF_STATUS_REGISTER;
/**
Shared.
@param ECX MSR_ATOM_THERM2_CTL (0x0000019D)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_THERM2_CTL_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_THERM2_CTL_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_THERM2_CTL_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_THERM2_CTL);
AsmWriteMsr64 (MSR_ATOM_THERM2_CTL, Msr.Uint64);
@endcode
@note MSR_ATOM_THERM2_CTL is defined as MSR_THERM2_CTL in SDM.
**/
#define MSR_ATOM_THERM2_CTL 0x0000019D
/**
MSR information returned for MSR index #MSR_ATOM_THERM2_CTL
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:16;
///
/// [Bit 16] TM_SELECT (R/W) Mode of automatic thermal monitor: 1. =
/// Thermal Monitor 1 (thermally-initiated on-die modulation of the
/// stop-clock duty cycle) 2. = Thermal Monitor 2 (thermally-initiated
/// frequency transitions) If bit 3 of the IA32_MISC_ENABLE register is
/// cleared, TM_SELECT has no effect. Neither TM1 nor TM2 are enabled.
///
UINT32 TM_SELECT:1;
UINT32 Reserved2:15;
UINT32 Reserved3:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_THERM2_CTL_REGISTER;
/**
Unique. Enable Misc. Processor Features (R/W) Allows a variety of processor
functions to be enabled and disabled.
@param ECX MSR_ATOM_IA32_MISC_ENABLE (0x000001A0)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_IA32_MISC_ENABLE_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_IA32_MISC_ENABLE_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_IA32_MISC_ENABLE_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_IA32_MISC_ENABLE);
AsmWriteMsr64 (MSR_ATOM_IA32_MISC_ENABLE, Msr.Uint64);
@endcode
@note MSR_ATOM_IA32_MISC_ENABLE is defined as IA32_MISC_ENABLE in SDM.
**/
#define MSR_ATOM_IA32_MISC_ENABLE 0x000001A0
/**
MSR information returned for MSR index #MSR_ATOM_IA32_MISC_ENABLE
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] Fast-Strings Enable See Table 35-2.
///
UINT32 FastStrings:1;
UINT32 Reserved1:2;
///
/// [Bit 3] Unique. Automatic Thermal Control Circuit Enable (R/W) See
/// Table 35-2. Default value is 0.
///
UINT32 AutomaticThermalControlCircuit:1;
UINT32 Reserved2:3;
///
/// [Bit 7] Shared. Performance Monitoring Available (R) See Table 35-2.
///
UINT32 PerformanceMonitoring:1;
UINT32 Reserved3:1;
UINT32 Reserved4:1;
///
/// [Bit 10] Shared. FERR# Multiplexing Enable (R/W) 1 = FERR# asserted by
/// the processor to indicate a pending break event within the processor 0
/// = Indicates compatible FERR# signaling behavior This bit must be set
/// to 1 to support XAPIC interrupt model usage.
///
UINT32 FERR:1;
///
/// [Bit 11] Shared. Branch Trace Storage Unavailable (RO) See Table 35-2.
///
UINT32 BTS:1;
///
/// [Bit 12] Shared. Processor Event Based Sampling Unavailable (RO) See
/// Table 35-2.
///
UINT32 PEBS:1;
///
/// [Bit 13] Shared. TM2 Enable (R/W) When this bit is set (1) and the
/// thermal sensor indicates that the die temperature is at the
/// pre-determined threshold, the Thermal Monitor 2 mechanism is engaged.
/// TM2 will reduce the bus to core ratio and voltage according to the
/// value last written to MSR_THERM2_CTL bits 15:0.
/// When this bit is clear (0, default), the processor does not change
/// the VID signals or the bus to core ratio when the processor enters a
/// thermally managed state. The BIOS must enable this feature if the
/// TM2 feature flag (CPUID.1:ECX[8]) is set; if the TM2 feature flag is
/// not set, this feature is not supported and BIOS must not alter the
/// contents of the TM2 bit location. The processor is operating out of
/// specification if both this bit and the TM1 bit are set to 0.
///
UINT32 TM2:1;
UINT32 Reserved5:2;
///
/// [Bit 16] Shared. Enhanced Intel SpeedStep Technology Enable (R/W) See
/// Table 35-2.
///
UINT32 EIST:1;
UINT32 Reserved6:1;
///
/// [Bit 18] Shared. ENABLE MONITOR FSM (R/W) See Table 35-2.
///
UINT32 MONITOR:1;
UINT32 Reserved7:1;
///
/// [Bit 20] Shared. Enhanced Intel SpeedStep Technology Select Lock
/// (R/WO) When set, this bit causes the following bits to become
/// read-only: - Enhanced Intel SpeedStep Technology Select Lock (this
/// bit), - Enhanced Intel SpeedStep Technology Enable bit. The bit must
/// be set before an Enhanced Intel SpeedStep Technology transition is
/// requested. This bit is cleared on reset.
///
UINT32 EISTLock:1;
UINT32 Reserved8:1;
///
/// [Bit 22] Unique. Limit CPUID Maxval (R/W) See Table 35-2.
///
UINT32 LimitCpuidMaxval:1;
///
/// [Bit 23] Shared. xTPR Message Disable (R/W) See Table 35-2.
///
UINT32 xTPR_Message_Disable:1;
UINT32 Reserved9:8;
UINT32 Reserved10:2;
///
/// [Bit 34] Unique. XD Bit Disable (R/W) See Table 35-2.
///
UINT32 XD:1;
UINT32 Reserved11:29;
} Bits;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_IA32_MISC_ENABLE_REGISTER;
/**
Unique. Last Branch Record Stack TOS (R/W) Contains an index (bits 0-2)
that points to the MSR containing the most recent branch record. See
MSR_LASTBRANCH_0_FROM_IP (at 40H).
@param ECX MSR_ATOM_LASTBRANCH_TOS (0x000001C9)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_LASTBRANCH_TOS);
AsmWriteMsr64 (MSR_ATOM_LASTBRANCH_TOS, Msr);
@endcode
@note MSR_ATOM_LASTBRANCH_TOS is defined as MSR_LASTBRANCH_TOS in SDM.
**/
#define MSR_ATOM_LASTBRANCH_TOS 0x000001C9
/**
Unique. Last Exception Record From Linear IP (R) Contains a pointer to the
last branch instruction that the processor executed prior to the last
exception that was generated or the last interrupt that was handled.
@param ECX MSR_ATOM_LER_FROM_LIP (0x000001DD)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_LER_FROM_LIP);
@endcode
@note MSR_ATOM_LER_FROM_LIP is defined as MSR_LER_FROM_LIP in SDM.
**/
#define MSR_ATOM_LER_FROM_LIP 0x000001DD
/**
Unique. Last Exception Record To Linear IP (R) This area contains a pointer
to the target of the last branch instruction that the processor executed
prior to the last exception that was generated or the last interrupt that
was handled.
@param ECX MSR_ATOM_LER_TO_LIP (0x000001DE)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_LER_TO_LIP);
@endcode
@note MSR_ATOM_LER_TO_LIP is defined as MSR_LER_TO_LIP in SDM.
**/
#define MSR_ATOM_LER_TO_LIP 0x000001DE
/**
Unique. See Table 35-2. See Section 18.4.4, "Processor Event Based Sampling
(PEBS).".
@param ECX MSR_ATOM_PEBS_ENABLE (0x000003F1)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_ATOM_PEBS_ENABLE_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_ATOM_PEBS_ENABLE_REGISTER.
<b>Example usage</b>
@code
MSR_ATOM_PEBS_ENABLE_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_ATOM_PEBS_ENABLE);
AsmWriteMsr64 (MSR_ATOM_PEBS_ENABLE, Msr.Uint64);
@endcode
@note MSR_ATOM_PEBS_ENABLE is defined as MSR_PEBS_ENABLE in SDM.
**/
#define MSR_ATOM_PEBS_ENABLE 0x000003F1
/**
MSR information returned for MSR index #MSR_ATOM_PEBS_ENABLE
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] Enable PEBS on IA32_PMC0. (R/W).
///
UINT32 Enable:1;
UINT32 Reserved1:31;
UINT32 Reserved2:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_ATOM_PEBS_ENABLE_REGISTER;
/**
Package. Package C2 Residency Note: C-state values are processor specific
C-state code names, unrelated to MWAIT extension C-state parameters or ACPI
C-States. Package. Package C2 Residency Counter. (R/O) Time that this
package is in processor-specific C2 states since last reset. Counts at 1 Mhz
frequency.
@param ECX MSR_ATOM_PKG_C2_RESIDENCY (0x000003F8)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_PKG_C2_RESIDENCY);
AsmWriteMsr64 (MSR_ATOM_PKG_C2_RESIDENCY, Msr);
@endcode
@note MSR_ATOM_PKG_C2_RESIDENCY is defined as MSR_PKG_C2_RESIDENCY in SDM.
**/
#define MSR_ATOM_PKG_C2_RESIDENCY 0x000003F8
/**
Package. Package C4 Residency Note: C-state values are processor specific
C-state code names, unrelated to MWAIT extension C-state parameters or ACPI
C-States. Package. Package C4 Residency Counter. (R/O) Time that this
package is in processor-specific C4 states since last reset. Counts at 1 Mhz
frequency.
@param ECX MSR_ATOM_PKG_C4_RESIDENCY (0x000003F9)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_PKG_C4_RESIDENCY);
AsmWriteMsr64 (MSR_ATOM_PKG_C4_RESIDENCY, Msr);
@endcode
@note MSR_ATOM_PKG_C4_RESIDENCY is defined as MSR_PKG_C4_RESIDENCY in SDM.
**/
#define MSR_ATOM_PKG_C4_RESIDENCY 0x000003F9
/**
Package. Package C6 Residency Note: C-state values are processor specific
C-state code names, unrelated to MWAIT extension C-state parameters or ACPI
C-States. Package. Package C6 Residency Counter. (R/O) Time that this
package is in processor-specific C6 states since last reset. Counts at 1 Mhz
frequency.
@param ECX MSR_ATOM_PKG_C6_RESIDENCY (0x000003FA)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_ATOM_PKG_C6_RESIDENCY);
AsmWriteMsr64 (MSR_ATOM_PKG_C6_RESIDENCY, Msr);
@endcode
@note MSR_ATOM_PKG_C6_RESIDENCY is defined as MSR_PKG_C6_RESIDENCY in SDM.
**/
#define MSR_ATOM_PKG_C6_RESIDENCY 0x000003FA
#endif

View File

@ -0,0 +1,306 @@
/** @file
MSR Definitions for Intel processors based on the Broadwell microarchitecture.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.13.
**/
#ifndef __BROADWELL_MSR_H__
#define __BROADWELL_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Intel processors based on the Broadwell microarchitecture?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_BROADWELL_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x06 && \
( \
DisplayModel == 0x3D || \
DisplayModel == 0x47 || \
DisplayModel == 0x4F || \
DisplayModel == 0x56 \
) \
)
/**
Thread. See Table 35-2. See Section 18.4.2, "Global Counter Control
Facilities.".
@param ECX MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS (0x0000038E)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS_REGISTER.
<b>Example usage</b>
@code
MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS);
AsmWriteMsr64 (MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS, Msr.Uint64);
@endcode
@note MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS is defined as IA32_PERF_GLOBAL_STATUS in SDM.
**/
#define MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS 0x0000038E
/**
MSR information returned for MSR index #MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] Ovf_PMC0.
///
UINT32 Ovf_PMC0:1;
///
/// [Bit 1] Ovf_PMC1.
///
UINT32 Ovf_PMC1:1;
///
/// [Bit 2] Ovf_PMC2.
///
UINT32 Ovf_PMC2:1;
///
/// [Bit 3] Ovf_PMC3.
///
UINT32 Ovf_PMC3:1;
UINT32 Reserved1:28;
///
/// [Bit 32] Ovf_FixedCtr0.
///
UINT32 Ovf_FixedCtr0:1;
///
/// [Bit 33] Ovf_FixedCtr1.
///
UINT32 Ovf_FixedCtr1:1;
///
/// [Bit 34] Ovf_FixedCtr2.
///
UINT32 Ovf_FixedCtr2:1;
UINT32 Reserved2:20;
///
/// [Bit 55] Trace_ToPA_PMI. See Section 36.2.6.2, "Table of Physical
/// Addresses (ToPA).".
///
UINT32 Trace_ToPA_PMI:1;
UINT32 Reserved3:5;
///
/// [Bit 61] Ovf_Uncore.
///
UINT32 Ovf_Uncore:1;
///
/// [Bit 62] Ovf_BufDSSAVE.
///
UINT32 OvfBuf:1;
///
/// [Bit 63] CondChgd.
///
UINT32 CondChgd:1;
} Bits;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_BROADWELL_IA32_PERF_GLOBAL_STATUS_REGISTER;
/**
Core. C-State Configuration Control (R/W) Note: C-state values are processor
specific C-state code names, unrelated to MWAIT extension C-state parameters
or ACPI C-states. `See http://biosbits.org. <http://biosbits.org>`__.
@param ECX MSR_BROADWELL_PKG_CST_CONFIG_CONTROL (0x000000E2)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_BROADWELL_PKG_CST_CONFIG_CONTROL_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_BROADWELL_PKG_CST_CONFIG_CONTROL_REGISTER.
<b>Example usage</b>
@code
MSR_BROADWELL_PKG_CST_CONFIG_CONTROL_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_BROADWELL_PKG_CST_CONFIG_CONTROL);
AsmWriteMsr64 (MSR_BROADWELL_PKG_CST_CONFIG_CONTROL, Msr.Uint64);
@endcode
@note MSR_BROADWELL_PKG_CST_CONFIG_CONTROL is defined as MSR_PKG_CST_CONFIG_CONTROL in SDM.
**/
#define MSR_BROADWELL_PKG_CST_CONFIG_CONTROL 0x000000E2
/**
MSR information returned for MSR index #MSR_BROADWELL_PKG_CST_CONFIG_CONTROL
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 3:0] Package C-State Limit (R/W) Specifies the lowest
/// processor-specific C-state code name (consuming the least power) for
/// the package. The default is set as factory-configured package C-state
/// limit. The following C-state code name encodings are supported: 0000b:
/// C0/C1 (no package C-state support) 0001b: C2 0010b: C3 0011b: C6
/// 0100b: C7 0101b: C7s 0110b: C8 0111b: C9 1000b: C10.
///
UINT32 Limit:4;
UINT32 Reserved1:6;
///
/// [Bit 10] I/O MWAIT Redirection Enable (R/W).
///
UINT32 IO_MWAIT:1;
UINT32 Reserved2:4;
///
/// [Bit 15] CFG Lock (R/WO).
///
UINT32 CFGLock:1;
UINT32 Reserved3:9;
///
/// [Bit 25] C3 State Auto Demotion Enable (R/W).
///
UINT32 C3AutoDemotion:1;
///
/// [Bit 26] C1 State Auto Demotion Enable (R/W).
///
UINT32 C1AutoDemotion:1;
///
/// [Bit 27] Enable C3 Undemotion (R/W).
///
UINT32 C3Undemotion:1;
///
/// [Bit 28] Enable C1 Undemotion (R/W).
///
UINT32 C1Undemotion:1;
///
/// [Bit 29] Enable Package C-State Auto-demotion (R/W).
///
UINT32 CStateAutoDemotion:1;
///
/// [Bit 30] Enable Package C-State Undemotion (R/W).
///
UINT32 CStateUndemotion:1;
UINT32 Reserved4:1;
UINT32 Reserved5:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_BROADWELL_PKG_CST_CONFIG_CONTROL_REGISTER;
/**
Package. Maximum Ratio Limit of Turbo Mode RO if MSR_PLATFORM_INFO.[28] = 0,
RW if MSR_PLATFORM_INFO.[28] = 1.
@param ECX MSR_BROADWELL_TURBO_RATIO_LIMIT (0x000001AD)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_BROADWELL_TURBO_RATIO_LIMIT_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_BROADWELL_TURBO_RATIO_LIMIT_REGISTER.
<b>Example usage</b>
@code
MSR_BROADWELL_TURBO_RATIO_LIMIT_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_BROADWELL_TURBO_RATIO_LIMIT);
@endcode
@note MSR_BROADWELL_TURBO_RATIO_LIMIT is defined as MSR_TURBO_RATIO_LIMIT in SDM.
**/
#define MSR_BROADWELL_TURBO_RATIO_LIMIT 0x000001AD
/**
MSR information returned for MSR index #MSR_BROADWELL_TURBO_RATIO_LIMIT
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Package. Maximum Ratio Limit for 1C Maximum turbo ratio
/// limit of 1 core active.
///
UINT32 Maximum1C:8;
///
/// [Bits 15:8] Package. Maximum Ratio Limit for 2C Maximum turbo ratio
/// limit of 2 core active.
///
UINT32 Maximum2C:8;
///
/// [Bits 23:16] Package. Maximum Ratio Limit for 3C Maximum turbo ratio
/// limit of 3 core active.
///
UINT32 Maximum3C:8;
///
/// [Bits 31:24] Package. Maximum Ratio Limit for 4C Maximum turbo ratio
/// limit of 4 core active.
///
UINT32 Maximum4C:8;
///
/// [Bits 39:32] Package. Maximum Ratio Limit for 5C Maximum turbo ratio
/// limit of 5core active.
///
UINT32 Maximum5C:8;
///
/// [Bits 47:40] Package. Maximum Ratio Limit for 6C Maximum turbo ratio
/// limit of 6core active.
///
UINT32 Maximum6C:8;
UINT32 Reserved:16;
} Bits;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_BROADWELL_TURBO_RATIO_LIMIT_REGISTER;
/**
Package. PP0 Energy Status (R/O) See Section 14.9.4, "PP0/PP1 RAPL
Domains.".
@param ECX MSR_BROADWELL_PP0_ENERGY_STATUS (0x00000639)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_BROADWELL_PP0_ENERGY_STATUS);
@endcode
@note MSR_BROADWELL_PP0_ENERGY_STATUS is defined as MSR_PP0_ENERGY_STATUS in SDM.
**/
#define MSR_BROADWELL_PP0_ENERGY_STATUS 0x00000639
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,684 @@
/** @file
MSR Definitions for Pentium M Processors.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.20.
**/
#ifndef __PENTIUM_M_MSR_H__
#define __PENTIUM_M_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Pentium M Processors?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_PENTIUM_M_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x06 && \
( \
DisplayModel == 0x0D \
) \
)
/**
See Section 35.22, "MSRs in Pentium Processors.".
@param ECX MSR_PENTIUM_M_P5_MC_ADDR (0x00000000)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_P5_MC_ADDR);
AsmWriteMsr64 (MSR_PENTIUM_M_P5_MC_ADDR, Msr);
@endcode
@note MSR_PENTIUM_M_P5_MC_ADDR is defined as P5_MC_ADDR in SDM.
**/
#define MSR_PENTIUM_M_P5_MC_ADDR 0x00000000
/**
See Section 35.22, "MSRs in Pentium Processors.".
@param ECX MSR_PENTIUM_M_P5_MC_TYPE (0x00000001)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_P5_MC_TYPE);
AsmWriteMsr64 (MSR_PENTIUM_M_P5_MC_TYPE, Msr);
@endcode
@note MSR_PENTIUM_M_P5_MC_TYPE is defined as P5_MC_TYPE in SDM.
**/
#define MSR_PENTIUM_M_P5_MC_TYPE 0x00000001
/**
Processor Hard Power-On Configuration (R/W) Enables and disables processor
features. (R) Indicates current processor configuration.
@param ECX MSR_PENTIUM_M_EBL_CR_POWERON (0x0000002A)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_EBL_CR_POWERON_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_EBL_CR_POWERON_REGISTER.
<b>Example usage</b>
@code
MSR_PENTIUM_M_EBL_CR_POWERON_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_PENTIUM_M_EBL_CR_POWERON);
AsmWriteMsr64 (MSR_PENTIUM_M_EBL_CR_POWERON, Msr.Uint64);
@endcode
@note MSR_PENTIUM_M_EBL_CR_POWERON is defined as MSR_EBL_CR_POWERON in SDM.
**/
#define MSR_PENTIUM_M_EBL_CR_POWERON 0x0000002A
/**
MSR information returned for MSR index #MSR_PENTIUM_M_EBL_CR_POWERON
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:1;
///
/// [Bit 1] Data Error Checking Enable (R) 0 = Disabled Always 0 on the
/// Pentium M processor.
///
UINT32 DataErrorCheckingEnable:1;
///
/// [Bit 2] Response Error Checking Enable (R) 0 = Disabled Always 0 on
/// the Pentium M processor.
///
UINT32 ResponseErrorCheckingEnable:1;
///
/// [Bit 3] MCERR# Drive Enable (R) 0 = Disabled Always 0 on the Pentium
/// M processor.
///
UINT32 MCERR_DriveEnable:1;
///
/// [Bit 4] Address Parity Enable (R) 0 = Disabled Always 0 on the Pentium
/// M processor.
///
UINT32 AddressParityEnable:1;
UINT32 Reserved2:2;
///
/// [Bit 7] BINIT# Driver Enable (R) 1 = Enabled; 0 = Disabled Always 0 on
/// the Pentium M processor.
///
UINT32 BINIT_DriverEnable:1;
///
/// [Bit 8] Output Tri-state Enabled (R/O) 1 = Enabled; 0 = Disabled.
///
UINT32 OutputTriStateEnable:1;
///
/// [Bit 9] Execute BIST (R/O) 1 = Enabled; 0 = Disabled.
///
UINT32 ExecuteBIST:1;
///
/// [Bit 10] MCERR# Observation Enabled (R/O) 1 = Enabled; 0 = Disabled
/// Always 0 on the Pentium M processor.
///
UINT32 MCERR_ObservationEnabled:1;
UINT32 Reserved3:1;
///
/// [Bit 12] BINIT# Observation Enabled (R/O) 1 = Enabled; 0 = Disabled
/// Always 0 on the Pentium M processor.
///
UINT32 BINIT_ObservationEnabled:1;
UINT32 Reserved4:1;
///
/// [Bit 14] 1 MByte Power on Reset Vector (R/O) 1 = 1 MByte; 0 = 4 GBytes
/// Always 0 on the Pentium M processor.
///
UINT32 ResetVector:1;
UINT32 Reserved5:1;
///
/// [Bits 17:16] APIC Cluster ID (R/O) Always 00B on the Pentium M
/// processor.
///
UINT32 APICClusterID:2;
///
/// [Bit 18] System Bus Frequency (R/O) 1. = 100 MHz 2. = Reserved Always
/// 0 on the Pentium M processor.
///
UINT32 SystemBusFrequency:1;
UINT32 Reserved6:1;
///
/// [Bits 21:20] Symmetric Arbitration ID (R/O) Always 00B on the Pentium
/// M processor.
///
UINT32 SymmetricArbitrationID:2;
///
/// [Bits 26:22] Clock Frequency Ratio (R/O).
///
UINT32 ClockFrequencyRatio:5;
UINT32 Reserved7:5;
UINT32 Reserved8:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_PENTIUM_M_EBL_CR_POWERON_REGISTER;
/**
Last Branch Record n (R/W) One of 8 last branch record registers on the last
branch record stack: bits 31-0 hold the 'from' address and bits 63-32 hold
the to address. See also: - Last Branch Record Stack TOS at 1C9H - Section
17.13, "Last Branch, Interrupt, and Exception Recording (Pentium M
Processors)".
@param ECX MSR_PENTIUM_M_LASTBRANCH_n
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_LASTBRANCH_0);
AsmWriteMsr64 (MSR_PENTIUM_M_LASTBRANCH_0, Msr);
@endcode
@note MSR_PENTIUM_M_LASTBRANCH_0 is defined as MSR_LASTBRANCH_0 in SDM.
MSR_PENTIUM_M_LASTBRANCH_1 is defined as MSR_LASTBRANCH_1 in SDM.
MSR_PENTIUM_M_LASTBRANCH_2 is defined as MSR_LASTBRANCH_2 in SDM.
MSR_PENTIUM_M_LASTBRANCH_3 is defined as MSR_LASTBRANCH_3 in SDM.
MSR_PENTIUM_M_LASTBRANCH_4 is defined as MSR_LASTBRANCH_4 in SDM.
MSR_PENTIUM_M_LASTBRANCH_5 is defined as MSR_LASTBRANCH_5 in SDM.
MSR_PENTIUM_M_LASTBRANCH_6 is defined as MSR_LASTBRANCH_6 in SDM.
MSR_PENTIUM_M_LASTBRANCH_7 is defined as MSR_LASTBRANCH_7 in SDM.
@{
**/
#define MSR_PENTIUM_M_LASTBRANCH_0 0x00000040
#define MSR_PENTIUM_M_LASTBRANCH_1 0x00000041
#define MSR_PENTIUM_M_LASTBRANCH_2 0x00000042
#define MSR_PENTIUM_M_LASTBRANCH_3 0x00000043
#define MSR_PENTIUM_M_LASTBRANCH_4 0x00000044
#define MSR_PENTIUM_M_LASTBRANCH_5 0x00000045
#define MSR_PENTIUM_M_LASTBRANCH_6 0x00000046
#define MSR_PENTIUM_M_LASTBRANCH_7 0x00000047
/// @}
/**
Reserved.
@param ECX MSR_PENTIUM_M_BBL_CR_CTL (0x00000119)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_BBL_CR_CTL);
AsmWriteMsr64 (MSR_PENTIUM_M_BBL_CR_CTL, Msr);
@endcode
@note MSR_PENTIUM_M_BBL_CR_CTL is defined as MSR_BBL_CR_CTL in SDM.
**/
#define MSR_PENTIUM_M_BBL_CR_CTL 0x00000119
/**
@param ECX MSR_PENTIUM_M_BBL_CR_CTL3 (0x0000011E)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_BBL_CR_CTL3_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_BBL_CR_CTL3_REGISTER.
<b>Example usage</b>
@code
MSR_PENTIUM_M_BBL_CR_CTL3_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_PENTIUM_M_BBL_CR_CTL3);
AsmWriteMsr64 (MSR_PENTIUM_M_BBL_CR_CTL3, Msr.Uint64);
@endcode
@note MSR_PENTIUM_M_BBL_CR_CTL3 is defined as MSR_BBL_CR_CTL3 in SDM.
**/
#define MSR_PENTIUM_M_BBL_CR_CTL3 0x0000011E
/**
MSR information returned for MSR index #MSR_PENTIUM_M_BBL_CR_CTL3
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bit 0] L2 Hardware Enabled (RO) 1 = If the L2 is hardware-enabled 0 =
/// Indicates if the L2 is hardware-disabled.
///
UINT32 L2HardwareEnabled:1;
UINT32 Reserved1:4;
///
/// [Bit 5] ECC Check Enable (RO) This bit enables ECC checking on the
/// cache data bus. ECC is always generated on write cycles. 1. = Disabled
/// (default) 2. = Enabled For the Pentium M processor, ECC checking on
/// the cache data bus is always enabled.
///
UINT32 ECCCheckEnable:1;
UINT32 Reserved2:2;
///
/// [Bit 8] L2 Enabled (R/W) 1 = L2 cache has been initialized 0 =
/// Disabled (default) Until this bit is set the processor will not
/// respond to the WBINVD instruction or the assertion of the FLUSH# input.
///
UINT32 L2Enabled:1;
UINT32 Reserved3:14;
///
/// [Bit 23] L2 Not Present (RO) 1. = L2 Present 2. = L2 Not Present.
///
UINT32 L2NotPresent:1;
UINT32 Reserved4:8;
UINT32 Reserved5:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_PENTIUM_M_BBL_CR_CTL3_REGISTER;
/**
@param ECX MSR_PENTIUM_M_THERM2_CTL (0x0000019D)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_THERM2_CTL_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_THERM2_CTL_REGISTER.
<b>Example usage</b>
@code
MSR_PENTIUM_M_THERM2_CTL_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_PENTIUM_M_THERM2_CTL);
AsmWriteMsr64 (MSR_PENTIUM_M_THERM2_CTL, Msr.Uint64);
@endcode
@note MSR_PENTIUM_M_THERM2_CTL is defined as MSR_THERM2_CTL in SDM.
**/
#define MSR_PENTIUM_M_THERM2_CTL 0x0000019D
/**
MSR information returned for MSR index #MSR_PENTIUM_M_THERM2_CTL
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:16;
///
/// [Bit 16] TM_SELECT (R/W) Mode of automatic thermal monitor: 1. =
/// Thermal Monitor 1 (thermally-initiated on-die modulation of the
/// stop-clock duty cycle) 2. = Thermal Monitor 2 (thermally-initiated
/// frequency transitions) If bit 3 of the IA32_MISC_ENABLE register is
/// cleared, TM_SELECT has no effect. Neither TM1 nor TM2 will be enabled.
///
UINT32 TM_SELECT:1;
UINT32 Reserved2:15;
UINT32 Reserved3:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_PENTIUM_M_THERM2_CTL_REGISTER;
/**
Enable Miscellaneous Processor Features (R/W) Allows a variety of processor
functions to be enabled and disabled.
@param ECX MSR_PENTIUM_M_IA32_MISC_ENABLE (0x000001A0)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_IA32_MISC_ENABLE_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_PENTIUM_M_IA32_MISC_ENABLE_REGISTER.
<b>Example usage</b>
@code
MSR_PENTIUM_M_IA32_MISC_ENABLE_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_PENTIUM_M_IA32_MISC_ENABLE);
AsmWriteMsr64 (MSR_PENTIUM_M_IA32_MISC_ENABLE, Msr.Uint64);
@endcode
@note MSR_PENTIUM_M_IA32_MISC_ENABLE is defined as IA32_MISC_ENABLE in SDM.
**/
#define MSR_PENTIUM_M_IA32_MISC_ENABLE 0x000001A0
/**
MSR information returned for MSR index #MSR_PENTIUM_M_IA32_MISC_ENABLE
**/
typedef union {
///
/// Individual bit fields
///
struct {
UINT32 Reserved1:3;
///
/// [Bit 3] Automatic Thermal Control Circuit Enable (R/W) 1 = Setting
/// this bit enables the thermal control circuit (TCC) portion of the
/// Intel Thermal Monitor feature. This allows processor clocks to be
/// automatically modulated based on the processor's thermal sensor
/// operation. 0 = Disabled (default). The automatic thermal control
/// circuit enable bit determines if the thermal control circuit (TCC)
/// will be activated when the processor's internal thermal sensor
/// determines the processor is about to exceed its maximum operating
/// temperature. When the TCC is activated and TM1 is enabled, the
/// processors clocks will be forced to a 50% duty cycle. BIOS must enable
/// this feature. The bit should not be confused with the on-demand
/// thermal control circuit enable bit.
///
UINT32 AutomaticThermalControlCircuit:1;
UINT32 Reserved2:3;
///
/// [Bit 7] Performance Monitoring Available (R) 1 = Performance
/// monitoring enabled 0 = Performance monitoring disabled.
///
UINT32 PerformanceMonitoring:1;
UINT32 Reserved3:2;
///
/// [Bit 10] FERR# Multiplexing Enable (R/W) 1 = FERR# asserted by the
/// processor to indicate a pending break event within the processor 0 =
/// Indicates compatible FERR# signaling behavior This bit must be set to
/// 1 to support XAPIC interrupt model usage.
/// **Branch Trace Storage Unavailable (RO)** 1 = Processor doesn't
/// support branch trace storage (BTS) 0 = BTS is supported
///
UINT32 FERR:1;
///
/// [Bit 11] Branch Trace Storage Unavailable (RO)
/// 1 = Processor doesn't support branch trace storage (BTS)
/// 0 = BTS is supported
///
UINT32 BTS:1;
///
/// [Bit 12] Processor Event Based Sampling Unavailable (RO) 1 =
/// Processor does not support processor event based sampling (PEBS); 0 =
/// PEBS is supported. The Pentium M processor does not support PEBS.
///
UINT32 PEBS:1;
UINT32 Reserved5:3;
///
/// [Bit 16] Enhanced Intel SpeedStep Technology Enable (R/W) 1 =
/// Enhanced Intel SpeedStep Technology enabled. On the Pentium M
/// processor, this bit may be configured to be read-only.
///
UINT32 EIST:1;
UINT32 Reserved6:6;
///
/// [Bit 23] xTPR Message Disable (R/W) When set to 1, xTPR messages are
/// disabled. xTPR messages are optional messages that allow the processor
/// to inform the chipset of its priority. The default is processor
/// specific.
///
UINT32 xTPR_Message_Disable:1;
UINT32 Reserved7:8;
UINT32 Reserved8:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_PENTIUM_M_IA32_MISC_ENABLE_REGISTER;
/**
Last Branch Record Stack TOS (R/W) Contains an index (bits 0-3) that points
to the MSR containing the most recent branch record. See also: -
MSR_LASTBRANCH_0_FROM_IP (at 40H) - Section 17.13, "Last Branch, Interrupt,
and Exception Recording (Pentium M Processors)".
@param ECX MSR_PENTIUM_M_LASTBRANCH_TOS (0x000001C9)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_LASTBRANCH_TOS);
AsmWriteMsr64 (MSR_PENTIUM_M_LASTBRANCH_TOS, Msr);
@endcode
@note MSR_PENTIUM_M_LASTBRANCH_TOS is defined as MSR_LASTBRANCH_TOS in SDM.
**/
#define MSR_PENTIUM_M_LASTBRANCH_TOS 0x000001C9
/**
Debug Control (R/W) Controls how several debug features are used. Bit
definitions are discussed in the referenced section. See Section 17.13,
"Last Branch, Interrupt, and Exception Recording (Pentium M Processors).".
@param ECX MSR_PENTIUM_M_DEBUGCTLB (0x000001D9)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_DEBUGCTLB);
AsmWriteMsr64 (MSR_PENTIUM_M_DEBUGCTLB, Msr);
@endcode
@note MSR_PENTIUM_M_DEBUGCTLB is defined as MSR_DEBUGCTLB in SDM.
**/
#define MSR_PENTIUM_M_DEBUGCTLB 0x000001D9
/**
Last Exception Record To Linear IP (R) This area contains a pointer to the
target of the last branch instruction that the processor executed prior to
the last exception that was generated or the last interrupt that was
handled. See Section 17.13, "Last Branch, Interrupt, and Exception Recording
(Pentium M Processors)" and Section 17.14.2, "Last Branch and Last Exception
MSRs.".
@param ECX MSR_PENTIUM_M_LER_TO_LIP (0x000001DD)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_LER_TO_LIP);
@endcode
@note MSR_PENTIUM_M_LER_TO_LIP is defined as MSR_LER_TO_LIP in SDM.
**/
#define MSR_PENTIUM_M_LER_TO_LIP 0x000001DD
/**
Last Exception Record From Linear IP (R) Contains a pointer to the last
branch instruction that the processor executed prior to the last exception
that was generated or the last interrupt that was handled. See Section
17.13, "Last Branch, Interrupt, and Exception Recording (Pentium M
Processors)" and Section 17.14.2, "Last Branch and Last Exception MSRs.".
@param ECX MSR_PENTIUM_M_LER_FROM_LIP (0x000001DE)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_LER_FROM_LIP);
@endcode
@note MSR_PENTIUM_M_LER_FROM_LIP is defined as MSR_LER_FROM_LIP in SDM.
**/
#define MSR_PENTIUM_M_LER_FROM_LIP 0x000001DE
/**
See Section 15.3.2.1, "IA32_MCi_CTL MSRs.".
@param ECX MSR_PENTIUM_M_MC4_CTL (0x0000040C)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC4_CTL);
AsmWriteMsr64 (MSR_PENTIUM_M_MC4_CTL, Msr);
@endcode
@note MSR_PENTIUM_M_MC4_CTL is defined as MSR_MC4_CTL in SDM.
**/
#define MSR_PENTIUM_M_MC4_CTL 0x0000040C
/**
See Section 15.3.2.2, "IA32_MCi_STATUS MSRS.".
@param ECX MSR_PENTIUM_M_MC4_STATUS (0x0000040D)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC4_STATUS);
AsmWriteMsr64 (MSR_PENTIUM_M_MC4_STATUS, Msr);
@endcode
@note MSR_PENTIUM_M_MC4_STATUS is defined as MSR_MC4_STATUS in SDM.
**/
#define MSR_PENTIUM_M_MC4_STATUS 0x0000040D
/**
See Section 15.3.2.3, "IA32_MCi_ADDR MSRs." The MSR_MC4_ADDR register is
either not implemented or contains no address if the ADDRV flag in the
MSR_MC4_STATUS register is clear. When not implemented in the processor, all
reads and writes to this MSR will cause a general-protection exception.
@param ECX MSR_PENTIUM_M_MC4_ADDR (0x0000040E)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC4_ADDR);
AsmWriteMsr64 (MSR_PENTIUM_M_MC4_ADDR, Msr);
@endcode
@note MSR_PENTIUM_M_MC4_ADDR is defined as MSR_MC4_ADDR in SDM.
**/
#define MSR_PENTIUM_M_MC4_ADDR 0x0000040E
/**
See Section 15.3.2.1, "IA32_MCi_CTL MSRs.".
@param ECX MSR_PENTIUM_M_MC3_CTL (0x00000410)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC3_CTL);
AsmWriteMsr64 (MSR_PENTIUM_M_MC3_CTL, Msr);
@endcode
@note MSR_PENTIUM_M_MC3_CTL is defined as MSR_MC3_CTL in SDM.
**/
#define MSR_PENTIUM_M_MC3_CTL 0x00000410
/**
See Section 15.3.2.2, "IA32_MCi_STATUS MSRS.".
@param ECX MSR_PENTIUM_M_MC3_STATUS (0x00000411)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC3_STATUS);
AsmWriteMsr64 (MSR_PENTIUM_M_MC3_STATUS, Msr);
@endcode
@note MSR_PENTIUM_M_MC3_STATUS is defined as MSR_MC3_STATUS in SDM.
**/
#define MSR_PENTIUM_M_MC3_STATUS 0x00000411
/**
See Section 15.3.2.3, "IA32_MCi_ADDR MSRs." The MSR_MC3_ADDR register is
either not implemented or contains no address if the ADDRV flag in the
MSR_MC3_STATUS register is clear. When not implemented in the processor, all
reads and writes to this MSR will cause a general-protection exception.
@param ECX MSR_PENTIUM_M_MC3_ADDR (0x00000412)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_M_MC3_ADDR);
AsmWriteMsr64 (MSR_PENTIUM_M_MC3_ADDR, Msr);
@endcode
@note MSR_PENTIUM_M_MC3_ADDR is defined as MSR_MC3_ADDR in SDM.
**/
#define MSR_PENTIUM_M_MC3_ADDR 0x00000412
#endif

View File

@ -0,0 +1,145 @@
/** @file
MSR Definitions for Pentium Processors.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.22.
**/
#ifndef __PENTIUM_MSR_H__
#define __PENTIUM_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Pentium Processors?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_PENTIUM_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x05 && \
( \
DisplayModel == 0x01 || \
DisplayModel == 0x02 || \
DisplayModel == 0x04 \
) \
)
/**
See Section 15.10.2, "Pentium Processor Machine-Check Exception Handling.".
@param ECX MSR_PENTIUM_P5_MC_ADDR (0x00000000)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_P5_MC_ADDR);
AsmWriteMsr64 (MSR_PENTIUM_P5_MC_ADDR, Msr);
@endcode
@note MSR_PENTIUM_P5_MC_ADDR is defined as P5_MC_ADDR in SDM.
**/
#define MSR_PENTIUM_P5_MC_ADDR 0x00000000
/**
See Section 15.10.2, "Pentium Processor Machine-Check Exception Handling.".
@param ECX MSR_PENTIUM_P5_MC_TYPE (0x00000001)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_P5_MC_TYPE);
AsmWriteMsr64 (MSR_PENTIUM_P5_MC_TYPE, Msr);
@endcode
@note MSR_PENTIUM_P5_MC_TYPE is defined as P5_MC_TYPE in SDM.
**/
#define MSR_PENTIUM_P5_MC_TYPE 0x00000001
/**
See Section 17.15, "Time-Stamp Counter.".
@param ECX MSR_PENTIUM_TSC (0x00000010)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_TSC);
AsmWriteMsr64 (MSR_PENTIUM_TSC, Msr);
@endcode
@note MSR_PENTIUM_TSC is defined as TSC in SDM.
**/
#define MSR_PENTIUM_TSC 0x00000010
/**
See Section 18.24.1, "Control and Event Select Register (CESR).".
@param ECX MSR_PENTIUM_CESR (0x00000011)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_CESR);
AsmWriteMsr64 (MSR_PENTIUM_CESR, Msr);
@endcode
@note MSR_PENTIUM_CESR is defined as CESR in SDM.
**/
#define MSR_PENTIUM_CESR 0x00000011
/**
Section 18.24.3, "Events Counted.".
@param ECX MSR_PENTIUM_CTRn
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_PENTIUM_CTR0);
AsmWriteMsr64 (MSR_PENTIUM_CTR0, Msr);
@endcode
@note MSR_PENTIUM_CTR0 is defined as CTR0 in SDM.
MSR_PENTIUM_CTR1 is defined as CTR1 in SDM.
@{
**/
#define MSR_PENTIUM_CTR0 0x00000012
#define MSR_PENTIUM_CTR1 0x00000013
/// @}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,203 @@
/** @file
MSR Definitions for Intel(R) Xeon(R) Processor Series 5600.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.7.
**/
#ifndef __XEON_5600_MSR_H__
#define __XEON_5600_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Intel(R) Xeon(R) Processor Series 5600?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_XEON_5600_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x06 && \
( \
DisplayModel == 0x25 || \
DisplayModel == 0x2C \
) \
)
/**
Core. AES Configuration (RW-L) Privileged post-BIOS agent must provide a #GP
handler to handle unsuccessful read of this MSR.
@param ECX MSR_XEON_5600_FEATURE_CONFIG (0x0000013C)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_XEON_5600_FEATURE_CONFIG_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_XEON_5600_FEATURE_CONFIG_REGISTER.
<b>Example usage</b>
@code
MSR_XEON_5600_FEATURE_CONFIG_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_XEON_5600_FEATURE_CONFIG);
AsmWriteMsr64 (MSR_XEON_5600_FEATURE_CONFIG, Msr.Uint64);
@endcode
@note MSR_XEON_5600_FEATURE_CONFIG is defined as MSR_FEATURE_CONFIG in SDM.
**/
#define MSR_XEON_5600_FEATURE_CONFIG 0x0000013C
/**
MSR information returned for MSR index #MSR_XEON_5600_FEATURE_CONFIG
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 1:0] AES Configuration (RW-L) Upon a successful read of this
/// MSR, the configuration of AES instruction set availability is as
/// follows: 11b: AES instructions are not available until next RESET.
/// otherwise, AES instructions are available. Note, AES instruction set
/// is not available if read is unsuccessful. If the configuration is not
/// 01b, AES instruction can be mis-configured if a privileged agent
/// unintentionally writes 11b.
///
UINT32 AESConfiguration:2;
UINT32 Reserved1:30;
UINT32 Reserved2:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_XEON_5600_FEATURE_CONFIG_REGISTER;
/**
Thread. Offcore Response Event Select Register (R/W).
@param ECX MSR_XEON_5600_OFFCORE_RSP_1 (0x000001A7)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_5600_OFFCORE_RSP_1);
AsmWriteMsr64 (MSR_XEON_5600_OFFCORE_RSP_1, Msr);
@endcode
@note MSR_XEON_5600_OFFCORE_RSP_1 is defined as MSR_OFFCORE_RSP_1 in SDM.
**/
#define MSR_XEON_5600_OFFCORE_RSP_1 0x000001A7
/**
Package. Maximum Ratio Limit of Turbo Mode RO if MSR_PLATFORM_INFO.[28] = 0,
RW if MSR_PLATFORM_INFO.[28] = 1.
@param ECX MSR_XEON_5600_TURBO_RATIO_LIMIT (0x000001AD)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_XEON_5600_TURBO_RATIO_LIMIT_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_XEON_5600_TURBO_RATIO_LIMIT_REGISTER.
<b>Example usage</b>
@code
MSR_XEON_5600_TURBO_RATIO_LIMIT_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_XEON_5600_TURBO_RATIO_LIMIT);
@endcode
@note MSR_XEON_5600_TURBO_RATIO_LIMIT is defined as MSR_TURBO_RATIO_LIMIT in SDM.
**/
#define MSR_XEON_5600_TURBO_RATIO_LIMIT 0x000001AD
/**
MSR information returned for MSR index #MSR_XEON_5600_TURBO_RATIO_LIMIT_REGISTER
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 7:0] Package. Maximum Ratio Limit for 1C Maximum turbo ratio
/// limit of 1 core active.
///
UINT32 Maximum1C:8;
///
/// [Bits 15:8] Package. Maximum Ratio Limit for 2C Maximum turbo ratio
/// limit of 2 core active.
///
UINT32 Maximum2C:8;
///
/// [Bits 23:16] Package. Maximum Ratio Limit for 3C Maximum turbo ratio
/// limit of 3 core active.
///
UINT32 Maximum3C:8;
///
/// [Bits 31:24] Package. Maximum Ratio Limit for 4C Maximum turbo ratio
/// limit of 4 core active.
///
UINT32 Maximum4C:8;
///
/// [Bits 39:32] Package. Maximum Ratio Limit for 5C Maximum turbo ratio
/// limit of 5 core active.
///
UINT32 Maximum5C:8;
///
/// [Bits 47:40] Package. Maximum Ratio Limit for 6C Maximum turbo ratio
/// limit of 6 core active.
///
UINT32 Maximum6C:8;
UINT32 Reserved:16;
} Bits;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_XEON_5600_TURBO_RATIO_LIMIT_REGISTER;
/**
Package. See Table 35-2.
@param ECX MSR_XEON_5600_IA32_ENERGY_PERF_BIAS (0x000001B0)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_5600_IA32_ENERGY_PERF_BIAS);
AsmWriteMsr64 (MSR_XEON_5600_IA32_ENERGY_PERF_BIAS, Msr);
@endcode
@note MSR_XEON_5600_IA32_ENERGY_PERF_BIAS is defined as IA32_ENERGY_PERF_BIAS in SDM.
**/
#define MSR_XEON_5600_IA32_ENERGY_PERF_BIAS 0x000001B0
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,373 @@
/** @file
MSR Definitions for Intel(R) Xeon(R) Processor E7 Family.
Provides defines for Machine Specific Registers(MSR) indexes. Data structures
are provided for MSRs that contain one or more bit fields. If the MSR value
returned is a single 32-bit or 64-bit value, then a data structure is not
provided for that MSR.
Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 3,
September 2016, Chapter 35 Model-Specific-Registers (MSR), Section 35.8.
**/
#ifndef __XEON_E7_MSR_H__
#define __XEON_E7_MSR_H__
#include <Register/ArchitecturalMsr.h>
/**
Is Intel(R) Xeon(R) Processor E7 Family?
@param DisplayFamily Display Family ID
@param DisplayModel Display Model ID
@retval TRUE Yes, it is.
@retval FALSE No, it isn't.
**/
#define IS_XEON_E7_PROCESSOR(DisplayFamily, DisplayModel) \
(DisplayFamily == 0x06 && \
( \
DisplayModel == 0x2F \
) \
)
/**
Core. AES Configuration (RW-L) Privileged post-BIOS agent must provide a #GP
handler to handle unsuccessful read of this MSR.
@param ECX MSR_XEON_E7_FEATURE_CONFIG (0x0000013C)
@param EAX Lower 32-bits of MSR value.
Described by the type MSR_XEON_E7_FEATURE_CONFIG_REGISTER.
@param EDX Upper 32-bits of MSR value.
Described by the type MSR_XEON_E7_FEATURE_CONFIG_REGISTER.
<b>Example usage</b>
@code
MSR_XEON_E7_FEATURE_CONFIG_REGISTER Msr;
Msr.Uint64 = AsmReadMsr64 (MSR_XEON_E7_FEATURE_CONFIG);
AsmWriteMsr64 (MSR_XEON_E7_FEATURE_CONFIG, Msr.Uint64);
@endcode
@note MSR_XEON_E7_FEATURE_CONFIG is defined as MSR_FEATURE_CONFIG in SDM.
**/
#define MSR_XEON_E7_FEATURE_CONFIG 0x0000013C
/**
MSR information returned for MSR index #MSR_XEON_E7_FEATURE_CONFIG
**/
typedef union {
///
/// Individual bit fields
///
struct {
///
/// [Bits 1:0] AES Configuration (RW-L) Upon a successful read of this
/// MSR, the configuration of AES instruction set availability is as
/// follows: 11b: AES instructions are not available until next RESET.
/// otherwise, AES instructions are available. Note, AES instruction set
/// is not available if read is unsuccessful. If the configuration is not
/// 01b, AES instruction can be mis-configured if a privileged agent
/// unintentionally writes 11b.
///
UINT32 AESConfiguration:2;
UINT32 Reserved1:30;
UINT32 Reserved2:32;
} Bits;
///
/// All bit fields as a 32-bit value
///
UINT32 Uint32;
///
/// All bit fields as a 64-bit value
///
UINT64 Uint64;
} MSR_XEON_E7_FEATURE_CONFIG_REGISTER;
/**
Thread. Offcore Response Event Select Register (R/W).
@param ECX MSR_XEON_E7_OFFCORE_RSP_1 (0x000001A7)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_OFFCORE_RSP_1);
AsmWriteMsr64 (MSR_XEON_E7_OFFCORE_RSP_1, Msr);
@endcode
@note MSR_XEON_E7_OFFCORE_RSP_1 is defined as MSR_OFFCORE_RSP_1 in SDM.
**/
#define MSR_XEON_E7_OFFCORE_RSP_1 0x000001A7
/**
Package. Reserved Attempt to read/write will cause #UD.
@param ECX MSR_XEON_E7_TURBO_RATIO_LIMIT (0x000001AD)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_TURBO_RATIO_LIMIT);
AsmWriteMsr64 (MSR_XEON_E7_TURBO_RATIO_LIMIT, Msr);
@endcode
@note MSR_XEON_E7_TURBO_RATIO_LIMIT is defined as MSR_TURBO_RATIO_LIMIT in SDM.
**/
#define MSR_XEON_E7_TURBO_RATIO_LIMIT 0x000001AD
/**
Package. Uncore C-box 8 perfmon local box control MSR.
@param ECX MSR_XEON_E7_C8_PMON_BOX_CTRL (0x00000F40)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C8_PMON_BOX_CTRL);
AsmWriteMsr64 (MSR_XEON_E7_C8_PMON_BOX_CTRL, Msr);
@endcode
@note MSR_XEON_E7_C8_PMON_BOX_CTRL is defined as MSR_C8_PMON_BOX_CTRL in SDM.
**/
#define MSR_XEON_E7_C8_PMON_BOX_CTRL 0x00000F40
/**
Package. Uncore C-box 8 perfmon local box status MSR.
@param ECX MSR_XEON_E7_C8_PMON_BOX_STATUS (0x00000F41)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C8_PMON_BOX_STATUS);
AsmWriteMsr64 (MSR_XEON_E7_C8_PMON_BOX_STATUS, Msr);
@endcode
@note MSR_XEON_E7_C8_PMON_BOX_STATUS is defined as MSR_C8_PMON_BOX_STATUS in SDM.
**/
#define MSR_XEON_E7_C8_PMON_BOX_STATUS 0x00000F41
/**
Package. Uncore C-box 8 perfmon local box overflow control MSR.
@param ECX MSR_XEON_E7_C8_PMON_BOX_OVF_CTRL (0x00000F42)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C8_PMON_BOX_OVF_CTRL);
AsmWriteMsr64 (MSR_XEON_E7_C8_PMON_BOX_OVF_CTRL, Msr);
@endcode
@note MSR_XEON_E7_C8_PMON_BOX_OVF_CTRL is defined as MSR_C8_PMON_BOX_OVF_CTRL in SDM.
**/
#define MSR_XEON_E7_C8_PMON_BOX_OVF_CTRL 0x00000F42
/**
Package. Uncore C-box 8 perfmon event select MSR.
@param ECX MSR_XEON_E7_C8_PMON_EVNT_SELn
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C8_PMON_EVNT_SEL0);
AsmWriteMsr64 (MSR_XEON_E7_C8_PMON_EVNT_SEL0, Msr);
@endcode
@note MSR_XEON_E7_C8_PMON_EVNT_SEL0 is defined as MSR_C8_PMON_EVNT_SEL0 in SDM.
MSR_XEON_E7_C8_PMON_EVNT_SEL1 is defined as MSR_C8_PMON_EVNT_SEL1 in SDM.
MSR_XEON_E7_C8_PMON_EVNT_SEL2 is defined as MSR_C8_PMON_EVNT_SEL2 in SDM.
MSR_XEON_E7_C8_PMON_EVNT_SEL3 is defined as MSR_C8_PMON_EVNT_SEL3 in SDM.
MSR_XEON_E7_C8_PMON_EVNT_SEL4 is defined as MSR_C8_PMON_EVNT_SEL4 in SDM.
MSR_XEON_E7_C8_PMON_EVNT_SEL5 is defined as MSR_C8_PMON_EVNT_SEL5 in SDM.
@{
**/
#define MSR_XEON_E7_C8_PMON_EVNT_SEL0 0x00000F50
#define MSR_XEON_E7_C8_PMON_EVNT_SEL1 0x00000F52
#define MSR_XEON_E7_C8_PMON_EVNT_SEL2 0x00000F54
#define MSR_XEON_E7_C8_PMON_EVNT_SEL3 0x00000F56
#define MSR_XEON_E7_C8_PMON_EVNT_SEL4 0x00000F58
#define MSR_XEON_E7_C8_PMON_EVNT_SEL5 0x00000F5A
/// @}
/**
Package. Uncore C-box 8 perfmon counter MSR.
@param ECX MSR_XEON_E7_C8_PMON_CTRn
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C8_PMON_CTR0);
AsmWriteMsr64 (MSR_XEON_E7_C8_PMON_CTR0, Msr);
@endcode
@note MSR_XEON_E7_C8_PMON_CTR0 is defined as MSR_C8_PMON_CTR0 in SDM.
MSR_XEON_E7_C8_PMON_CTR1 is defined as MSR_C8_PMON_CTR1 in SDM.
MSR_XEON_E7_C8_PMON_CTR2 is defined as MSR_C8_PMON_CTR2 in SDM.
MSR_XEON_E7_C8_PMON_CTR3 is defined as MSR_C8_PMON_CTR3 in SDM.
MSR_XEON_E7_C8_PMON_CTR4 is defined as MSR_C8_PMON_CTR4 in SDM.
MSR_XEON_E7_C8_PMON_CTR5 is defined as MSR_C8_PMON_CTR5 in SDM.
@{
**/
#define MSR_XEON_E7_C8_PMON_CTR0 0x00000F51
#define MSR_XEON_E7_C8_PMON_CTR1 0x00000F53
#define MSR_XEON_E7_C8_PMON_CTR2 0x00000F55
#define MSR_XEON_E7_C8_PMON_CTR3 0x00000F57
#define MSR_XEON_E7_C8_PMON_CTR4 0x00000F59
#define MSR_XEON_E7_C8_PMON_CTR5 0x00000F5B
/// @}
/**
Package. Uncore C-box 9 perfmon local box control MSR.
@param ECX MSR_XEON_E7_C9_PMON_BOX_CTRL (0x00000FC0)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C9_PMON_BOX_CTRL);
AsmWriteMsr64 (MSR_XEON_E7_C9_PMON_BOX_CTRL, Msr);
@endcode
@note MSR_XEON_E7_C9_PMON_BOX_CTRL is defined as MSR_C9_PMON_BOX_CTRL in SDM.
**/
#define MSR_XEON_E7_C9_PMON_BOX_CTRL 0x00000FC0
/**
Package. Uncore C-box 9 perfmon local box status MSR.
@param ECX MSR_XEON_E7_C9_PMON_BOX_STATUS (0x00000FC1)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C9_PMON_BOX_STATUS);
AsmWriteMsr64 (MSR_XEON_E7_C9_PMON_BOX_STATUS, Msr);
@endcode
@note MSR_XEON_E7_C9_PMON_BOX_STATUS is defined as MSR_C9_PMON_BOX_STATUS in SDM.
**/
#define MSR_XEON_E7_C9_PMON_BOX_STATUS 0x00000FC1
/**
Package. Uncore C-box 9 perfmon local box overflow control MSR.
@param ECX MSR_XEON_E7_C9_PMON_BOX_OVF_CTRL (0x00000FC2)
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C9_PMON_BOX_OVF_CTRL);
AsmWriteMsr64 (MSR_XEON_E7_C9_PMON_BOX_OVF_CTRL, Msr);
@endcode
@note MSR_XEON_E7_C9_PMON_BOX_OVF_CTRL is defined as MSR_C9_PMON_BOX_OVF_CTRL in SDM.
**/
#define MSR_XEON_E7_C9_PMON_BOX_OVF_CTRL 0x00000FC2
/**
Package. Uncore C-box 9 perfmon event select MSR.
@param ECX MSR_XEON_E7_C9_PMON_EVNT_SELn
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C9_PMON_EVNT_SEL0);
AsmWriteMsr64 (MSR_XEON_E7_C9_PMON_EVNT_SEL0, Msr);
@endcode
@note MSR_XEON_E7_C9_PMON_EVNT_SEL0 is defined as MSR_C9_PMON_EVNT_SEL0 in SDM.
MSR_XEON_E7_C9_PMON_EVNT_SEL1 is defined as MSR_C9_PMON_EVNT_SEL1 in SDM.
MSR_XEON_E7_C9_PMON_EVNT_SEL2 is defined as MSR_C9_PMON_EVNT_SEL2 in SDM.
MSR_XEON_E7_C9_PMON_EVNT_SEL3 is defined as MSR_C9_PMON_EVNT_SEL3 in SDM.
MSR_XEON_E7_C9_PMON_EVNT_SEL4 is defined as MSR_C9_PMON_EVNT_SEL4 in SDM.
MSR_XEON_E7_C9_PMON_EVNT_SEL5 is defined as MSR_C9_PMON_EVNT_SEL5 in SDM.
@{
**/
#define MSR_XEON_E7_C9_PMON_EVNT_SEL0 0x00000FD0
#define MSR_XEON_E7_C9_PMON_EVNT_SEL1 0x00000FD2
#define MSR_XEON_E7_C9_PMON_EVNT_SEL2 0x00000FD4
#define MSR_XEON_E7_C9_PMON_EVNT_SEL3 0x00000FD6
#define MSR_XEON_E7_C9_PMON_EVNT_SEL4 0x00000FD8
#define MSR_XEON_E7_C9_PMON_EVNT_SEL5 0x00000FDA
/// @}
/**
Package. Uncore C-box 9 perfmon counter MSR.
@param ECX MSR_XEON_E7_C9_PMON_CTRn
@param EAX Lower 32-bits of MSR value.
@param EDX Upper 32-bits of MSR value.
<b>Example usage</b>
@code
UINT64 Msr;
Msr = AsmReadMsr64 (MSR_XEON_E7_C9_PMON_CTR0);
AsmWriteMsr64 (MSR_XEON_E7_C9_PMON_CTR0, Msr);
@endcode
@note MSR_XEON_E7_C9_PMON_CTR0 is defined as MSR_C9_PMON_CTR0 in SDM.
MSR_XEON_E7_C9_PMON_CTR1 is defined as MSR_C9_PMON_CTR1 in SDM.
MSR_XEON_E7_C9_PMON_CTR2 is defined as MSR_C9_PMON_CTR2 in SDM.
MSR_XEON_E7_C9_PMON_CTR3 is defined as MSR_C9_PMON_CTR3 in SDM.
MSR_XEON_E7_C9_PMON_CTR4 is defined as MSR_C9_PMON_CTR4 in SDM.
MSR_XEON_E7_C9_PMON_CTR5 is defined as MSR_C9_PMON_CTR5 in SDM.
@{
**/
#define MSR_XEON_E7_C9_PMON_CTR0 0x00000FD1
#define MSR_XEON_E7_C9_PMON_CTR1 0x00000FD3
#define MSR_XEON_E7_C9_PMON_CTR2 0x00000FD5
#define MSR_XEON_E7_C9_PMON_CTR3 0x00000FD7
#define MSR_XEON_E7_C9_PMON_CTR4 0x00000FD9
#define MSR_XEON_E7_C9_PMON_CTR5 0x00000FDB
/// @}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,190 @@
/** @file
SMRAM Save State Map Definitions.
SMRAM Save State Map definitions based on contents of the
Intel(R) 64 and IA-32 Architectures Software Developer's Manual
Volume 3C, Section 34.4 SMRAM
Volume 3C, Section 34.5 SMI Handler Execution Environment
Volume 3C, Section 34.7 Managing Synchronous and Asynchronous SMIs
Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __SMRAM_SAVE_STATE_MAP_H__
#define __SMRAM_SAVE_STATE_MAP_H__
///
/// Default SMBASE address
///
#define SMM_DEFAULT_SMBASE 0x30000
///
/// Offset of SMM handler from SMBASE
///
#define SMM_HANDLER_OFFSET 0x8000
///
/// Offset of SMRAM Save State Map from SMBASE
///
#define SMRAM_SAVE_STATE_MAP_OFFSET 0xfc00
#pragma pack (1)
///
/// 32-bit SMRAM Save State Map
///
typedef struct {
UINT8 Reserved[0x200]; // 7c00h
// Padded an extra 0x200 bytes so 32-bit and 64-bit
// SMRAM Save State Maps are the same size
UINT8 Reserved1[0xf8]; // 7e00h
UINT32 SMBASE; // 7ef8h
UINT32 SMMRevId; // 7efch
UINT16 IORestart; // 7f00h
UINT16 AutoHALTRestart; // 7f02h
UINT8 Reserved2[0x9C]; // 7f08h
UINT32 IOMemAddr; // 7fa0h
UINT32 IOMisc; // 7fa4h
UINT32 _ES; // 7fa8h
UINT32 _CS; // 7fach
UINT32 _SS; // 7fb0h
UINT32 _DS; // 7fb4h
UINT32 _FS; // 7fb8h
UINT32 _GS; // 7fbch
UINT32 Reserved3; // 7fc0h
UINT32 _TR; // 7fc4h
UINT32 _DR7; // 7fc8h
UINT32 _DR6; // 7fcch
UINT32 _EAX; // 7fd0h
UINT32 _ECX; // 7fd4h
UINT32 _EDX; // 7fd8h
UINT32 _EBX; // 7fdch
UINT32 _ESP; // 7fe0h
UINT32 _EBP; // 7fe4h
UINT32 _ESI; // 7fe8h
UINT32 _EDI; // 7fech
UINT32 _EIP; // 7ff0h
UINT32 _EFLAGS; // 7ff4h
UINT32 _CR3; // 7ff8h
UINT32 _CR0; // 7ffch
} SMRAM_SAVE_STATE_MAP32;
///
/// 64-bit SMRAM Save State Map
///
typedef struct {
UINT8 Reserved1[0x1d0]; // 7c00h
UINT32 GdtBaseHiDword; // 7dd0h
UINT32 LdtBaseHiDword; // 7dd4h
UINT32 IdtBaseHiDword; // 7dd8h
UINT8 Reserved2[0xc]; // 7ddch
UINT64 IO_EIP; // 7de8h
UINT8 Reserved3[0x50]; // 7df0h
UINT32 _CR4; // 7e40h
UINT8 Reserved4[0x48]; // 7e44h
UINT32 GdtBaseLoDword; // 7e8ch
UINT32 Reserved5; // 7e90h
UINT32 IdtBaseLoDword; // 7e94h
UINT32 Reserved6; // 7e98h
UINT32 LdtBaseLoDword; // 7e9ch
UINT8 Reserved7[0x38]; // 7ea0h
UINT64 EptVmxControl; // 7ed8h
UINT32 EnEptVmxControl; // 7ee0h
UINT8 Reserved8[0x14]; // 7ee4h
UINT32 SMBASE; // 7ef8h
UINT32 SMMRevId; // 7efch
UINT16 IORestart; // 7f00h
UINT16 AutoHALTRestart; // 7f02h
UINT8 Reserved9[0x18]; // 7f04h
UINT64 _R15; // 7f1ch
UINT64 _R14;
UINT64 _R13;
UINT64 _R12;
UINT64 _R11;
UINT64 _R10;
UINT64 _R9;
UINT64 _R8;
UINT64 _RAX; // 7f5ch
UINT64 _RCX;
UINT64 _RDX;
UINT64 _RBX;
UINT64 _RSP;
UINT64 _RBP;
UINT64 _RSI;
UINT64 _RDI;
UINT64 IOMemAddr; // 7f9ch
UINT32 IOMisc; // 7fa4h
UINT32 _ES; // 7fa8h
UINT32 _CS;
UINT32 _SS;
UINT32 _DS;
UINT32 _FS;
UINT32 _GS;
UINT32 _LDTR; // 7fc0h
UINT32 _TR;
UINT64 _DR7; // 7fc8h
UINT64 _DR6;
UINT64 _RIP; // 7fd8h
UINT64 IA32_EFER; // 7fe0h
UINT64 _RFLAGS; // 7fe8h
UINT64 _CR3; // 7ff0h
UINT64 _CR0; // 7ff8h
} SMRAM_SAVE_STATE_MAP64;
///
/// Union of 32-bit and 64-bit SMRAM Save State Maps
///
typedef union {
SMRAM_SAVE_STATE_MAP32 x86;
SMRAM_SAVE_STATE_MAP64 x64;
} SMRAM_SAVE_STATE_MAP;
///
/// Minimum SMM Revision ID that supports IOMisc field in SMRAM Save State Map
///
#define SMRAM_SAVE_STATE_MIN_REV_ID_IOMISC 0x30004
///
/// SMRAM Save State Map IOMisc I/O Length Values
///
#define SMM_IO_LENGTH_BYTE 0x01
#define SMM_IO_LENGTH_WORD 0x02
#define SMM_IO_LENGTH_DWORD 0x04
///
/// SMRAM Save State Map IOMisc I/O Instruction Type Values
///
#define SMM_IO_TYPE_IN_IMMEDIATE 0x9
#define SMM_IO_TYPE_IN_DX 0x1
#define SMM_IO_TYPE_OUT_IMMEDIATE 0x8
#define SMM_IO_TYPE_OUT_DX 0x0
#define SMM_IO_TYPE_INS 0x3
#define SMM_IO_TYPE_OUTS 0x2
#define SMM_IO_TYPE_REP_INS 0x7
#define SMM_IO_TYPE_REP_OUTS 0x6
///
/// SMRAM Save State Map IOMisc structure
///
typedef union {
struct {
UINT32 SmiFlag:1;
UINT32 Length:3;
UINT32 Type:4;
UINT32 Reserved1:8;
UINT32 Port:16;
} Bits;
UINT32 Uint32;
} SMRAM_SAVE_STATE_IOMISC;
#pragma pack ()
#endif

View File

@ -0,0 +1,954 @@
/** @file
STM API definition
Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
SMI Transfer Monitor (STM) User Guide Revision 1.00
**/
#ifndef _STM_API_H_
#define _STM_API_H_
#include <Register/StmStatusCode.h>
#include <Register/StmResourceDescriptor.h>
#include <Register/ArchitecturalMsr.h>
#pragma pack (1)
/**
STM Header Structures
**/
typedef struct {
UINT32 Intel64ModeSupported :1; ///> bitfield
UINT32 EptSupported :1; ///> bitfield
UINT32 Reserved :30; ///> must be 0
} STM_FEAT;
#define STM_SPEC_VERSION_MAJOR 1
#define STM_SPEC_VERSION_MINOR 0
typedef struct {
UINT8 StmSpecVerMajor;
UINT8 StmSpecVerMinor;
///
/// Must be zero
///
UINT16 Reserved;
UINT32 StaticImageSize;
UINT32 PerProcDynamicMemorySize;
UINT32 AdditionalDynamicMemorySize;
STM_FEAT StmFeatures;
UINT32 NumberOfRevIDs;
UINT32 StmSmmRevID[1];
///
/// The total STM_HEADER should be 4K.
///
} SOFTWARE_STM_HEADER;
typedef struct {
MSEG_HEADER HwStmHdr;
SOFTWARE_STM_HEADER SwStmHdr;
} STM_HEADER;
/**
VMCALL API Numbers
API number convention: BIOS facing VMCALL interfaces have bit 16 clear
**/
/**
StmMapAddressRange enables a SMM guest to create a non-1:1 virtual to
physical mapping of an address range into the SMM guest's virtual
memory space.
@param EAX #STM_API_MAP_ADDRESS_RANGE (0x00000001)
@param EBX Low 32 bits of physical address of caller allocated
STM_MAP_ADDRESS_RANGE_DESCRIPTOR structure.
@param ECX High 32 bits of physical address of caller allocated
STM_MAP_ADDRESS_RANGE_DESCRIPTOR structure. If Intel64Mode is
clear (0), ECX must be 0.
@note All fields of STM_MAP_ADDRESS_RANGE_DESCRIPTOR are inputs only. They
are not modified by StmMapAddressRange.
@retval CF 0
No error, EAX set to STM_SUCCESS.
The memory range was mapped as requested.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_SECURITY_VIOLATION
The requested mapping contains a protected resource.
@retval EAX #ERROR_STM_CACHE_TYPE_NOT_SUPPORTED
The requested cache type could not be satisfied.
@retval EAX #ERROR_STM_PAGE_NOT_FOUND
Page count must not be zero.
@retval EAX #ERROR_STM_FUNCTION_NOT_SUPPORTED
STM supports EPT and has not implemented StmMapAddressRange().
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_MAP_ADDRESS_RANGE 0x00000001
/**
STM Map Address Range Descriptor for #STM_API_MAP_ADDRESS_RANGE VMCALL
**/
typedef struct {
UINT64 PhysicalAddress;
UINT64 VirtualAddress;
UINT32 PageCount;
UINT32 PatCacheType;
} STM_MAP_ADDRESS_RANGE_DESCRIPTOR;
/**
Define values for PatCacheType field of #STM_MAP_ADDRESS_RANGE_DESCRIPTOR
@{
**/
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_ST_UC 0x00
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_WC 0x01
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_WT 0x04
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_WP 0x05
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_WB 0x06
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_UC 0x07
#define STM_MAP_ADDRESS_RANGE_PAT_CACHE_TYPE_FOLLOW_MTRR 0xFFFFFFFF
/// @}
/**
StmUnmapAddressRange enables a SMM guest to remove mappings from its page
table.
If TXT_PROCESSOR_SMM_DESCRIPTOR.EptEnabled bit is set by the STM, BIOS can
control its own page tables. In this case, the STM implementation may
optionally return ERROR_STM_FUNCTION_NOT_SUPPORTED.
@param EAX #STM_API_UNMAP_ADDRESS_RANGE (0x00000002)
@param EBX Low 32 bits of virtual address of caller allocated
STM_UNMAP_ADDRESS_RANGE_DESCRIPTOR structure.
@param ECX High 32 bits of virtual address of caller allocated
STM_UNMAP_ADDRESS_RANGE_DESCRIPTOR structure. If Intel64Mode is
clear (0), ECX must be zero.
@retval CF 0
No error, EAX set to STM_SUCCESS. The memory range was unmapped
as requested.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_FUNCTION_NOT_SUPPORTED
STM supports EPT and has not implemented StmUnmapAddressRange().
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_UNMAP_ADDRESS_RANGE 0x00000002
/**
STM Unmap Address Range Descriptor for #STM_API_UNMAP_ADDRESS_RANGE VMCALL
**/
typedef struct {
UINT64 VirtualAddress;
UINT32 Length;
} STM_UNMAP_ADDRESS_RANGE_DESCRIPTOR;
/**
Since the normal OS environment runs with a different set of page tables than
the SMM guest, virtual mappings will certainly be different. In order to do a
guest virtual to host physical translation of an address from the normal OS
code (EIP for example), it is necessary to walk the page tables governing the
OS page mappings. Since the SMM guest has no direct access to the page tables,
it must ask the STM to do this page table walk. This is supported via the
StmAddressLookup VMCALL. All OS page table formats need to be supported,
(e.g. PAE, PSE, Intel64, EPT, etc.)
StmAddressLookup takes a CR3 value and a virtual address from the interrupted
code as input and returns the corresponding physical address. It also
optionally maps the physical address into the SMM guest's virtual address
space. This new mapping persists ONLY for the duration of the SMI and if
needed in subsequent SMIs it must be remapped. PAT cache types follow the
interrupted environment's page table.
If EPT is enabled, OS CR3 only provides guest physical address information,
but the SMM guest might also need to know the host physical address. Since
SMM does not have direct access rights to EPT (it is protected by the STM),
SMM can input InterruptedEptp to let STM help to walk through it, and output
the host physical address.
@param EAX #STM_API_ADDRESS_LOOKUP (0x00000003)
@param EBX Low 32 bits of virtual address of caller allocated
STM_ADDRESS_LOOKUP_DESCRIPTOR structure.
@param ECX High 32 bits of virtual address of caller allocated
STM_ADDRESS_LOOKUP_DESCRIPTOR structure. If Intel64Mode is
clear (0), ECX must be zero.
@retval CF 0
No error, EAX set to STM_SUCCESS. PhysicalAddress contains the
host physical address determined by walking the interrupted SMM
guest's page tables. SmmGuestVirtualAddress contains the SMM
guest's virtual mapping of the requested address.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_SECURITY_VIOLATION
The requested page was a protected page.
@retval EAX #ERROR_STM_PAGE_NOT_FOUND
The requested virtual address did not exist in the page given
page table.
@retval EAX #ERROR_STM_BAD_CR3
The CR3 input was invalid. CR3 values must be from one of the
interrupted guest, or from the interrupted guest of another
processor.
@retval EAX #ERROR_STM_PHYSICAL_OVER_4G
The resulting physical address is greater than 4G and no virtual
address was supplied. The STM could not determine what address
within the SMM guest's virtual address space to do the mapping.
STM_ADDRESS_LOOKUP_DESCRIPTOR field PhysicalAddress contains the
physical address determined by walking the interrupted
environment's page tables.
@retval EAX #ERROR_STM_VIRTUAL_SPACE_TOO_SMALL
A specific virtual mapping was requested, but
SmmGuestVirtualAddress + Length exceeds 4G and the SMI handler
is running in 32 bit mode.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_ADDRESS_LOOKUP 0x00000003
/**
STM Lookup Address Range Descriptor for #STM_API_ADDRESS_LOOKUP VMCALL
**/
typedef struct {
UINT64 InterruptedGuestVirtualAddress;
UINT32 Length;
UINT64 InterruptedCr3;
UINT64 InterruptedEptp;
UINT32 MapToSmmGuest:2;
UINT32 InterruptedCr4Pae:1;
UINT32 InterruptedCr4Pse:1;
UINT32 InterruptedIa32eMode:1;
UINT32 Reserved1:27;
UINT32 Reserved2;
UINT64 PhysicalAddress;
UINT64 SmmGuestVirtualAddress;
} STM_ADDRESS_LOOKUP_DESCRIPTOR;
/**
Define values for the MapToSmmGuest field of #STM_ADDRESS_LOOKUP_DESCRIPTOR
@{
**/
#define STM_ADDRESS_LOOKUP_DESCRIPTOR_DO_NOT_MAP 0
#define STM_ADDRESS_LOOKUP_DESCRIPTOR_ONE_TO_ONE 1
#define STM_ADDRESS_LOOKUP_DESCRIPTOR_VIRTUAL_ADDRESS_SPECIFIED 3
/// @}
/**
When returning from a protection exception (see section 6.2), the SMM guest
can instruct the STM to take one of two paths. It can either request a value
be logged to the TXT.ERRORCODE register and subsequently reset the machine
(indicating it couldn't resolve the problem), or it can request that the STM
resume the SMM guest again with the specified register state.
Unlike other VMCALL interfaces, StmReturnFromProtectionException behaves more
like a jump or an IRET instruction than a "call". It does not return directly
to the caller, but indirectly to a different location specified on the
caller's stack (see section 6.2) or not at all.
If the SMM guest STM protection exception handler itself causes a protection
exception (e.g. a single nested exception), or more than 100 un-nested
exceptions occur within the scope of a single SMI event, the STM must write
STM_CRASH_PROTECTION_EXCEPTION_FAILURE to the TXT.ERRORCODE register and
assert TXT.CMD.SYS_RESET. The reason for these restrictions is to simplify
the code requirements while still enabling a reasonable debugging capability.
@param EAX #STM_API_RETURN_FROM_PROTECTION_EXCEPTION (0x00000004)
@param EBX If 0, resume SMM guest using register state found on exception
stack. If in range 0x01..0x0F, EBX contains a BIOS error code
which the STM must record in the TXT.ERRORCODE register and
subsequently reset the system via TXT.CMD.SYS_RESET. The value
of the TXT.ERRORCODE register is calculated as follows:
TXT.ERRORCODE = (EBX & 0x0F) | STM_CRASH_BIOS_PANIC
Values 0x10..0xFFFFFFFF are reserved, do not use.
**/
#define STM_API_RETURN_FROM_PROTECTION_EXCEPTION 0x00000004
/**
VMCALL API Numbers
API number convention: MLE facing VMCALL interfaces have bit 16 set.
The STM configuration lifecycle is as follows:
1. SENTER->SINIT->MLE: MLE begins execution with SMI disabled (masked).
2. MLE invokes #STM_API_INITIALIZE_PROTECTION VMCALL to prepare STM for
setup of initial protection profile. This is done on a single CPU and
has global effect.
3. MLE invokes #STM_API_PROTECT_RESOURCE VMCALL to define the initial
protection profile. The protection profile is global across all CPUs.
4. MLE invokes #STM_API_START VMCALL to enable the STM to begin receiving
SMI events. This must be done on every logical CPU.
5. MLE may invoke #STM_API_PROTECT_RESOURCE VMCALL or
#STM_API_UNPROTECT_RESOURCE VMCALL during runtime as many times as
necessary.
6. MLE invokes #STM_API_STOP VMCALL to disable the STM. SMI is again masked
following #STM_API_STOP VMCALL.
**/
/**
StartStmVmcall() is used to configure an STM that is present in MSEG. SMIs
should remain disabled from the invocation of GETSEC[SENTER] until they are
re-enabled by StartStmVMCALL(). When StartStmVMCALL() returns, SMI is
enabled and the STM has been started and is active. Prior to invoking
StartStmVMCALL(), the MLE root should first invoke
InitializeProtectionVMCALL() followed by as many iterations of
ProtectResourceVMCALL() as necessary to establish the initial protection
profile. StartStmVmcall() must be invoked on all processor threads.
@param EAX #STM_API_START (0x00010001)
@param EDX STM configuration options. These provide the MLE with the
ability to pass configuration parameters to the STM.
@retval CF 0
No error, EAX set to STM_SUCCESS. The STM has been configured
and is now active and the guarding all requested resources.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_ALREADY_STARTED
The STM is already configured and active. STM remains active and
guarding previously enabled resource list.
@retval EAX #ERROR_STM_WITHOUT_SMX_UNSUPPORTED
The StartStmVMCALL() was invoked from VMX root mode, but outside
of SMX. This error code indicates the STM or platform does not
support the STM outside of SMX. The SMI handler remains active
and operates in legacy mode. See Appendix C
@retval EAX #ERROR_STM_UNSUPPORTED_MSR_BIT
The CPU doesn't support the MSR bit. The STM is not active.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_START (BIT16 | 1)
/**
Bit values for EDX input parameter to #STM_API_START VMCALL
@{
**/
#define STM_CONFIG_SMI_UNBLOCKING_BY_VMX_OFF BIT0
/// @}
/**
The StopStmVMCALL() is invoked by the MLE to teardown an active STM. This is
normally done as part of a full teardown of the SMX environment when the
system is being shut down. At the time the call is invoked, SMI is enabled
and the STM is active. When the call returns, the STM has been stopped and
all STM context is discarded and SMI is disabled.
@param EAX #STM_API_STOP (0x00010002)
@retval CF 0
No error, EAX set to STM_SUCCESS. The STM has been stopped and
is no longer processing SMI events. SMI is blocked.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_STOPPED
The STM was not active.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_STOP (BIT16 | 2)
/**
The ProtectResourceVMCALL() is invoked by the MLE root to request protection
of specific resources. The request is defined by a STM_RESOURCE_LIST, which
may contain more than one resource descriptor. Each resource descriptor is
processed separately by the STM. Whether or not protection for any specific
resource is granted is returned by the STM via the ReturnStatus bit in the
associated STM_RSC_DESC_HEADER.
@param EAX #STM_API_PROTECT_RESOURCE (0x00010003)
@param EBX Low 32 bits of physical address of caller allocated
STM_RESOURCE_LIST. Bits 11:0 are ignored and assumed to be zero,
making the buffer 4K aligned.
@param ECX High 32 bits of physical address of caller allocated
STM_RESOURCE_LIST.
@note All fields of STM_RESOURCE_LIST are inputs only, except for the
ReturnStatus bit. On input, the ReturnStatus bit must be clear. On
return, the ReturnStatus bit is set for each resource request granted,
and clear for each resource request denied. There are no other fields
modified by ProtectResourceVMCALL(). The STM_RESOURCE_LIST must be
contained entirely within a single 4K page.
@retval CF 0
No error, EAX set to STM_SUCCESS. The STM has successfully
merged the entire protection request into the active protection
profile. There is therefore no need to check the ReturnStatus
bits in the STM_RESOURCE_LIST.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_UNPROTECTABLE_RESOURCE
At least one of the requested resource protections intersects a
BIOS required resource. Therefore, the caller must walk through
the STM_RESOURCE_LIST to determine which of the requested
resources was not granted protection. The entire list must be
traversed since there may be multiple failures.
@retval EAX #ERROR_STM_MALFORMED_RESOURCE_LIST
The resource list could not be parsed correctly, or did not
terminate before crossing a 4K page boundary. The caller must
walk through the STM_RESOURCE_LIST to determine which of the
requested resources was not granted protection. The entire list
must be traversed since there may be multiple failures.
@retval EAX #ERROR_STM_OUT_OF_RESOURCES
The STM has encountered an internal error and cannot complete
the request.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_PROTECT_RESOURCE (BIT16 | 3)
/**
The UnProtectResourceVMCALL() is invoked by the MLE root to request that the
STM allow the SMI handler access to the specified resources.
@param EAX #STM_API_UNPROTECT_RESOURCE (0x00010004)
@param EBX Low 32 bits of physical address of caller allocated
STM_RESOURCE_LIST. Bits 11:0 are ignored and assumed to be zero,
making the buffer 4K aligned.
@param ECX High 32 bits of physical address of caller allocated
STM_RESOURCE_LIST.
@note All fields of STM_RESOURCE_LIST are inputs only, except for the
ReturnStatus bit. On input, the ReturnStatus bit must be clear. On
return, the ReturnStatus bit is set for each resource processed. For
a properly formed STM_RESOURCE_LIST, this should be all resources
listed. There are no other fields modified by
UnProtectResourceVMCALL(). The STM_RESOURCE_LIST must be contained
entirely within a single 4K page.
@retval CF 0
No error, EAX set to STM_SUCCESS. The requested resources are
not being guarded by the STM.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_MALFORMED_RESOURCE_LIST
The resource list could not be parsed correctly, or did not
terminate before crossing a 4K page boundary. The caller must
walk through the STM_RESOURCE_LIST to determine which of the
requested resources were not able to be unprotected. The entire
list must be traversed since there may be multiple failures.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_UNPROTECT_RESOURCE (BIT16 | 4)
/**
The GetBiosResourcesVMCALL() is invoked by the MLE root to request the list
of BIOS required resources from the STM.
@param EAX #STM_API_GET_BIOS_RESOURCES (0x00010005)
@param EBX Low 32 bits of physical address of caller allocated destination
buffer. Bits 11:0 are ignored and assumed to be zero, making the
buffer 4K aligned.
@param ECX High 32 bits of physical address of caller allocated destination
buffer.
@param EDX Indicates which page of the BIOS resource list to copy into the
destination buffer. The first page is indicated by 0, the second
page by 1, etc.
@retval CF 0
No error, EAX set to STM_SUCCESS. The destination buffer
contains the BIOS required resources. If the page retrieved is
the last page, EDX will be cleared to 0. If there are more pages
to retrieve, EDX is incremented to the next page index. Calling
software should iterate on GetBiosResourcesVMCALL() until EDX is
returned cleared to 0.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_PAGE_NOT_FOUND
The page index supplied in EDX input was out of range.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@retval EDX Page index of next page to read. A return of EDX=0 signifies
that the entire list has been read.
@note EDX is both an input and an output register.
@note All other registers unmodified.
**/
#define STM_API_GET_BIOS_RESOURCES (BIT16 | 5)
/**
The ManageVmcsDatabaseVMCALL() is invoked by the MLE root to add or remove an
MLE guest (including the MLE root) from the list of protected domains.
@param EAX #STM_API_MANAGE_VMCS_DATABASE (0x00010006)
@param EBX Low 32 bits of physical address of caller allocated
STM_VMCS_DATABASE_REQUEST. Bits 11:0 are ignored and assumed to
be zero, making the buffer 4K aligned.
@param ECX High 32 bits of physical address of caller allocated
STM_VMCS_DATABASE_REQUEST.
@note All fields of STM_VMCS_DATABASE_REQUEST are inputs only. They are not
modified by ManageVmcsDatabaseVMCALL().
@retval CF 0
No error, EAX set to STM_SUCCESS.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_INVALID_VMCS
Indicates a request to remove a VMCS from the database was made,
but the referenced VMCS was not found in the database.
@retval EAX #ERROR_STM_VMCS_PRESENT
Indicates a request to add a VMCS to the database was made, but
the referenced VMCS was already present in the database.
@retval EAX #ERROR_INVALID_PARAMETER
Indicates non-zero reserved field.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred
@note All other registers unmodified.
**/
#define STM_API_MANAGE_VMCS_DATABASE (BIT16 | 6)
/**
STM VMCS Database Request for #STM_API_MANAGE_VMCS_DATABASE VMCALL
**/
typedef struct {
///
/// bits 11:0 are reserved and must be 0
///
UINT64 VmcsPhysPointer;
UINT32 DomainType :4;
UINT32 XStatePolicy :2;
UINT32 DegradationPolicy :4;
///
/// Must be 0
///
UINT32 Reserved1 :22;
UINT32 AddOrRemove;
} STM_VMCS_DATABASE_REQUEST;
/**
Values for the DomainType field of #STM_VMCS_DATABASE_REQUEST
@{
**/
#define DOMAIN_UNPROTECTED 0
#define DOMAIN_DISALLOWED_IO_OUT BIT0
#define DOMAIN_DISALLOWED_IO_IN BIT1
#define DOMAIN_INTEGRITY BIT2
#define DOMAIN_CONFIDENTIALITY BIT3
#define DOMAIN_INTEGRITY_PROT_OUT_IN (DOMAIN_INTEGRITY)
#define DOMAIN_FULLY_PROT_OUT_IN (DOMAIN_CONFIDENTIALITY | DOMAIN_INTEGRITY)
#define DOMAIN_FULLY_PROT (DOMAIN_FULLY_PROT_OUT_IN | DOMAIN_DISALLOWED_IO_IN | DOMAIN_DISALLOWED_IO_OUT)
/// @}
/**
Values for the XStatePolicy field of #STM_VMCS_DATABASE_REQUEST
@{
**/
#define XSTATE_READWRITE 0x00
#define XSTATE_READONLY 0x01
#define XSTATE_SCRUB 0x03
/// @}
/**
Values for the AddOrRemove field of #STM_VMCS_DATABASE_REQUEST
@{
**/
#define STM_VMCS_DATABASE_REQUEST_ADD 1
#define STM_VMCS_DATABASE_REQUEST_REMOVE 0
/// @}
/**
InitializeProtectionVMCALL() prepares the STM for setup of the initial
protection profile which is subsequently communicated via one or more
invocations of ProtectResourceVMCALL(), prior to invoking StartStmVMCALL().
It is only necessary to invoke InitializeProtectionVMCALL() on one processor
thread. InitializeProtectionVMCALL() does not alter whether SMIs are masked
or unmasked. The STM should return back to the MLE with "Blocking by SMI" set
to 1 in the GUEST_INTERRUPTIBILITY field for the VMCS the STM created for the
MLE guest.
@param EAX #STM_API_INITIALIZE_PROTECTION (0x00010007)
@retval CF 0
No error, EAX set to STM_SUCCESS, EBX bits set to indicate STM
capabilities as defined below. The STM has set up an empty
protection profile, except for the resources that it sets up to
protect itself. The STM must not allow the SMI handler to map
any pages from the MSEG Base to the top of TSEG. The STM must
also not allow SMI handler access to those MSRs which the STM
requires for its own protection.
@retval CF 1
An error occurred, EAX holds relevant error value.
@retval EAX #ERROR_STM_ALREADY_STARTED
The STM is already configured and active. The STM remains active
and guarding the previously enabled resource list.
@retval EAX #ERROR_STM_UNPROTECTABLE
The STM determines that based on the platform configuration, the
STM is unable to protect itself. For example, the BIOS required
resource list contains memory pages in MSEG.
@retval EAX #ERROR_STM_UNSPECIFIED
An unspecified error occurred.
@note All other registers unmodified.
**/
#define STM_API_INITIALIZE_PROTECTION (BIT16 | 7)
/**
Byte granular support bits returned in EBX from #STM_API_INITIALIZE_PROTECTION
@{
**/
#define STM_RSC_BGI BIT1
#define STM_RSC_BGM BIT2
#define STM_RSC_MSR BIT3
/// @}
/**
The ManageEventLogVMCALL() is invoked by the MLE root to control the logging
feature. It consists of several sub-functions to facilitate establishment of
the log itself, configuring what events will be logged, and functions to
start, stop, and clear the log.
@param EAX #STM_API_MANAGE_EVENT_LOG (0x00010008)
@param EBX Low 32 bits of physical address of caller allocated
STM_EVENT_LOG_MANAGEMENT_REQUEST. Bits 11:0 are ignored and
assumed to be zero, making the buffer 4K aligned.
@param ECX High 32 bits of physical address of caller allocated
STM_EVENT_LOG_MANAGEMENT_REQUEST.
@retval CF=0
No error, EAX set to STM_SUCCESS.
@retval CF=1
An error occurred, EAX holds relevant error value. See subfunction
descriptions below for details.
@note All other registers unmodified.
**/
#define STM_API_MANAGE_EVENT_LOG (BIT16 | 8)
///
/// STM Event Log Management Request for #STM_API_MANAGE_EVENT_LOG VMCALL
///
typedef struct {
UINT32 SubFunctionIndex;
union {
struct {
UINT32 PageCount;
//
// number of elements is PageCount
//
UINT64 Pages[];
} LogBuffer;
//
// bitmap of EVENT_TYPE
//
UINT32 EventEnableBitmap;
} Data;
} STM_EVENT_LOG_MANAGEMENT_REQUEST;
/**
Defines values for the SubFunctionIndex field of
#STM_EVENT_LOG_MANAGEMENT_REQUEST
@{
**/
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_NEW_LOG 1
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_CONFIGURE_LOG 2
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_START_LOG 3
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_STOP_LOG 4
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_CLEAR_LOG 5
#define STM_EVENT_LOG_MANAGEMENT_REQUEST_DELETE_LOG 6
/// @}
/**
Log Entry Header
**/
typedef struct {
UINT32 EventSerialNumber;
UINT16 Type;
UINT16 Lock :1;
UINT16 Valid :1;
UINT16 ReadByMle :1;
UINT16 Wrapped :1;
UINT16 Reserved :12;
} LOG_ENTRY_HEADER;
/**
Enum values for the Type field of #LOG_ENTRY_HEADER
**/
typedef enum {
EvtLogStarted,
EvtLogStopped,
EvtLogInvalidParameterDetected,
EvtHandledProtectionException,
///
/// unhandled protection exceptions result in reset & cannot be logged
///
EvtBiosAccessToUnclaimedResource,
EvtMleResourceProtectionGranted,
EvtMleResourceProtectionDenied,
EvtMleResourceUnprotect,
EvtMleResourceUnprotectError,
EvtMleDomainTypeDegraded,
///
/// add more here
///
EvtMleMax,
///
/// Not used
///
EvtInvalid = 0xFFFFFFFF,
} EVENT_TYPE;
typedef struct {
UINT32 Reserved;
} ENTRY_EVT_LOG_STARTED;
typedef struct {
UINT32 Reserved;
} ENTRY_EVT_LOG_STOPPED;
typedef struct {
UINT32 VmcallApiNumber;
} ENTRY_EVT_LOG_INVALID_PARAM;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_LOG_HANDLED_PROTECTION_EXCEPTION;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_BIOS_ACCESS_UNCLAIMED_RSC;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_MLE_RSC_PROT_GRANTED;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_MLE_RSC_PROT_DENIED;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_MLE_RSC_UNPROT;
typedef struct {
STM_RSC Resource;
} ENTRY_EVT_MLE_RSC_UNPROT_ERROR;
typedef struct {
UINT64 VmcsPhysPointer;
UINT8 ExpectedDomainType;
UINT8 DegradedDomainType;
} ENTRY_EVT_MLE_DOMAIN_TYPE_DEGRADED;
typedef union {
ENTRY_EVT_LOG_STARTED Started;
ENTRY_EVT_LOG_STOPPED Stopped;
ENTRY_EVT_LOG_INVALID_PARAM InvalidParam;
ENTRY_EVT_LOG_HANDLED_PROTECTION_EXCEPTION HandledProtectionException;
ENTRY_EVT_BIOS_ACCESS_UNCLAIMED_RSC BiosUnclaimedRsc;
ENTRY_EVT_MLE_RSC_PROT_GRANTED MleRscProtGranted;
ENTRY_EVT_MLE_RSC_PROT_DENIED MleRscProtDenied;
ENTRY_EVT_MLE_RSC_UNPROT MleRscUnprot;
ENTRY_EVT_MLE_RSC_UNPROT_ERROR MleRscUnprotError;
ENTRY_EVT_MLE_DOMAIN_TYPE_DEGRADED MleDomainTypeDegraded;
} LOG_ENTRY_DATA;
typedef struct {
LOG_ENTRY_HEADER Hdr;
LOG_ENTRY_DATA Data;
} STM_LOG_ENTRY;
/**
Maximum STM Log Entry Size
**/
#define STM_LOG_ENTRY_SIZE 256
/**
STM Protection Exception Stack Frame Structures
**/
typedef struct {
UINT32 Rdi;
UINT32 Rsi;
UINT32 Rbp;
UINT32 Rdx;
UINT32 Rcx;
UINT32 Rbx;
UINT32 Rax;
UINT32 Cr3;
UINT32 Cr2;
UINT32 Cr0;
UINT32 VmcsExitInstructionInfo;
UINT32 VmcsExitInstructionLength;
UINT64 VmcsExitQualification;
///
/// An TXT_SMM_PROTECTION_EXCEPTION_TYPE num value
///
UINT32 ErrorCode;
UINT32 Rip;
UINT32 Cs;
UINT32 Rflags;
UINT32 Rsp;
UINT32 Ss;
} STM_PROTECTION_EXCEPTION_STACK_FRAME_IA32;
typedef struct {
UINT64 R15;
UINT64 R14;
UINT64 R13;
UINT64 R12;
UINT64 R11;
UINT64 R10;
UINT64 R9;
UINT64 R8;
UINT64 Rdi;
UINT64 Rsi;
UINT64 Rbp;
UINT64 Rdx;
UINT64 Rcx;
UINT64 Rbx;
UINT64 Rax;
UINT64 Cr8;
UINT64 Cr3;
UINT64 Cr2;
UINT64 Cr0;
UINT64 VmcsExitInstructionInfo;
UINT64 VmcsExitInstructionLength;
UINT64 VmcsExitQualification;
///
/// An TXT_SMM_PROTECTION_EXCEPTION_TYPE num value
///
UINT64 ErrorCode;
UINT64 Rip;
UINT64 Cs;
UINT64 Rflags;
UINT64 Rsp;
UINT64 Ss;
} STM_PROTECTION_EXCEPTION_STACK_FRAME_X64;
typedef union {
STM_PROTECTION_EXCEPTION_STACK_FRAME_IA32 *Ia32StackFrame;
STM_PROTECTION_EXCEPTION_STACK_FRAME_X64 *X64StackFrame;
} STM_PROTECTION_EXCEPTION_STACK_FRAME;
/**
Enum values for the ErrorCode field in
#STM_PROTECTION_EXCEPTION_STACK_FRAME_IA32 and
#STM_PROTECTION_EXCEPTION_STACK_FRAME_X64
**/
typedef enum {
TxtSmmPageViolation = 1,
TxtSmmMsrViolation,
TxtSmmRegisterViolation,
TxtSmmIoViolation,
TxtSmmPciViolation
} TXT_SMM_PROTECTION_EXCEPTION_TYPE;
/**
TXT Pocessor SMM Descriptor (PSD) structures
**/
typedef struct {
UINT64 SpeRip;
UINT64 SpeRsp;
UINT16 SpeSs;
UINT16 PageViolationException:1;
UINT16 MsrViolationException:1;
UINT16 RegisterViolationException:1;
UINT16 IoViolationException:1;
UINT16 PciViolationException:1;
UINT16 Reserved1:11;
UINT32 Reserved2;
} STM_PROTECTION_EXCEPTION_HANDLER;
typedef struct {
UINT8 ExecutionDisableOutsideSmrr:1;
UINT8 Intel64Mode:1;
UINT8 Cr4Pae : 1;
UINT8 Cr4Pse : 1;
UINT8 Reserved1 : 4;
} STM_SMM_ENTRY_STATE;
typedef struct {
UINT8 SmramToVmcsRestoreRequired : 1; ///> BIOS restore hint
UINT8 ReinitializeVmcsRequired : 1; ///> BIOS request
UINT8 Reserved2 : 6;
} STM_SMM_RESUME_STATE;
typedef struct {
UINT8 DomainType : 4; ///> STM input to BIOS on each SMI
UINT8 XStatePolicy : 2; ///> STM input to BIOS on each SMI
UINT8 EptEnabled : 1;
UINT8 Reserved3 : 1;
} STM_SMM_STATE;
#define TXT_SMM_PSD_OFFSET 0xfb00
#define TXT_PROCESSOR_SMM_DESCRIPTOR_SIGNATURE SIGNATURE_64('T', 'X', 'T', 'P', 'S', 'S', 'I', 'G')
#define TXT_PROCESSOR_SMM_DESCRIPTOR_VERSION_MAJOR 1
#define TXT_PROCESSOR_SMM_DESCRIPTOR_VERSION_MINOR 0
typedef struct {
UINT64 Signature;
UINT16 Size;
UINT8 SmmDescriptorVerMajor;
UINT8 SmmDescriptorVerMinor;
UINT32 LocalApicId;
STM_SMM_ENTRY_STATE SmmEntryState;
STM_SMM_RESUME_STATE SmmResumeState;
STM_SMM_STATE StmSmmState;
UINT8 Reserved4;
UINT16 SmmCs;
UINT16 SmmDs;
UINT16 SmmSs;
UINT16 SmmOtherSegment;
UINT16 SmmTr;
UINT16 Reserved5;
UINT64 SmmCr3;
UINT64 SmmStmSetupRip;
UINT64 SmmStmTeardownRip;
UINT64 SmmSmiHandlerRip;
UINT64 SmmSmiHandlerRsp;
UINT64 SmmGdtPtr;
UINT32 SmmGdtSize;
UINT32 RequiredStmSmmRevId;
STM_PROTECTION_EXCEPTION_HANDLER StmProtectionExceptionHandler;
UINT64 Reserved6;
UINT64 BiosHwResourceRequirementsPtr;
// extend area
UINT64 AcpiRsdp;
UINT8 PhysicalAddressBits;
} TXT_PROCESSOR_SMM_DESCRIPTOR;
#pragma pack ()
#endif

View File

@ -0,0 +1,228 @@
/** @file
STM Resource Descriptor
Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
SMI Transfer Monitor (STM) User Guide Revision 1.00
**/
#ifndef _STM_RESOURCE_DESCRIPTOR_H_
#define _STM_RESOURCE_DESCRIPTOR_H_
#pragma pack (1)
/**
STM Resource Descriptor Header
**/
typedef struct {
UINT32 RscType;
UINT16 Length;
UINT16 ReturnStatus:1;
UINT16 Reserved:14;
UINT16 IgnoreResource:1;
} STM_RSC_DESC_HEADER;
/**
Define values for the RscType field of #STM_RSC_DESC_HEADER
@{
**/
#define END_OF_RESOURCES 0
#define MEM_RANGE 1
#define IO_RANGE 2
#define MMIO_RANGE 3
#define MACHINE_SPECIFIC_REG 4
#define PCI_CFG_RANGE 5
#define TRAPPED_IO_RANGE 6
#define ALL_RESOURCES 7
#define REGISTER_VIOLATION 8
#define MAX_DESC_TYPE 8
/// @}
/**
STM Resource End Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT64 ResourceListContinuation;
} STM_RSC_END;
/**
STM Resource Memory Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT64 Base;
UINT64 Length;
UINT32 RWXAttributes:3;
UINT32 Reserved:29;
UINT32 Reserved_2;
} STM_RSC_MEM_DESC;
/**
Define values for the RWXAttributes field of #STM_RSC_MEM_DESC
@{
**/
#define STM_RSC_MEM_R 0x1
#define STM_RSC_MEM_W 0x2
#define STM_RSC_MEM_X 0x4
/// @}
/**
STM Resource I/O Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT16 Base;
UINT16 Length;
UINT32 Reserved;
} STM_RSC_IO_DESC;
/**
STM Resource MMIO Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT64 Base;
UINT64 Length;
UINT32 RWXAttributes:3;
UINT32 Reserved:29;
UINT32 Reserved_2;
} STM_RSC_MMIO_DESC;
/**
Define values for the RWXAttributes field of #STM_RSC_MMIO_DESC
@{
**/
#define STM_RSC_MMIO_R 0x1
#define STM_RSC_MMIO_W 0x2
#define STM_RSC_MMIO_X 0x4
/// @}
/**
STM Resource MSR Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT32 MsrIndex;
UINT32 KernelModeProcessing:1;
UINT32 Reserved:31;
UINT64 ReadMask;
UINT64 WriteMask;
} STM_RSC_MSR_DESC;
/**
STM PCI Device Path node used for the PciDevicePath field of
#STM_RSC_PCI_CFG_DESC
**/
typedef struct {
///
/// Must be 1, indicating Hardware Device Path
///
UINT8 Type;
///
/// Must be 1, indicating PCI
///
UINT8 Subtype;
///
/// sizeof(STM_PCI_DEVICE_PATH_NODE) which is 6
///
UINT16 Length;
UINT8 PciFunction;
UINT8 PciDevice;
} STM_PCI_DEVICE_PATH_NODE;
/**
STM Resource PCI Configuration Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT16 RWAttributes:2;
UINT16 Reserved:14;
UINT16 Base;
UINT16 Length;
UINT8 OriginatingBusNumber;
UINT8 LastNodeIndex;
STM_PCI_DEVICE_PATH_NODE PciDevicePath[1];
//STM_PCI_DEVICE_PATH_NODE PciDevicePath[LastNodeIndex + 1];
} STM_RSC_PCI_CFG_DESC;
/**
Define values for the RWAttributes field of #STM_RSC_PCI_CFG_DESC
@{
**/
#define STM_RSC_PCI_CFG_R 0x1
#define STM_RSC_PCI_CFG_W 0x2
/// @}
/**
STM Resource Trapped I/O Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT16 Base;
UINT16 Length;
UINT16 In:1;
UINT16 Out:1;
UINT16 Api:1;
UINT16 Reserved1:13;
UINT16 Reserved2;
} STM_RSC_TRAPPED_IO_DESC;
/**
STM Resource All Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
} STM_RSC_ALL_RESOURCES_DESC;
/**
STM Register Volation Descriptor
**/
typedef struct {
STM_RSC_DESC_HEADER Hdr;
UINT32 RegisterType;
UINT32 Reserved;
UINT64 ReadMask;
UINT64 WriteMask;
} STM_REGISTER_VIOLATION_DESC;
/**
Enum values for the RWAttributes field of #STM_REGISTER_VIOLATION_DESC
**/
typedef enum {
StmRegisterCr0,
StmRegisterCr2,
StmRegisterCr3,
StmRegisterCr4,
StmRegisterCr8,
StmRegisterMax,
} STM_REGISTER_VIOLATION_TYPE;
/**
Union of all STM resource types
**/
typedef union {
STM_RSC_DESC_HEADER Header;
STM_RSC_END End;
STM_RSC_MEM_DESC Mem;
STM_RSC_IO_DESC Io;
STM_RSC_MMIO_DESC Mmio;
STM_RSC_MSR_DESC Msr;
STM_RSC_PCI_CFG_DESC PciCfg;
STM_RSC_TRAPPED_IO_DESC TrappedIo;
STM_RSC_ALL_RESOURCES_DESC All;
STM_REGISTER_VIOLATION_DESC RegisterViolation;
} STM_RSC;
#pragma pack ()
#endif

View File

@ -0,0 +1,78 @@
/** @file
STM Status Codes
Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
SMI Transfer Monitor (STM) User Guide Revision 1.00
**/
#ifndef _STM_STATUS_CODE_H_
#define _STM_STATUS_CODE_H_
/**
STM Status Codes
**/
typedef UINT32 STM_STATUS;
/**
Success code have BIT31 clear.
All error codes have BIT31 set.
STM errors have BIT16 set.
SMM errors have BIT17 set
Errors that apply to both STM and SMM have bits BIT15, BT16, and BIT17 set.
STM TXT.ERRORCODE codes have BIT30 set.
@{
**/
#define STM_SUCCESS 0x00000000
#define SMM_SUCCESS 0x00000000
#define ERROR_STM_SECURITY_VIOLATION (BIT31 | BIT16 | 0x0001)
#define ERROR_STM_CACHE_TYPE_NOT_SUPPORTED (BIT31 | BIT16 | 0x0002)
#define ERROR_STM_PAGE_NOT_FOUND (BIT31 | BIT16 | 0x0003)
#define ERROR_STM_BAD_CR3 (BIT31 | BIT16 | 0x0004)
#define ERROR_STM_PHYSICAL_OVER_4G (BIT31 | BIT16 | 0x0005)
#define ERROR_STM_VIRTUAL_SPACE_TOO_SMALL (BIT31 | BIT16 | 0x0006)
#define ERROR_STM_UNPROTECTABLE_RESOURCE (BIT31 | BIT16 | 0x0007)
#define ERROR_STM_ALREADY_STARTED (BIT31 | BIT16 | 0x0008)
#define ERROR_STM_WITHOUT_SMX_UNSUPPORTED (BIT31 | BIT16 | 0x0009)
#define ERROR_STM_STOPPED (BIT31 | BIT16 | 0x000A)
#define ERROR_STM_BUFFER_TOO_SMALL (BIT31 | BIT16 | 0x000B)
#define ERROR_STM_INVALID_VMCS_DATABASE (BIT31 | BIT16 | 0x000C)
#define ERROR_STM_MALFORMED_RESOURCE_LIST (BIT31 | BIT16 | 0x000D)
#define ERROR_STM_INVALID_PAGECOUNT (BIT31 | BIT16 | 0x000E)
#define ERROR_STM_LOG_ALLOCATED (BIT31 | BIT16 | 0x000F)
#define ERROR_STM_LOG_NOT_ALLOCATED (BIT31 | BIT16 | 0x0010)
#define ERROR_STM_LOG_NOT_STOPPED (BIT31 | BIT16 | 0x0011)
#define ERROR_STM_LOG_NOT_STARTED (BIT31 | BIT16 | 0x0012)
#define ERROR_STM_RESERVED_BIT_SET (BIT31 | BIT16 | 0x0013)
#define ERROR_STM_NO_EVENTS_ENABLED (BIT31 | BIT16 | 0x0014)
#define ERROR_STM_OUT_OF_RESOURCES (BIT31 | BIT16 | 0x0015)
#define ERROR_STM_FUNCTION_NOT_SUPPORTED (BIT31 | BIT16 | 0x0016)
#define ERROR_STM_UNPROTECTABLE (BIT31 | BIT16 | 0x0017)
#define ERROR_STM_UNSUPPORTED_MSR_BIT (BIT31 | BIT16 | 0x0018)
#define ERROR_STM_UNSPECIFIED (BIT31 | BIT16 | 0xFFFF)
#define ERROR_SMM_BAD_BUFFER (BIT31 | BIT17 | 0x0001)
#define ERROR_SMM_INVALID_RSC (BIT31 | BIT17 | 0x0004)
#define ERROR_SMM_INVALID_BUFFER_SIZE (BIT31 | BIT17 | 0x0005)
#define ERROR_SMM_BUFFER_TOO_SHORT (BIT31 | BIT17 | 0x0006)
#define ERROR_SMM_INVALID_LIST (BIT31 | BIT17 | 0x0007)
#define ERROR_SMM_OUT_OF_MEMORY (BIT31 | BIT17 | 0x0008)
#define ERROR_SMM_AFTER_INIT (BIT31 | BIT17 | 0x0009)
#define ERROR_SMM_UNSPECIFIED (BIT31 | BIT17 | 0xFFFF)
#define ERROR_INVALID_API (BIT31 | BIT17 | BIT16 | BIT15 | 0x0001)
#define ERROR_INVALID_PARAMETER (BIT31 | BIT17 | BIT16 | BIT15 | 0x0002)
#define STM_CRASH_PROTECTION_EXCEPTION (BIT31 | BIT30 | 0xF001)
#define STM_CRASH_PROTECTION_EXCEPTION_FAILURE (BIT31 | BIT30 | 0xF002)
#define STM_CRASH_DOMAIN_DEGRADATION_FAILURE (BIT31 | BIT30 | 0xF003)
#define STM_CRASH_BIOS_PANIC (BIT31 | BIT30 | 0xE000)
/// @}
#endif

View File

@ -75,56 +75,73 @@
gAppleEFINVRAMTRBSecureGuid = {0xF68DA75E, 0x1B55, 0x4E70, {0xB4, 0x1B, 0xA7, 0xB7, 0xA5, 0xB7, 0x58, 0xEA}}
gDataHubOptionsGuid = {0x0021001C, 0x3CE3, 0x41F8, {0x99, 0xC6, 0xEC, 0xF5, 0xDA, 0x75, 0x47, 0x31}}
gApplePlatformInfoKeyboardGuid = {0x51871CB9, 0xE25D, 0x44B4, {0x96, 0x99, 0x0E, 0xE8, 0x64, 0x4C, 0xED, 0x69}}
gAppleOsLoadedNamedEventGuid = {0xC5C5DA95, 0x7D5C, 0x45E6, {0x83, 0x72, 0x89, 0xBD, 0x52, 0x6D, 0xE9, 0x56}}
gAppleOSLoadedNamedEventGuid = {0xC5C5DA95, 0x7D5C, 0x45E6, {0x83, 0x72, 0x89, 0xBD, 0x52, 0x6D, 0xE9, 0x56}}
gBootChimeVendorVariableGuid = {0x89D4F995, 0x67E3, 0x4895, {0x8F, 0x18, 0x45, 0x4B, 0x65, 0x1D, 0x92, 0x15}}
# Include/Guid/AppleVariable.h
gAppleCoreStorageVariableGuid = { 0x8D63D4FE, 0xBD3C, 0x4AAD, { 0x88, 0x1D, 0x86, 0xFD, 0x97, 0x4B, 0xC1, 0xDF }}
# Include/Guid/AppleVariable.h
gAppleTamperResistantBootVariableGuid = { 0x5D62B28D, 0x6ED2, 0x40B4, { 0xA5, 0x60, 0x6C, 0xD7, 0x9B, 0x93, 0xD3, 0x66 }}
# Include/Guid/AppleVariable.h
gAppleWirelessNetworkVariableGuid = { 0x36C28AB5, 0x6566, 0x4C50, { 0x9E, 0xBD, 0xCB, 0xB9, 0x20, 0xF8, 0x38, 0x43 }}
# Include/Guid/AppleVariable.h
gApplePersonalizationVariableGuid = { 0xFA4CE28D, 0xB62F, 0x4C99, { 0x9C, 0xC3, 0x68, 0x15, 0x68, 0x6E, 0x30, 0xF9 }}
# Include/Guid/AppleVariable.h
gAppleTamperResistantBootSecureVariableGuid = { 0xF68DA75E, 0x1B55, 0x4E70, { 0xB4, 0x1B, 0xA7, 0xB7, 0xA5, 0xB7, 0x58, 0xEA }}
# Include/Guid/AppleVariable.h
gAppleTamperResistantBootEfiUserVariableGuid = { 0x4E8023FF, 0xA79A, 0x47D1, { 0xA3, 0x42, 0x75, 0x24, 0xCF, 0xC9, 0x6D, 0xC4 }}
# Include/Guid/AppleVariable.h
gAppleNetbootVariableGuid = { 0x37BCBEC7, 0xA645, 0x4215, { 0x97, 0x9E, 0xF5, 0xAE, 0x4D, 0x11, 0x5F, 0x13 }}
# Include/Guid/AppleVariable.h
gAppleSecureBootVariableGuid = { 0x94B73556, 0x2197, 0x4702, { 0x82, 0xA8, 0x3E, 0x13, 0x37, 0xDA, 0xFB, 0xFB }}
gAppleCoreStorageVariableGuid = {0x8D63D4FE, 0xBD3C, 0x4AAD, {0x88, 0x1D, 0x86, 0xFD, 0x97, 0x4B, 0xC1, 0xDF}}
gAppleTamperResistantBootVariableGuid = {0x5D62B28D, 0x6ED2, 0x40B4, {0xA5, 0x60, 0x6C, 0xD7, 0x9B, 0x93, 0xD3, 0x66}}
gAppleWirelessNetworkVariableGuid = {0x36C28AB5, 0x6566, 0x4C50, {0x9E, 0xBD, 0xCB, 0xB9, 0x20, 0xF8, 0x38, 0x43}}
gApplePersonalizationVariableGuid = {0xFA4CE28D, 0xB62F, 0x4C99, {0x9C, 0xC3, 0x68, 0x15, 0x68, 0x6E, 0x30, 0xF9}}
gAppleTamperResistantBootSecureVariableGuid = {0xF68DA75E, 0x1B55, 0x4E70, {0xB4, 0x1B, 0xA7, 0xB7, 0xA5, 0xB7, 0x58, 0xEA}}
gAppleTamperResistantBootEfiUserVariableGuid = {0x4E8023FF, 0xA79A, 0x47D1, {0xA3, 0x42, 0x75, 0x24, 0xCF, 0xC9, 0x6D, 0xC4}}
gAppleNetbootVariableGuid = {0x37BCBEC7, 0xA645, 0x4215, {0x97, 0x9E, 0xF5, 0xAE, 0x4D, 0x11, 0x5F, 0x13}}
gAppleSecureBootVariableGuid = {0x94B73556, 0x2197, 0x4702, {0x82, 0xA8, 0x3E, 0x13, 0x37, 0xDA, 0xFB, 0xFB}}
# Include/Protocol/ApplePartitionInfo.h
gAppleApfsPartitionTypeGuid = {0x7C3457EF, 0x0000, 0x11AA, {0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC}}
gAppleApfsContainerInfoGuid = {0x3533CF0D, 0x685F, 0x5EBF, {0x8D, 0xC6, 0x73, 0x93, 0x48, 0x5B, 0xAF, 0xA2}}
gAppleApfsVolumeInfoGuid = {0x900C7693, 0x8C14, 0x58BA, {0xB4, 0x4E, 0x97, 0x45, 0x15, 0xD2, 0x7C, 0x78}}
gAppleApfsPartitionTypeGuid = {0x7C3457EF, 0x0000, 0x11AA, {0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC}}
gAppleApfsContainerInfoGuid = {0x3533CF0D, 0x685F, 0x5EBF, {0x8D, 0xC6, 0x73, 0x93, 0x48, 0x5B, 0xAF, 0xA2}}
gAppleApfsVolumeInfoGuid = {0x900C7693, 0x8C14, 0x58BA, {0xB4, 0x4E, 0x97, 0x45, 0x15, 0xD2, 0x7C, 0x78}}
## Include/Apple/Guid/AppleHfsInfo.h
gAppleHfsPartitionTypeGuid = {0x48465300, 0x0000, 0x11AA, {0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC}}
gAppleHfsCsPartitionTypeGuid = {0x53746F72, 0x6167, 0x11AA, {0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC}}
gAppleHfsBootPartitionTypeGuid = {0x426F6F74, 0x0000, 0x11AA, {0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC}}
gAppleHfsUuidInfoGuid = {0xFA99420C, 0x88F1, 0x11E7, {0x95, 0xF6, 0xB8, 0xE8, 0x56, 0x2C, 0xBA, 0xFA}}
## Include/Apple/Guid/AppleFile.h
gAppleFirmwareInfoFileGuid = {0x95C8C131, 0x4467, 0x4447, {0x8A, 0x71, 0xF0, 0x87, 0xAF, 0xCA, 0x07, 0xA5}}
gAppleSlingShotFileGuid = {0xD5B366C7, 0xDB85, 0x455F, {0xB5, 0x0B, 0x90, 0x0A, 0x69, 0x4E, 0x4C, 0x8C}}
gAppleBootPickerFileGuid = {0xE1628C66, 0x2A2D, 0x4DC5, {0xBD, 0x41, 0xB2, 0x0F, 0x35, 0x38, 0xAA, 0xF7}}
gApplePasswordUIFileGuid = {0x9EBA2D25, 0xBBE3, 0x4AC2, {0xA2, 0xC6, 0xC8, 0x7F, 0x44, 0xA1, 0x27, 0x8C}}
gAppleUTDMUIAppFileGuid = {0xD3231048, 0xB7D7, 0x46FC, {0x80, 0xF8, 0x2F, 0x7B, 0x22, 0x95, 0x86, 0xC5}}
gAppleLegacyLoadAppFileGuid = {0x2B0585EB, 0xD8B8, 0x49A9, {0x8B, 0x8C, 0xE2, 0x1B, 0x01, 0xAE, 0xF2, 0xB7}}
gAppleAlertUiFileGuid = {0x05984E1A, 0xD8BB, 0x5D8A, {0xA8, 0xE6, 0x90, 0xE6, 0xFB, 0x2A, 0xB7, 0xDA}}
gAppleHfsPlusDxeFileGuid = {0x4CF484CD, 0x135F, 0x4FDC, {0xBA, 0xFB, 0x1A, 0xA1, 0x04, 0xB4, 0x8D, 0x36}}
gAppleHfsPlusFileGuid = {0xAE4C11C8, 0x1D6C, 0xF24E, {0xA1, 0x83, 0xE1, 0xCA, 0x36, 0xD1, 0xA8, 0xA9}}
gAppleExFatDxeFileGuid = {0x44883EC1, 0xC77C, 0x1749, {0xB7, 0x3D, 0x30, 0xC7, 0xB4, 0x68, 0xB5, 0x56}}
gAppleApfsFileGuid = {0x3730EC36, 0x868D, 0x4DF6, {0x88, 0xCF, 0x30, 0xB7, 0x91, 0x27, 0x2F, 0x5C}}
# Include/Guid/ApplePlatformInfo.h
gAppleKeyboardPlatformInfoGuid = {0x51871CB9, 0xE25D, 0x44B4, { 0x96, 0x99, 0x0E, 0xE8, 0x64, 0x4C, 0xED, 0x69 }}
gAppleKeyboardPlatformInfoGuid = {0x51871CB9, 0xE25D, 0x44B4, {0x96, 0x99, 0x0E, 0xE8, 0x64, 0x4C, 0xED, 0x69}}
## Include/Apple/Guid/AppleBless.h
gAppleBlessedSystemFileInfoGuid = {0xCA7E4814, 0x2ADC, 0x4ADD, {0xAB, 0xFF, 0x73, 0x4E, 0x3C, 0xFE, 0x13, 0xF3}}
gAppleBlessedSystemFolderInfoGuid = {0x7BD1F02D, 0x9C2F, 0x4581, {0xBF, 0x12, 0xD5, 0x4a, 0xBA, 0x0D, 0x98, 0xD6}}
gAppleBlessedOsxFolderInfoGuid = {0x893CA450, 0x5F5E, 0x48BA, {0x85, 0x8F, 0x08, 0xC4, 0x5D, 0x80, 0x23, 0x18}}
## OC guids
gOcVendorVariableGuid = {0x4D1FDA02, 0x38C7, 0x4A6A, { 0x9C, 0xC6, 0x4B, 0xCC, 0xA8, 0xB3, 0x01, 0x02 }}
gOcReadOnlyVariableGuid = {0xE09B9297, 0x7928, 0x4440, { 0x9A, 0xAB, 0xD1, 0xF8, 0x53, 0x6F, 0xBF, 0x0A }}
gOcWriteOnlyVariableGuid = {0xF0B9AF8F, 0x2222, 0x4840, { 0x8A, 0x37, 0xEC, 0xF7, 0xCC, 0x8C, 0x12, 0xE1 }}
gOcVendorVariableGuid = {0x4D1FDA02, 0x38C7, 0x4A6A, {0x9C, 0xC6, 0x4B, 0xCC, 0xA8, 0xB3, 0x01, 0x02}}
gOcReadOnlyVariableGuid = {0xE09B9297, 0x7928, 0x4440, {0x9A, 0xAB, 0xD1, 0xF8, 0x53, 0x6F, 0xBF, 0x0A}}
gOcWriteOnlyVariableGuid = {0xF0B9AF8F, 0x2222, 0x4840, {0x8A, 0x37, 0xEC, 0xF7, 0xCC, 0x8C, 0x12, 0xE1}}
## OcSupport package token space guid
gOpenCorePkgTokenSpaceGuid = { 0x38D40CB0, 0x7E37, 0x4CAA, { 0x91, 0xD3, 0x00, 0x47, 0x70, 0xA8, 0x73, 0x77 }}
## Include/Microsoft/Guid/MicrosoftVariable.h
gMicrosoftVariableGuid = {0x77FA9ABD, 0x0359, 0x4D32, { 0xBD, 0x60, 0x28, 0xF4, 0xE7, 0x8F, 0x78, 0x4B }}
gMicrosoftVariableGuid = {0x77FA9ABD, 0x0359, 0x4D32, {0xBD, 0x60, 0x28, 0xF4, 0xE7, 0x8F, 0x78, 0x4B}}
[Protocols]
## Include/Protocol/FSInjectProtocol.h
gFSInjectProtocolGuid = {0x3F048284, 0x6D4C, 0x11E1, {0xA4, 0xD7, 0x37, 0xE3, 0x48, 0x24, 0x01, 0x9B }}
gFSInjectProtocolGuid = {0x3F048284, 0x6D4C, 0x11E1, {0xA4, 0xD7, 0x37, 0xE3, 0x48, 0x24, 0x01, 0x9B}}
## Include/Protocol/MsgLog.h
gMsgLogProtocolGuid = {0x511CE018, 0x0018, 0x4002, {0x20, 0x12, 0x17, 0x38, 0x05, 0x01, 0x02, 0x03 }}
gMsgLogProtocolGuid = {0x511CE018, 0x0018, 0x4002, {0x20, 0x12, 0x17, 0x38, 0x05, 0x01, 0x02, 0x03}}
## Include/Protocol/EmuVariableControl.h
gEmuVariableControlProtocolGuid = {0x21F41E73, 0xD214, 0x4FCD, {0x85, 0x50, 0x0D, 0x11, 0x51, 0xCF, 0x8E, 0xFB}}
@ -148,8 +165,10 @@
gEfiKeyboardInfoProtocolGuid = {0xE82A0A1E, 0x0E4D, 0x45AC, {0xA6, 0xDC, 0x2A, 0xE0, 0x58, 0x00, 0xD3, 0x11}}
gApplePartitionInfoProtocolGuid = {0x68425EE5, 0x1C43, 0x4BAA, {0x84, 0xF7, 0x9A, 0xA8, 0xA4, 0xD8, 0xE1, 0x1E}}
gApfsEfiBootRecordInfoProtocolGuid = {0x03B8D751, 0xA02F, 0x4FF8, {0x9B, 0x1A, 0x55, 0x24, 0xAF, 0xA3, 0x94, 0x5F}}
gAppleRamDiskProtocolGuid = {0x957932CC, 0x7E8E, 0x433B, {0x8F, 0x41, 0xD3, 0x91, 0xEA, 0x3C, 0x10, 0xF8}}
gAppleRtcRamProtocolGuid = {0xE121EC07, 0x9C42, 0x45EE, {0xB0, 0xB6, 0xFF, 0xF8, 0xEF, 0x03, 0xC5, 0x21}}
gAppleDiskImageProtocolGuid = {0x004B07E8, 0x0B9C, 0x427E, {0xB0, 0xD4, 0xA4, 0x66, 0xE6, 0xE5, 0x7A, 0x62}}
# gEfiHashAlgorithmSha1Guid = {0x2AE9D80F, 0x3fB2, 0x4095, {0xB7, 0xB1, 0xE9, 0x31, 0x57, 0xB9, 0x46, 0xB6}}
gEfiHdaControllerInfoProtocolGuid = {0xE5FC2CAF, 0x0291, 0x46F2, {0x87, 0xF8, 0x10, 0xC7, 0x58, 0x72, 0x58, 0x04}}
gEfiHdaIoProtocolGuid = {0xA090D7F9, 0xB50A, 0x4EA1, {0xBD, 0xE9, 0x1A, 0xA5, 0xE9, 0x81, 0x2F, 0x45}}
@ -161,6 +180,15 @@
gAmiEfiPointerProtocolGuid = {0x15A10CE7, 0xEAB5, 0x43BF, {0x90, 0x42, 0x74, 0x43, 0x2E, 0x69, 0x63, 0x77}}
gAmiEfiKeycodeProtocolGuid = {0x0ADFB62D, 0xFF74, 0x484C, {0x89, 0x44, 0xF8, 0x5C, 0x4B, 0xEA, 0x87, 0xA8}}
gOcFirmwareRuntimeProtocolGuid = {0x570332E4, 0xFC50, 0x4B21, {0xAB, 0xE8, 0xAE, 0x72, 0xF0, 0x5B, 0x4F, 0xF7}}
gOcAfterBootCompatProtocolGuid = {0xC7CBA84E, 0xCC77, 0x461D, {0x9E, 0x3C, 0x6B, 0xE0, 0xCB, 0x79, 0xA7, 0xC1}}
## Include/Protocol/AppleBootPolicy.h
gAppleBootPolicyProtocolGuid = {0x62257758, 0x350C, 0x4D0A, {0xB0, 0xBD, 0xF6, 0xBE, 0x2E, 0x1E, 0x27, 0x2C}}
## Include/Protocol/AppleBeepGenProtocol.h
gAppleBeepGenProtocolGuid = {0xC32332DF, 0xFC56, 0x4FE1, {0x93, 0x58, 0xBA, 0x0D, 0x52, 0x9B, 0x24, 0xCD}}
## Include/Protocol/OcAudio.h
gOcAudioProtocolGuid = {0x4B228577, 0x6274, 0x4A48, {0x82, 0xAE, 0x07, 0x13, 0xA1, 0x17, 0x19, 0x87}}
@ -191,6 +219,26 @@
gPcAtChipsetPkgTokenSpaceGuid.PcdIsaAcpiPs2MouseEnable|TRUE|BOOLEAN|0x00000006
# gPcAtChipsetPkgTokenSpaceGuid.PcdIsaAcpiFloppyAEnable|TRUE|BOOLEAN|0x00000007
# gPcAtChipsetPkgTokenSpaceGuid.PcdIsaAcpiFloppyBEnable|TRUE|BOOLEAN|0x00000008
## Defines the Console Control initialization mode set on entry.<BR><BR>
## 0 - EfiConsoleControlScreenText<BR>
## 1 - EfiConsoleControlScreenGraphics<BR>
## 2 - EfiConsoleControlScreenMaxValue (does nothing)<BR>
## @Prompt Initialize the console to the specified mode on entry.
gOpenCorePkgTokenSpaceGuid.PcdConsoleControlEntryMode|0|UINT8|0x00000100
## Defines the allowed OcCryptoLib RSA moduli by OR'ing the two's potencies in bytes.<BR><BR>
## @Prompt Allow these RSA moduli for cryptographic usage.
gOpenCorePkgTokenSpaceGuid.PcdOcCryptoAllowedRsaModuli|0x300|UINT16|0x00000500
## Defines the allowed OcCryptoLib signature hashing algorihtms by OR'ing the
## types' Bit indices.<BR><BR>
## Bit 0 - OcSigHashTypeSha256
## Bit 1 - OcSigHashTypeSha384
## Bit 2 - OcSigHashTypeSha512
## @Prompt Allow these signature hashing algorithms for cryptographic usage.
gOpenCorePkgTokenSpaceGuid.PcdOcCryptoAllowedSigHashTypes|0x07|UINT16|0x00000501
[PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]
# gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0204|UINT32|0x10010001

View File

@ -20,7 +20,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
STATIC BOOLEAN mExitingBootServices = FALSE;
extern EFI_GUID gAppleOsLoadedNamedEventGuid;
extern EFI_GUID gAppleOSLoadedNamedEventGuid;
//
// USB Keyboard Driver Global Variables
//
@ -71,7 +71,7 @@ USBKeyboardDriverBindingEntryPoint (
}
Status = EfiNamedEventListen(
&gAppleOsLoadedNamedEventGuid,
&gAppleOSLoadedNamedEventGuid,
TPL_NOTIFY,
WaitForOs,
NULL,

View File

@ -81,7 +81,7 @@
gUsbKeyboardLayoutPackageGuid ## SOMETIMES_CONSUMES ## HII
gUsbKeyboardLayoutKeyGuid ## SOMETIMES_PRODUCES ## UNDEFINED
gApplePlatformInfoKeyboardGuid ## SOMETIMES_CONSUMES
gAppleOsLoadedNamedEventGuid ## SOMETIMES_CONSUMES
gAppleOSLoadedNamedEventGuid ## SOMETIMES_CONSUMES
[Protocols]
gEfiUsbIoProtocolGuid ## TO_START

21
Include/AppleCpuType.h Normal file
View File

@ -0,0 +1,21 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_CPU_TYPE_H
#define APPLE_CPU_TYPE_H
#define CURRENT_CPU_TYPE MachCpuTypeX8664
#define CURRENT_CPU_SUBTYPE MachCpuSubtypeX8664All
#define APPLE_REMOVABLE_MEDIA_FILE_NAME APPLE_REMOVABLE_MEDIA_FILE_NAME_X64
#endif // APPLE_CPU_TYPE_H

38
Include/AppleMacEfi.h Normal file
View File

@ -0,0 +1,38 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_MAC_EFI_H
#define APPLE_MAC_EFI_H
#include <AppleCpuType.h>
#include <Uefi.h>
#include <AppleMacEfi/AppleMacEfiSpec.h>
#ifndef ARRAY_SIZE
/**
Return the number of elements in an array.
@param Array An object of array type. Array is only used as an argument to
the sizeof operator, therefore Array is never evaluated. The
caller is responsible for ensuring that Array's type is not
incomplete; that is, Array must have known constant size.
@return The number of elements in Array. The result has type UINTN.
**/
#define ARRAY_SIZE(Array) (sizeof (Array) / sizeof ((Array)[0]))
#endif
#endif // APPLE_MAC_EFI_H

View File

@ -0,0 +1,64 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_MAC_EFI_SPEC_H
#define APPLE_MAC_EFI_SPEC_H
// EFI Revision information
#define APPLE_EFI_FIRMWARE_REVISION 0x010000
#define APPLE_EFI_FIRMWARE_VENDOR L"Apple"
//
// Magic ID found at 0xFFFFFF80 address in newer firmwares like MBP12,1.
//
#define APPLE_EFI_FIRMWARE_GEN2_ID_MAGIC \
{ 0xA1, 0x7B, 0xE5, 0x98, 0x31, 0x22, 0x4F, 0x4E }
//
// Magic ID similar to APPLE_EFI_FIRMWARE_ID_MAGIC in T2-based firmwares.
//
#define APPLE_EFI_FIRMWARE_GEN3_ID_MAGIC \
{ 0xC6, 0x8A, 0x85, 0x99, 0xF5, 0xE2, 0x15, 0x4E }
// APPLE_BOOTER_FILE_NAME
#define APPLE_BOOTER_FILE_NAME L"boot.efi"
// APPLE_BOOTLOADER_FILE_PATH
#define APPLE_BOOTER_DEFAULT_FILE_NAME L"\\System\\Library\\CoreServices\\boot.efi"
// BOOT_EFI_FILE_NAME
#define APPLE_BOOTER_ROOT_FILE_NAME L"\\boot.efi"
// Apple EFI File location to boot from on removable media devices
// APPLE_REMOVABLE_MEDIA_FILE_NAME_IA32
#define APPLE_REMOVABLE_MEDIA_FILE_NAME_IA32 \
L"\\EFI\\APPLE\\IA32\\BOOT.EFI"
// APPLE_REMOVABLE_MEDIA_FILE_NAME_X64
#define APPLE_REMOVABLE_MEDIA_FILE_NAME_X64 \
L"\\EFI\\APPLE\\X64\\BOOT.EFI"
// APPLE_REMOVABLE_MEDIA_FILE_NAME_ARM
#define APPLE_REMOVABLE_MEDIA_FILE_NAME_ARM \
L"\\EFI\\APPLE\\ARM\\BOOT.EFI"
// APPLE_REMOVABLE_MEDIA_FILE_NAME_AARCH64
#define APPLE_REMOVABLE_MEDIA_FILE_NAME_AARCH64 \
L"\\EFI\\APPLE\\AARCH64\\BOOT.EFI"
// APPLE_SYSTEM_VERSION_FILE_NAME
#define APPLE_SYSTEM_VERSION_FILE_NAME \
L"\\System\\Library\\CoreServices\\SystemVersion.plist"
#endif // APPLE_MAC_EFI_SPEC_H

69
Include/Guid/AppleBless.h Normal file
View File

@ -0,0 +1,69 @@
/** @file
Copyright (C) 2014 - 2016, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_BLESS_H
#define APPLE_BLESS_H
//
// These GUIDs allow to retrieve parsed finderInfo fields out of HFSPlusVolumeHeader
// via HFSPlus.efi driver. The fields are reads from the following structure in Big Endian:
//
// struct HFSPlusVolumeFinderInfo {
// uint32_t blessedSystemFolderID; // for OpenFirmware systems
// uint32_t blessedSystemFileID; // for EFI systems
// uint32_t openWindowFolderID; // deprecated, first link in linked list of folders to open at mount
// uint32_t blessedAlternateOSID; // currently used for FV2 recovery, inaccessible from UEFI
// uint32_t unused; // formerly PowerTalk Inbox
// uint32_t blessedOSXFolderID; // currently used for normal recovery
// uint64_t volumeID;
// };
//
// References:
// https://opensource.apple.com/source/hfs/hfs-407.30.1/core/hfs_format.h.auto.html
// https://opensource.apple.com/source/bless/bless-166/handleInfo.c.auto.html
// https://opensource.apple.com/source/bless/bless-166/libbless/FinderInfo/BLGetVolumeFinderInfo.c.auto.html
// https://opensource.apple.com/source/bless/bless-166/libbless/HFS/BLLookupFileIDOnMount.c.auto.html
//
// TODO: Implement this in an opensource HFSPlus EFI driver.
//
// APPLE_BLESSED_SYSTEM_FILE_INFO_GUID
/// InformationType GUID used to get the blessed file's path.
#define APPLE_BLESSED_SYSTEM_FILE_INFO_GUID \
{ 0xCA7E4814, 0x2ADC, 0x4ADD, \
{ 0xAB, 0xFF, 0x73, 0x4E, 0x3C, 0xFE, 0x13, 0xF3 } }
// APPLE_BLESSED_SYSTEM_FOLDER_INFO_GUID
/// InformationType GUID exposed used to get the blessed folder's path.
#define APPLE_BLESSED_SYSTEM_FOLDER_INFO_GUID \
{ 0x7BD1F02D, 0x9C2F, 0x4581, \
{ 0xBF, 0x12, 0xD5, 0x4a, 0xBA, 0x0D, 0x98, 0xD6 } }
// APPLE_BLESSED_OSX_FOLDER_INFO_GUID
/// InformationType GUID exposed used to get alternative blessed file or folder's path.
#define APPLE_BLESSED_OSX_FOLDER_INFO_GUID \
{ 0x893CA450, 0x5F5E, 0x48BA, \
{ 0x85, 0x8F, 0x08, 0xC4, 0x5D, 0x80, 0x23, 0x18 } }
// gAppleBlessedSystemFileInfoGuid
/// A global variable storing the GUID of the APPLE_BLESSED_SYSTEM_FILE_INFO_GUID.
extern EFI_GUID gAppleBlessedSystemFileInfoGuid;
// gAppleBlessedSystemFolderInfoGuid
/// A global variable storing the GUID of the APPLE_BLESSED_SYSTEM_FOLDER_INFO_GUID.
extern EFI_GUID gAppleBlessedSystemFolderInfoGuid;
// gAppleBlessedOsxFolderInfoGuid
/// A global variable storing the GUID of the APPLE_BLESSED_OSX_FOLDER_INFO_GUID.
extern EFI_GUID gAppleBlessedOsxFolderInfoGuid;
#endif // APPLE_BLESS_H

102
Include/Guid/AppleFile.h Normal file
View File

@ -0,0 +1,102 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_FILE_H
#define APPLE_FILE_H
//
// ASCII content stored in legacy firmwares.
//
#define APPLE_FIRMWARE_INFO_FILE_GUID \
{ 0x95C8C131, 0x4467, 0x4447, \
{ 0x8A, 0x71, 0xF0, 0x87, 0xAF, 0xCA, 0x07, 0xA5 } }
// gAppleFirmwareInfoFileGuid
extern EFI_GUID gAppleFirmwareInfoFileGuid;
#define APPLE_SLING_SHOT_FILE_GUID \
{ 0xD5B366C7, 0xDB85, 0x455F, \
{ 0xB5, 0x0B, 0x90, 0x0A, 0x69, 0x4E, 0x4C, 0x8C } }
extern EFI_GUID gAppleSlingShotFileGuid;
#define APPLE_BOOT_PICKER_FILE_GUID \
{ 0xE1628C66, 0x2A2D, 0x4DC5, \
{ 0xBD, 0x41, 0xB2, 0x0F, 0x35, 0x38, 0xAA, 0xF7 } }
extern EFI_GUID gAppleBootPickerFileGuid;
#define APPLE_PASSWORD_UI_FILE_GUID \
{ 0x9EBA2D25, 0xBBE3, 0x4AC2, \
{ 0xA2, 0xC6, 0xC8, 0x7F, 0x44, 0xA1, 0x27, 0x8C } }
extern EFI_GUID gApplePasswordUIFileGuid;
#define APPLE_UTDMUI_APP_FILE_GUID \
{ 0xD3231048, 0xB7D7, 0x46FC, \
{ 0x80, 0xF8, 0x2F, 0x7B, 0x22, 0x95, 0x86, 0xC5 } }
extern EFI_GUID gAppleUTDMUIAppFileGuid;
#define APPLE_LEGACY_LOAD_APP_FILE_GUID \
{ 0x2B0585EB, 0xD8B8, 0x49A9, \
{ 0x8B, 0x8C, 0xE2, 0x1B, 0x01, 0xAE, 0xF2, 0xB7 } }
extern EFI_GUID gAppleLegacyLoadAppFileGuid;
///
/// 05984E1A-D8BB-5D8A-A8E6-90E6FB2AB7DA
///
#define APPLE_ALERT_UI_FILE_GUID \
{ 0x05984E1A, 0xD8BB, 0x5D8A, \
{ 0xA8, 0xE6, 0x90, 0xE6, 0xFB, 0x2A, 0xB7, 0xDA } }
extern EFI_GUID gAppleAlertUiFileGuid;
///
/// 4CF484CD-135F-4FDC-BAFB-1AA104B48D36
///
#define APPLE_HFS_PLUS_DXE_FILE_GUID \
{ 0x4CF484CD, 0x135F, 0x4FDC, \
{ 0xBA, 0xFB, 0x1A, 0xA1, 0x04, 0xB4, 0x8D, 0x36 } }
extern EFI_GUID gAppleHfsPlusDxeFileGuid;
///
/// AE4C11C8-1D6C-F24E-A183-E1CA36D1A8A9
///
#define APPLE_HFS_PLUS_FILE_GUID \
{ 0xAE4C11C8, 0x1D6C, 0xF24E, \
{ 0xA1, 0x83, 0xE1, 0xCA, 0x36, 0xD1, 0xA8, 0xA9 } }
extern EFI_GUID gAppleHfsPlusFileGuid;
///
/// 44883EC1-C77C-1749-B73D-30C7B468B556
///
#define APPLE_EX_FAT_DXE_FILE_GUID \
{ 0x44883EC1, 0xC77C, 0x1749, \
{ 0xB7, 0x3D, 0x30, 0xC7, 0xB4, 0x68, 0xB5, 0x56 } }
extern EFI_GUID gAppleExFatDxeFileGuid;
///
/// 3730EC36-868D-4DF6-88CF-30B791272F5C
///
#define APPLE_APFS_FILE_GUID \
{ 0x3730EC36, 0x868D, 0x4DF6, \
{ 0x88, 0xCF, 0x30, 0xB7, 0x91, 0x27, 0x2F, 0x5C } }
extern EFI_GUID gAppleApfsFileGuid;
#endif // APPLE_FILE_H

View File

@ -0,0 +1,53 @@
/** @file
Copyright (C) 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_HFS_INFO_H
#define APPLE_HFS_INFO_H
/**
Normal HFS+ volume.
**/
#define APPLE_HFS_PARTITION_TYPE_GUID \
{ 0x48465300, 0x0000, 0x11AA, \
{ 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }
extern EFI_GUID gAppleHfsPartitionTypeGuid;
/**
CoreStorage HFS+ volume.
**/
#define APPLE_HFS_CS_PARTITION_TYPE_GUID \
{ 0x53746F72, 0x6167, 0x11AA, \
{ 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }
extern EFI_GUID gAppleHfsCsPartitionTypeGuid;
/**
Boot (Recovery) HFS+ volume.
**/
#define APPLE_HFS_BOOT_PARTITION_TYPE_GUID \
{ 0x426F6F74, 0x0000, 0x11AA, \
{ 0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC } }
extern EFI_GUID gAppleHfsBootPartitionTypeGuid;
/**
Accessible from EFI_FILE_PROTOCOL::GetInfo, this GUID
allows to quickly obtain volume UUID.
**/
#define APPLE_HFS_UUID_INFO_GUID \
{ 0xFA99420C, 0x88F1, 0x11E7, \
{ 0x95, 0xF6, 0xB8, 0xE8, 0x56, 0x2C, 0xBA, 0xFA } }
extern EFI_GUID gAppleHfsUuidInfoGuid;
#endif // APPLE_HFS_INFO_H

View File

@ -0,0 +1,26 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_OS_LOADED_H
#define APPLE_OS_LOADED_H
#include <Uefi.h>
// APPLE_OS_LOADED_EVENT_NAME
#define APPLE_OS_LOADED_NAMED_EVENT_GUID \
{ 0xC5C5DA95, 0x7D5C, 0x45E6, \
{ 0x83, 0x72, 0x89, 0xBD, 0x52, 0x6D, 0xE9, 0x56 } }
// gAppleOSLoadedNamedEventGuid
extern EFI_GUID gAppleOSLoadedNamedEventGuid;
#endif // APPLE_OS_LOADED_H

View File

@ -0,0 +1,303 @@
/** @file
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_VARIABLE_H
#define APPLE_VARIABLE_H
#include <Uefi.h>
///
/// The Apple Vendor Variable-vendor GUID.
///
#define APPLE_VENDOR_VARIABLE_GUID \
{ 0x4D1EDE05, 0x38C7, 0x4A6A, \
{ 0x9C, 0xC6, 0x4B, 0xCC, 0xA8, 0xB3, 0x8C, 0x14 } }
///
/// The Apple boot Variable-vendor GUID.
///
#define APPLE_BOOT_VARIABLE_GUID \
{ 0x7C436110, 0xAB2A, 0x4BBB, \
{ 0xA8, 0x80, 0xFE, 0x41, 0x99, 0x5C, 0x9F, 0x82 } }
///
/// The Apple Core Storage Variable-vendor GUID.
///
#define APPLE_CORE_STORAGE_VARIABLE_GUID \
{ 0x8D63D4FE, 0xBD3C, 0x4AAD, \
{ 0x88, 0x1D, 0x86, 0xFD, 0x97, 0x4B, 0xC1, 0xDF } }
///
/// The Apple TRB Variable-vendor GUID.
///
#define APPLE_TAMPER_RESISTANT_BOOT_VARIABLE_GUID \
{ 0x5D62B28D, 0x6ED2, 0x40B4, \
{ 0xA5, 0x60, 0x6C, 0xD7, 0x9B, 0x93, 0xD3, 0x66 } }
///
/// The Apple TRB EFI User GUID.
///
#define APPLE_TAMPER_RESISTANT_BOOT_EFI_USER_GUID \
{ 0x4E8023FF, 0xA79A, 0x47D1, \
{ 0xA3, 0x42, 0x75, 0x24, 0xCF, 0xC9, 0x6D, 0xC4 } }
///
/// The Apple WiFi Network Variable-vendor GUID.
///
#define APPLE_WIRELESS_NETWORK_VARIABLE_GUID \
{ 0x36C28AB5, 0x6566, 0x4C50, \
{ 0x9E, 0xBD, 0xCB, 0xB9, 0x20, 0xF8, 0x38, 0x43 } }
///
/// The Apple Personalization Variable-vendor GUID.
///
#define APPLE_PERSONALIZATION_VARIABLE_GUID \
{ 0xFA4CE28D, 0xB62F, 0x4C99, \
{ 0x9C, 0xC3, 0x68, 0x15, 0x68, 0x6E, 0x30, 0xF9 } }
///
/// The Apple TRB Secure Variable-vendor GUID.
///
#define APPLE_TAMPER_RESISTANT_BOOT_SECURE_VARIABLE_GUID \
{ 0xF68DA75E, 0x1B55, 0x4E70, \
{ 0xB4, 0x1B, 0xA7, 0xB7, 0xA5, 0xB7, 0x58, 0xEA } }
///
/// The Apple Netboot Variable-vendor GUID.
///
#define APPLE_NETBOOT_VARIABLE_GUID \
{ 0x37BCBEC7, 0xA645, 0x4215, \
{ 0x97, 0x9E, 0xF5, 0xAE, 0x4D, 0x11, 0x5F, 0x13 } }
///
/// The Apple Security-vendor GUID.
///
#define APPLE_SECURITY_VARIABLE_GUID \
{ 0x7870DBED, 0x151D, 0x63FE, \
{ 0xF5, 0x88, 0x7C, 0x69, 0x94, 0x1C, 0xD0, 0x7B } }
///
/// The Apple Secure Boot Variable-vendor GUID.
///
#define APPLE_SECURE_BOOT_VARIABLE_GUID \
{ 0x94B73556, 0x2197, 0x4702, \
{ 0x82, 0xA8, 0x3E, 0x13, 0x37, 0xDA, 0xFB, 0xFB } }
///
/// The Apple Startup Manager Variable-vendor GUID.
///
#define APPLE_STARTUP_MANAGER_VARIABLE_GUID \
{ 0x5EEB160F, 0x45FB, 0x4CE9, \
{ 0xB4, 0xE3, 0x61, 0x03, 0x59, 0xAB, 0xF6, 0xF8 } }
///
/// The Apple Boot Variable Backup-vendor GUID.
///
#define APPLE_BACKUP_BOOT_VARIABLE_GUID \
{ 0xA5CE328C, 0x769D, 0x11E9, \
{ 0x94, 0xC7, 0x8C, 0x85, 0x90, 0x6B, 0xAC, 0x48 } }
///
/// User interface scale variable
/// UINT8: 1 or 2
/// gEfiAppleNvramGuid
///
#define APPLE_UI_SCALE_VARIABLE_NAME L"UIScale"
///
/// User interface scale variable.
/// UINT32: RGBA
/// gEfiAppleNvramGuid
///
#define APPLE_DEFAULT_BACKGROUND_COLOR_VARIABLE_NAME L"DefaultBackgroundColor"
typedef enum {
ApplePickerEntryReasonUnknown = 0, ///< Unknown
ApplePickerEntryReasonManufacturingMode = 1, ///< IR Remote
ApplePickerEntryReasonNvram = 2, ///< NVRAM
ApplePickerEntryReasonLeftOptKeyPress = 3, ///< Left Option
ApplePickerEntryReasonRightOptKeyPress = 4, ///< Right Option
ApplePickerEntryReasonBootDeviceTimeout = 5, ///< BDS Timeout
} APPLE_PICKER_ENTRY_REASON;
///
/// BootPicker startup mode.
/// UINT32: APPLE_PICKER_ENTRY_REASON.
/// gEfiAppleNvramGuid
///
#define APPLE_PICKER_ENTRY_REASON_VARIABLE_NAME L"PickerEntryReason"
#define APPLE_SYSTEM_AUDIO_VOLUME_MUTED BIT7
#define APPLE_SYSTEM_AUDIO_VOLUME_VOLUME_MASK 0x7FU
///
/// System audio volume.
/// UINT8: APPLE_SYSTEM_AUDIO_VOLUME_VOLUME_MASK | APPLE_SYSTEM_AUDIO_VOLUME_VOLUME_MASK
/// gEfiAppleBootGuid
///
#define APPLE_SYSTEM_AUDIO_VOLUME_VARIABLE_NAME L"SystemAudioVolume"
///
/// System audio volume backup, restored by AppleEFIRuntime.kext at next reboot.
/// UINT8: APPLE_SYSTEM_AUDIO_VOLUME_VOLUME_MASK | APPLE_SYSTEM_AUDIO_VOLUME_VOLUME_MASK
/// gEfiAppleBootGuid
///
#define APPLE_SYSTEM_AUDIO_VOLUME_SAVED_VARIABLE_NAME L"SystemAudioVolumeSaved"
///
/// System audio volume in decibels, created by AppleHDA.kext.
/// UINT8: SystemAudioVolume'
/// gEfiAppleBootGuid
///
#define APPLE_SYSTEM_AUDIO_VOLUME_SAVED_VARIABLE_DB_NAME L"SystemAudioVolumeDB"
///
/// System language.
/// String starting with language code (e.g. ru-RU:252).
/// gEfiAppleBootGuid
///
#define APPLE_PREV_LANG_KBD_VARIABLE_NAME L"prev-lang:kbd"
///
/// Performance record data enable.
/// UINT8: Any value to enable performance gathering (one time).
/// gEfiAppleBootGuid
///
#define APPLE_EFI_BOOT_PERF_VARIABLE_NAME L"efiboot-perf-record"
///
/// Performance record data address.
/// UINT32: Physical address to EfiACPIReclaimMemory containing perf data.
/// gEfiAppleBootGuid
///
#define APPLE_EFI_BOOT_PERF_ADDRESS_VARIABLE_NAME L"efiboot-perf-record-data"
///
/// Performance record data size.
/// UINT32: Size of performance record data, usually 4096 bytes.
/// gEfiAppleBootGuid
///
#define APPLE_EFI_BOOT_PERF_SIZE_VARIABLE_NAME L"efiboot-perf-record-data-size"
///
/// Hibernation wake log (mirror for APPLE_RTC_WAKE_LOG_ADDR).
/// UINT8[4]: Normally printed like 0x%02X 0x%02X % 3d 0x%02X.
/// gEfiAppleBootGuid
///
#define APPLE_WAKE_FAILURE_VARIABLE_NAME L"wake-failure"
///
/// Force enable UEFI Windows support.
/// CHAR8: '1'.
/// gEfiAppleBootGuid
///
#define APPLE_UEFI_WINDOWS_BOOT_CAPABLE_VARIABLE_NAME L"UEFIWindowsBootCapable"
///
/// Will install UEFI Windows on next reboot.
/// CHAR8: '1'.
/// gEfiAppleBootGuid
///
#define APPLE_INSTALL_WINDOWS_UEFI_VARIABLE_NAME L"InstallWindowsUEFI"
///
/// 7-bit packed panic information.
/// Data blob from with indices in the range of [0000, 0400).
/// gEfiAppleBootGuid
///
#define APPLE_PANIC_INFO_NO_VARIABLE_NAME L"AAPL,PanicInfo%04x"
///
/// BootCampt device path.
/// UEFI Device Path.
/// gEfiAppleBootGuid
///
#define APPLE_BOOT_CAMP_HD_VARIABLE_NAME L"BootCampHD"
///
/// A global variable storing the GUID of the APPLE_VENDOR EFI variable scope.
///
extern EFI_GUID gEfiAppleNvramGuid;
///
/// A global variable storing the GUID of the APPLE_BOOT EFI variable scope.
/// AKA gAppleEFINVRAMGuid
///
extern EFI_GUID gEfiAppleBootGuid;
///
/// A global variable storing the GUID of the APPLE_CORE_STORAGE EFI variable
/// scope.
///
extern EFI_GUID gAppleCoreStorageVariableGuid;
///
/// A global variable storing the GUID of the APPLE_TAMPER_RESISTANT_BOOT EFI
/// variable scope.
/// AKA gAppleEFINVRAMTRBStagingCommandGuid.
///
extern EFI_GUID gAppleTamperResistantBootVariableGuid;
///
/// A global variable storing the GUID of the APPLE_WIRELESS_NETWORK EFI
/// variable scope.
///
extern EFI_GUID gAppleWirelessNetworkVariableGuid;
///
/// A global variable storing the GUID of the APPLE_PERSONALIZATION EFI
/// variable scope.
///
extern EFI_GUID gApplePersonalizationVariableGuid;
///
/// A global variable storing the GUID of
/// the APPLE_TAMPER_RESISTANT_BOOT_SECURE_VARIABLE_GUID EFI variable scope.
/// AKA gAppleEFINVRAMTRBSecureVariableGuid.
///
extern EFI_GUID gAppleTamperResistantBootSecureVariableGuid;
///
/// A global variable storing the GUID of
/// the APPLE_TAMPER_RESISTANT_BOOT_EFI_USER_VARIABLE_GUID EFI variable scope.
///
extern EFI_GUID gAppleTamperResistantBootEfiUserVariableGuid;
///
/// A global variable storing the GUID of the APPLE_NETBOOT EFI variable
/// scope.
///
extern EFI_GUID gAppleNetbootVariableGuid;
///
/// A global variable storing the GUID of the APPLE_SECURITY EFI variable
/// scope.
///
extern EFI_GUID gAppleSecurityVariableGuid;
///
/// A global variable storing the GUID of the APPLE_SECURE_BOOT_VARIABLE_GUID
/// EFI variable scope.
///
extern EFI_GUID gAppleSecureBootVariableGuid;
///
/// A global variable storing the GUID of the APPLE_STARTUP_MANAGER variable scope.
///
extern EFI_GUID gAppleStartupManagerVariableGuid;
///
/// A global variable storing the GUID of the APPLE_BACKUP_BOOT variable scope.
///
extern EFI_GUID gAppleBackupBootVariableGuid;
#endif // APPLE_VARIABLE_H

View File

@ -0,0 +1,65 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_CHUNKLIST_H
#define APPLE_CHUNKLIST_H
//
// Magic number used to identify chunklist.
//
#define APPLE_CHUNKLIST_MAGIC 0x4C4B4E43 // "CNKL"
//
// Supported chunklist versions.
//
#define APPLE_CHUNKLIST_FILE_VERSION_10 0x1
#define APPLE_CHUNKLIST_CHUNK_METHOD_10 0x1
#define APPLE_CHUNKLIST_SIG_METHOD_10 0x1
#define APPLE_CHUNKLIST_CHECKSUM_LENGTH 32
#define APPLE_CHUNKLIST_SIG_LENGTH 256
#pragma pack(push, 1)
//
// Chunklist chunk.
//
typedef struct APPLE_CHUNKLIST_CHUNK_ {
UINT32 Length;
UINT8 Checksum[APPLE_CHUNKLIST_CHECKSUM_LENGTH];
} APPLE_CHUNKLIST_CHUNK;
//
// Chunklist signature.
//
typedef struct APPLE_CHUNKLIST_SIG_ {
UINT8 Signature[APPLE_CHUNKLIST_SIG_LENGTH];
} APPLE_CHUNKLIST_SIG;
//
// Chunklist header.
//
typedef struct {
UINT32 Magic;
UINT32 Length;
UINT8 FileVersion;
UINT8 ChunkMethod;
UINT8 SigMethod;
UINT8 Unused;
UINT64 ChunkCount;
UINT64 ChunkOffset;
UINT64 SigOffset;
} APPLE_CHUNKLIST_HEADER;
#pragma pack(pop)
#endif // APPLE_CHUNKLIST_H

View File

@ -31,7 +31,7 @@
#define CSR_ALLOW_DESTRUCTIVE_DTRACE (1U << 5U) /// < Name deprecated
#define CSR_ALLOW_UNRESTRICTED_DTRACE (1U << 5U)
#define CSR_ALLOW_UNRESTRICTED_NVRAM (1U << 6U)
#define CSR_ALLOW_DEVICE_CONFIGURATIO (1U << 7U)
#define CSR_ALLOW_DEVICE_CONFIGURATION (1U << 7U)
#define CSR_ALLOW_ANY_RECOVERY_OS (1U << 8U)
#define CSR_ALLOW_UNAPPROVED_KEXTS (1U << 9U)
#define CSR_ALLOW_EXECUTABLE_POLICY_OVERRIDE (1U << 10U)

View File

@ -0,0 +1,130 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_DISK_IMAGE_H
#define APPLE_DISK_IMAGE_H
//
// Magic number used to identify the disk image trailer.
//
#define APPLE_DISK_IMAGE_MAGIC 0x6B6F6C79
//
// Supported disk image version.
//
#define APPLE_DISK_IMAGE_VERSION 4
//
// Checksum length.
//
#define APPLE_DISK_IMAGE_CHECKSUM_SIZE 32
//
// Magic number used to identify the disk image block data.
//
#define APPLE_DISK_IMAGE_BLOCK_DATA_MAGIC 0x6D697368
//
// Sector size.
//
#define APPLE_DISK_IMAGE_SECTOR_SIZE 512
//
// Disk image checksum type.
//
#define APPLE_DISK_IMAGE_CHECKSUM_TYPE_CRC32 0x00000002
//
// Disk image chunk type.
//
#define APPLE_DISK_IMAGE_CHUNK_TYPE_ZERO 0x00000000
#define APPLE_DISK_IMAGE_CHUNK_TYPE_RAW 0x00000001
#define APPLE_DISK_IMAGE_CHUNK_TYPE_IGNORE 0x00000002
#define APPLE_DISK_IMAGE_CHUNK_TYPE_ADC 0x80000004
#define APPLE_DISK_IMAGE_CHUNK_TYPE_ZLIB 0x80000005
#define APPLE_DISK_IMAGE_CHUNK_TYPE_BZ2 0x80000006
#define APPLE_DISK_IMAGE_CHUNK_TYPE_COMMENT 0x7FFFFFFE
#define APPLE_DISK_IMAGE_CHUNK_TYPE_LAST 0xFFFFFFFF
#pragma pack(push, 1)
//
// Disk image checksum.
//
typedef struct APPLE_DISK_IMAGE_CHECKSUM_ {
UINT32 Type;
UINT32 Size;
UINT32 Data[APPLE_DISK_IMAGE_CHECKSUM_SIZE];
} APPLE_DISK_IMAGE_CHECKSUM;
//
// Disk image chunk (in XML).
//
typedef struct APPLE_DISK_IMAGE_CHUNK_ {
UINT32 Type;
UINT32 Comment;
UINT64 SectorNumber;
UINT64 SectorCount;
UINT64 CompressedOffset;
UINT64 CompressedLength;
} APPLE_DISK_IMAGE_CHUNK;
//
// Disk image block data (in XML).
//
typedef struct APPLE_DISK_IMAGE_BLOCK_DATA_ {
UINT32 Signature;
UINT32 Version;
UINT64 SectorNumber;
UINT64 SectorCount;
UINT64 DataOffset;
UINT32 BuffersNeeded;
UINT32 BlockDescriptors;
UINT32 Reserved[6];
APPLE_DISK_IMAGE_CHECKSUM Checksum;
UINT32 ChunkCount;
APPLE_DISK_IMAGE_CHUNK Chunks[];
} APPLE_DISK_IMAGE_BLOCK_DATA;
//
// Disk image trailer.
//
typedef struct APPLE_DISK_IMAGE_TRAILER_ {
UINT32 Signature;
UINT32 Version;
UINT32 HeaderSize;
UINT32 Flags;
UINT64 RunningDataForkOffset;
UINT64 DataForkOffset;
UINT64 DataForkLength;
UINT64 RsrcForkOffset;
UINT64 RsrcForkLength;
UINT32 SegmentNumber;
UINT32 SegmentCount;
GUID SegmentId;
APPLE_DISK_IMAGE_CHECKSUM DataForkChecksum;
UINT64 XmlOffset;
UINT64 XmlLength;
UINT8 Reserved1[120];
APPLE_DISK_IMAGE_CHECKSUM Checksum;
UINT32 ImageVariant;
UINT64 SectorCount;
UINT32 Reserved2[3];
} APPLE_DISK_IMAGE_TRAILER;
#pragma pack(pop)
#endif // APPLE_DISK_IMAGE_H

View File

@ -0,0 +1,48 @@
/** @file
Copyright (C) 2020, vit9696. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_DISK_LABEL_H
#define APPLE_DISK_LABEL_H
///
/// Image contains 8-bit values, which are indices in the opacity palette.
/// Colour is black.
///
#define APPLE_DISK_LABEL_PALETTED 1
///
/// Image contains 8-bit values, which are BGRA sequences.
/// For alpha 0xFF is fully transparent and 0x00 is fully opaque.
///
#define APPLE_DISK_LABEL_BGRA 2
///
/// Maximum disk label width and height for 1x scale.
///
#define APPLE_DISK_LABEL_MAX_WIDTH 340U
#define APPLE_DISK_LABEL_MAX_HEIGHT 12U
#pragma pack(push, 1)
///
/// Apple disk label structure, all fields are Big Endian.
///
typedef struct APPLE_DISK_LABEL_ {
UINT8 Type;
UINT16 Width;
UINT16 Height;
UINT8 Data[];
} APPLE_DISK_LABEL;
#pragma pack(pop)
#endif // APPLE_DISK_LABEL_H

View File

@ -0,0 +1,188 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_INTEL_CPU_INFO_H
#define APPLE_INTEL_CPU_INFO_H
///
/// i386_cpu_info_t related definitions.
/// Keep in sync with XNU osfmk/i386/cpuid.h.
/// Last sync time: 4903.221.2.
///
/*
* CPU families (sysctl hw.cpufamily)
*
* These are meant to identify the CPU's marketing name - an
* application can map these to (possibly) localized strings.
* NB: the encodings of the CPU families are intentionally arbitrary.
* There is no ordering, and you should never try to deduce whether
* or not some feature is available based on the family.
* Use feature flags (eg, hw.optional.altivec) to test for optional
* functionality.
*/
#define CPUFAMILY_UNKNOWN 0
#define CPUFAMILY_INTEL_6_13 0xaa33392b
#define CPUFAMILY_INTEL_PENRYN 0x78ea4fbc
#define CPUFAMILY_INTEL_NEHALEM 0x6b5a4cd2
#define CPUFAMILY_INTEL_WESTMERE 0x573b5eec
#define CPUFAMILY_INTEL_SANDYBRIDGE 0x5490b78c
#define CPUFAMILY_INTEL_IVYBRIDGE 0x1f65e835
#define CPUFAMILY_INTEL_HASWELL 0x10b282dc
#define CPUFAMILY_INTEL_BROADWELL 0x582ed09c
#define CPUFAMILY_INTEL_SKYLAKE 0x37fc219f
#define CPUFAMILY_INTEL_KABYLAKE 0x0f817246
/* CPU type, integer_t */
typedef INT32 cpu_type_t;
typedef INT32 cpu_subtype_t;
/*
* Cache ID descriptor structure, used to parse CPUID leaf 2.
* Note: not used in kernel.
*/
typedef enum { Lnone, L1I, L1D, L2U, L3U, LCACHE_MAX } cache_type_t;
typedef struct {
UINT8 value; /* Descriptor value */
cache_type_t type; /* Cache type */
UINT32 size; /* Cache size */
UINT32 linesize; /* Cache line size */
CONST CHAR8 *description; /* Cache description */
} cpuid_cache_desc_t;
/* Monitor/mwait Leaf: */
typedef struct {
UINT32 linesize_min;
UINT32 linesize_max;
UINT32 extensions;
UINT32 sub_Cstates;
} cpuid_mwait_leaf_t;
/* Thermal and Power Management Leaf: */
typedef struct {
BOOLEAN sensor;
BOOLEAN dynamic_acceleration;
BOOLEAN invariant_APIC_timer;
BOOLEAN core_power_limits;
BOOLEAN fine_grain_clock_mod;
BOOLEAN package_thermal_intr;
UINT32 thresholds;
BOOLEAN ACNT_MCNT;
BOOLEAN hardware_feedback;
BOOLEAN energy_policy;
} cpuid_thermal_leaf_t;
/* XSAVE Feature Leaf: */
typedef struct {
UINT32 extended_state[4]; /* eax .. edx */
} cpuid_xsave_leaf_t;
/* Architectural Performance Monitoring Leaf: */
typedef struct {
UINT8 version;
UINT8 number;
UINT8 width;
UINT8 events_number;
UINT32 events;
UINT8 fixed_number;
UINT8 fixed_width;
} cpuid_arch_perf_leaf_t;
/* The TSC to Core Crystal (RefCLK) Clock Information leaf */
typedef struct {
UINT32 numerator;
UINT32 denominator;
} cpuid_tsc_leaf_t;
/* Physical CPU info - this is exported out of the kernel (kexts), so be wary of changes */
typedef struct {
CHAR8 cpuid_vendor[16];
CHAR8 cpuid_brand_string[48];
CONST CHAR8 *cpuid_model_string;
cpu_type_t cpuid_type; /* this is *not* a cpu_type_t in our <mach/machine.h> */
UINT8 cpuid_family;
UINT8 cpuid_model;
UINT8 cpuid_extmodel;
UINT8 cpuid_extfamily;
UINT8 cpuid_stepping;
UINT64 cpuid_features;
UINT64 cpuid_extfeatures;
UINT32 cpuid_signature;
UINT8 cpuid_brand;
UINT8 cpuid_processor_flag;
UINT32 cache_size[LCACHE_MAX];
UINT32 cache_linesize;
UINT8 cache_info[64]; /* list of cache descriptors */
UINT32 cpuid_cores_per_package;
UINT32 cpuid_logical_per_package;
UINT32 cache_sharing[LCACHE_MAX];
UINT32 cache_partitions[LCACHE_MAX];
cpu_type_t cpuid_cpu_type; /* <mach/machine.h> */
cpu_subtype_t cpuid_cpu_subtype; /* <mach/machine.h> */
/* Per-vendor info */
cpuid_mwait_leaf_t cpuid_mwait_leaf;
#define cpuid_mwait_linesize_max cpuid_mwait_leaf.linesize_max
#define cpuid_mwait_linesize_min cpuid_mwait_leaf.linesize_min
#define cpuid_mwait_extensions cpuid_mwait_leaf.extensions
#define cpuid_mwait_sub_Cstates cpuid_mwait_leaf.sub_Cstates
cpuid_thermal_leaf_t cpuid_thermal_leaf;
cpuid_arch_perf_leaf_t cpuid_arch_perf_leaf;
UINT32 unused[4]; /* cpuid_xsave_leaf */
/* Cache details: */
UINT32 cpuid_cache_linesize;
UINT32 cpuid_cache_L2_associativity;
UINT32 cpuid_cache_size;
/* Virtual and physical address aize: */
UINT32 cpuid_address_bits_physical;
UINT32 cpuid_address_bits_virtual;
UINT32 cpuid_microcode_version;
/* Numbers of tlbs per processor [i|d, small|large, level0|level1] */
UINT32 cpuid_tlb[2][2][2];
#define TLB_INST 0
#define TLB_DATA 1
#define TLB_SMALL 0
#define TLB_LARGE 1
UINT32 cpuid_stlb;
UINT32 core_count;
UINT32 thread_count;
/* Max leaf ids available from CPUID */
UINT32 cpuid_max_basic;
UINT32 cpuid_max_ext;
/* Family-specific info links */
UINT32 cpuid_cpufamily;
cpuid_mwait_leaf_t *cpuid_mwait_leafp;
cpuid_thermal_leaf_t *cpuid_thermal_leafp;
cpuid_arch_perf_leaf_t *cpuid_arch_perf_leafp;
cpuid_xsave_leaf_t *cpuid_xsave_leafp;
UINT64 cpuid_leaf7_features;
cpuid_tsc_leaf_t cpuid_tsc_leaf;
cpuid_xsave_leaf_t cpuid_xsave_leaf[2];
} i386_cpu_info_t;
typedef i386_cpu_info_t APPLE_INTEL_CPU_INFO;
#endif // APPLE_INTEL_CPU_INFO_H

View File

@ -0,0 +1,400 @@
/** @file
Copyright (C) 2020, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_RTC_H
#define APPLE_RTC_H
/**
Sample RTC memory dump from MBP12,1 running 10.15.4:
00: 33 02 01 00 12 22 04 16 04 20 26 02 70 80 FF FF
10: FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
20: FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
30: 01 FE 20 FF FF FF FF FF F8 11 FF FF FF 00 1A 7C
40: 00 00 00 00 FE 00 00 00 00 00 00 00 00 00 00 00
50: 00 00 00 00 00 00 00 FF 0B D1 80 00 05 00 00 00
60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
70: 00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FF
80: 44 45 41 44 00 00 00 00 00 00 00 00 00 00 00 00
90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
A0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
B0: 76 CF 85 13 00 00 00 00 00 00 00 00 00 00 00 00
C0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
D0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
E0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
F0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
**/
/**
APPLE_RTC_BG_COLOR_ADDR - background colour.
APPLE_RTC_BG_COMPLEMENT_ADDR - complementary byte to background colour.
0x00 - Grey background (applies to 10.9 and older).
0x01 - Black background (applies to 10.10 and newer).
Valid pair gives APPLE_RTC_BG_COLOR_ADDR ^ APPLE_RTC_BG_COMPLEMENT_ADDR == 0xFF.
Otherwise background colour should be treated as 0, grey.
Prior to rebooting to MacEFI firmare upgrade /usr/libexec/efiupdater
removes DefaultBackgroundColor NVRAM variable and resets background to black.
When performing hibernate wake OSInfo writes chooses the background colour
based on reported macOS version (grey for 10.9 and below, black otherwise).
**/
#define APPLE_RTC_BG_COLOR_ADDR 0x30
#define APPLE_RTC_BG_COMPLEMENT_ADDR 0x31
/**
APPLE_RTC_BG_COLOR_ADDR values.
**/
#define APPLE_RTC_BG_COLOR_GRAY 0x00
#define APPLE_RTC_BG_COLOR_BLACK 0x01
/**
By default masked out with 0xF8.
Connected thunderbolt devices can set 3 lower bits.
BIT3 seems to be set when InstallWindowsUEFI was present at boot.
See ThunderboltNhi and PchInitDxe.
**/
#define APPLE_RTC_FIRMWARE_STATE_ADDR 0x38
/**
Used by ApplePlatformInit, 1 byte.
**/
#define APPLE_RTC_FIRMWARE_3D_ADDR 0x3D
/**
Bitmask of started test indices.
Little endian 32-bit number.
Note: memory testing statuses are a bit more complicated,
but we do not need too much detail atm.
**/
#define APPLE_RTC_MEM_TEST_ACCEPT_ADDR 0x44
/**
Bitmask of request test indices.
Little endian 32-bit number.
**/
#define APPLE_RTC_MEM_TEST_REQUEST_ADDR 0x48
/**
Bitmask of performed test indices.
Little endian 32-bit number.
**/
#define APPLE_RTC_MEM_TEST_RESULT_ADDR 0x4C
/**
Another unknown reserved address.
**/
#define APPLE_RTC_FIRMWARE_57_ADDR 0x57
/**
Firmware boot progress, mostly maintained by AppleBds.
0x00, 0x01, 0x02 - Set by RomIntegrityPei.
0x04 - Normal boot started. At this step AppleBds will process hibernation,
enable video output, check battery state, perform memory test, etc.
0x05 - Exit Boot Services called. Set in AppleBds event handler.
**/
#define APPLE_RTC_FIRMWARE_PROGRESS_ADDR 0x5C
/**
Apple RTC reserved memory area for unclear purposes, normally filled with FF.
Should not be erased during PRAM reset (CMD+OPT+P+R).
**/
#define APPLE_RTC_RESERVED_ADDR 0x78
/**
Apple RTC reserved memory size.
**/
#define APPLE_RTC_RESERVED_LENGTH 8
/**
Hibernation image encryption data, a copy of IOHibernateRTCVariables.
See AppleRTCHibernateVars type in AppleHibernate.h for the definition.
- Valid hibernation image encryption data starts with "AAPL" magic.
- Erased hibernation image encryption data starts with "DEAD" magic.
Normally handled by AppleBds prior to transfering control to the bootloader.
**/
#define APPLE_RTC_HIBERNATION_KEY_ADDR 0x80
/**
Effectively equals to sizeof (AppleRTCHibernateVars).
**/
#define APPLE_RTC_HIBERNATION_KEY_LENGTH 0x2C
/**
Firmware upgrade control and status byte.
0x00 - Normal boot. AppleBds resets to this value upon BOOT_ON_FLASH_UPDATE
prior to running BootRomFlash. BootRomFlash may itself reset to this
value on successful(?) flashing. Mirrored to NOBP SMC key.
0x01 - Alternative unsuccessful (?) result of firmware flashing written
by BootRomFlash. Mirrored to NOBP SMC key. Also set in ApplePlatformInit.
0x02 - Schedule firmware upgrade. Closed-source bless part writes this value
when intending to upgrade MacEFI firmware.
0x03 - Peform firmware upgrade. BootRomFlash writes this value prior to
rebooting into BOOT_ON_FLASH_UPDATE mode. Might be needed due to region
unlock.
**/
#define APPLE_RTC_FIRMWARE_UPGRADE_ADDR 0xAC
/**
AppleBds zeroes this byte at the same time it reaches normal booting phase (0x4)
in APPLE_RTC_FIRMWARE_PROGRESS_ADDR. This may be set to non-zero value by ApplePlatformInit.
**/
#define APPLE_RTC_FIRMWARE_CHECK_ADDR 0xAF
/**
Data contained in RTC allowing to trace various power management events.
Called via AppleRTC::rtcRecordTracePoint and also used for EfiBoot wake log.
**/
#define APPLE_RTC_TRACE_POINT_ADDR 0xB0
/**
Trace point data contains a total of 8 bytes, but they seem to have varying purpose.
**/
#define APPLE_RTC_TRACE_POINT_LENGTH 8
/**
Trace data is a 32-bit value, which format depends on the phase
(APPLE_RTC_TRACE_PHASE_ADDR) the platform is currently in.
For the kernel this may e.g. contain PCI device index currently put
in sleep or being awoken (kIOPMTracePointSleepPowerPlaneDrivers
or kIOPMTracePointWakePowerPlaneDrivers).
For EfiBoot this is named hibernatin wake log. It is also written to
wake-failure NVRAM variable (and later DeviceTree).
**/
#define APPLE_RTC_TRACE_DATA_ADDR 0xB0
/**
Trace data length.
**/
#define APPLE_RTC_TRACE_DATA_LENGTH 4
/**
Mask of events, which happened during booting.
These events are appended during the boot progress.
Note, unlike APPLE_RTC_WL_EVENT_ADDR/APPLE_RTC_WL_EVENT_EXTRA_ADDR,
which only get updated in hibernate wake, this value is always written
when a non-zero event is supplied.
**/
#define APPLE_RTC_WL_MASK_ADDR 0xB1
/**
Known event bits.
**/
#define APPLE_RTC_WL_MASK_BOOT_STARTED BIT0 ///< Called early at boot.efi startup.
#define APPLE_RTC_WL_MASK_BOOT_FAILED BIT1 ///< gBS->Exit: Boot failed; will sleep for 10 seconds before exiting.
#define APPLE_RTC_WL_MASK_BOOT_KERNEL BIT2 ///< Called right before jumping to the kernel code.
#define APPLE_RTC_WL_MASK_CS_UNLOCKED BIT3 ///< Set along with APPLE_RTC_WL_CS_VOLUME_UNLOCKED.
#define APPLE_RTC_WL_MASK_HIB_CLEAR_KEYS BIT4 ///< Removed boot-image-key, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_MASK_HIB_CLEAR_IMG BIT5 ///< Removed boot-image, will reboot now.
#define APPLE_RTC_WL_MASK_BOOT_RESET BIT6 ///< gBS->Reset was called.
/**
Event index that happened last during booting.
0xB2 is the event type and 0xB3 is its subtype.
**/
#define APPLE_RTC_WL_EVENT_ADDR 0xB2
#define APPLE_RTC_WL_EVENT_EXTRA_ADDR 0xB3
/**
Known events.
**/
#define APPLE_RTC_WL_EVENT_DEFAULT 0 ///< For everything.
#define APPLE_RTC_WL_INIT_DEVICE_TREE 2 ///< Before first "Start InitDeviceTree".
#define APPLE_RTC_WL_KERNEL_ALLOC_CALL_GATE 3 ///< After "End InitDeviceTree".
#define APPLE_RTC_WL_INIT_MEMORY_CONFIG 4 ///< Before "Start InitMemoryConfig".
#define APPLE_RTC_WL_HIB_CHECK 5 ///< Before "Start CheckHibernate".
#define APPLE_RTC_WL_CS_LOAD_CONFIGURATION 6 ///< Before "Start LoadCoreStorageConfiguration".
#define APPLE_RTC_WL_GET_FDE_KEY 7 ///< Before reading HBKP key.
#define APPLE_RTC_WL_HIB_WAKE_START 8 ///< Before reading FACP table.
#define APPLE_RTC_WL_HIB_GET_MMAP 9 ///< Before GetMemoryMap for hibernation.
#define APPLE_RTC_WL_HIB_HWSIG_VALID 10 ///< After confirming FACP signature validity with the image.
#define APPLE_RTC_WL_HIB_MEM_ALLOC 11 ///< Before restore1CodePhysPage / runtimePages allocation.
#define APPLE_RTC_WL_HIB_SPLASH 12 ///< Before "Start OpenBootGraphics".
#define APPLE_RTC_WL_HIB_READ 13 ///< After "Start hibernate read".
#define APPLE_RTC_WL_HIB_HANDOFF 14 ///< Before adjusting IOHibernateImageHeader and booting kernel.
#define APPLE_RTC_WL_HIB_EXIT_BOOT_SERVICES 15 ///< Done ExitBootServices for hibernate, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_KERNEL_START 16 ///< Calling kernel entry point for hibernate.
#define APPLE_RTC_WL_HIB_FINISH_FDE 17 ///< After "Start FinishFDEHibernate".
#define APPLE_RTC_WL_HIB_WIRED_KEY_VALID 18 ///< Before APPLE_RTC_WL_HIBERNATE_WAKE_START with valid FDE key.
#define APPLE_RTC_WL_RECOVERY_OS_FOUND 19 ///< After detecting com.apple.recovery.boot in boot path.
#define APPLE_RTC_WL_CS_VOLUME_UNLOCKED 20 ///< After "End UnlockCoreStorageVolumeKey" with EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_KERNEL_LOAD_CACHE_FAIL 22 ///< Failed to load kernel cache, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BS_MISSING 23 ///< Missing boot-signature, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BIK_MISSING 24 ///< Missing boot-image-key, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_RECOVERY_OS_REBOOT 25 ///< Before rebooting into recovery with APPLE_RTC_WL_MASK_BOOT_RESET.
#define APPLE_RTC_WL_LOGIN_WINDOW_PWRESET 26 ///< Requested FDE password recovery.
#define APPLE_RTC_WL_LOGIN_WINDOW_GUEST 27 ///< Chose guest in FV2 login window, will gBS->Reset now.
#define APPLE_RTC_WL_LOGIN_WINDOW_RESET 28 ///< Chose reset in FV2 login window, will gBS->Reset now.
#define APPLE_RTC_WL_LOGIN_WINDOW_HIB 29 ///< Will save hibernation data after FV2 login window and shutdown.
#define APPLE_RTC_WL_LOGIN_WINDOW_SHUTDOWN 30 ///< Chose shutdown in FV2 login window, will gBS->Reset now.
#define APPLE_RTC_WL_LOGIN_WINDOW_FAIL 31 ///< After "End LoginWindow Initialize", EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_ABORT_SAFE_MODE 32 ///< Hibernation aborted due to safe mode, after "Start CheckHibernate".
#define APPLE_RTC_WL_HIB_BI_ALLOC 33 ///< Failed to allocate memory for boot-image, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BI_MISSING 34 ///< Missing boot-image variable or 0 size, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BI_INVALID 35 ///< Did not find valid data in boot-image.
#define APPLE_RTC_WL_HIB_BI_DP_ALLOC 36 ///< Failed to allocate boot-image device path(?).
#define APPLE_RTC_WL_HIB_BI_DP_ZERO 37 ///< boot-image contains empty DP(?).
#define APPLE_RTC_WL_HIB_BI_DP_MISSING 38 ///< Failed to locate boot-image device path, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BI_DP_NO_DISK_IO 39 ///< Failed to find Disk I/O protocol, EFI_STATUS in EXTRA.
#define APPLE_RTC_WL_HIB_BI_DP_NI_BLOCK_IO 40 ///< Failed to find Block I/O protocol, EFI_STATUS in EXTRA.
/**
Certain components have the ability to log their wake progress
directly via RTC. See XNU IOPMPrivate.h for more details.
LoginWindow - 4 bits
CoreDisplay - 8 bits
CoreGraphics - 8 bits
Apparently these look mostly unused, at least in release builds.
CoreDisplay is known to report 0 (very helpful) on screen wake.
I guess we can abuse them if we want.
**/
#define APPLE_RTC_TRACE_LOGIN_WINDOW_ADDR 0xB4
#define APPLE_RTC_TRACE_CORE_DISPLAY_ADDR 0xB5
#define APPLE_RTC_TRACE_CORE_GRAPHICS_ADDR 0xB6
/**
Trace point power phase e.g. kIOPMTracePointSystemUp.
See XNU IOPMPrivate.h for more details.
**/
#define APPLE_RTC_TRACE_PHASE_ADDR 0xB7
/**
256-bit full disk encryption (FDE) key used for authenticated restart.
AppleRTC and other kexts name it key stash.
Written by AppleRTC at the request of IOHibernateSMCVariables I/O registry
entry submitted either by XNU kernel or AppleFDEKeyStore.kext. The variable
itself is a pair of 64-bit values: key size and key address in kernel memory.
This was replaced with HBKP SMC key in modern Macs.
*** VirtualSMC addendum ***
Since this value is no longer used due to HBKP present in almost every Mac
we badly abuse this area when vertualising SMC.
When HBKP SMC key is written VirtualSMC AES-128 encrypts the submitted value
with a unique key and writes the result to an NVRAM variable (vsmc-key).
The AES encryption key goes to RTC at this addrress instead.
Afterwards the EFI module implementing SMC protocol performs the decryption.
TODO: Replace AES with one-time pad, i.e. increase the temporary key size
to 256 bits and just XOR the value. This will break old VirtualSmc.efi
module, but we do not care anymore.
**/
#define APPLE_RTC_FDE_KEY_ADDR 0xD0
/**
FDE key maximum and default, as AES-256-XTS has 256-bit key.
For smaller keys remaining bytes are zeroed.
**/
#define APPLE_RTC_FDE_KEY_LENGTH 0x20
/**
FDE key state. Normally written by ApplePlatformInit.
0x00 - The key is either present or not.
0x41 - The key is not present, and should be copied to RTC from HBKP
SMC key prior to transfering control to the bootloader. After the
copying succeeds this value is overwritten with 0x00. Normally
this is done by AppleBds.
**/
#define APPLE_RTC_FDE_STATE_ADDR 0xF0
/**
Known values for APPLE_RTC_FDE_STATE_ADDR.
**/
#define APPLE_RTC_FDE_STATE_DEFAULT 0x00
#define APPLE_RTC_FDE_STATE_NEED_KEY 0x41
/**
Checksum is calculated starting from this address.
**/
#define APPLE_RTC_CHECKSUM_START 0x0E
/**
First 64 bytes are RTC core and are hashed separately.
**/
#define APPLE_RTC_CORE_SIZE 0x40
/**
All Apple hardware cares about 256 bytes of RTC memory.
**/
#define APPLE_RTC_TOTAL_SIZE 0x100
/**
Apple checksum custom CRC polynomial.
Apple checksum is a modified version of ANSI CRC16 in REFIN mode (0xA001 poly).
See http://zlib.net/crc_v3.txt for more details.
Effective poly is 0x2001 due to a bitwise OR with BIT15.
The change turns CRC16 into CRC14, making BIT14 and BIT15 always zero.
This modification is commonly found in legacy Phoenix firmwares,
where it was used for password hashing as found by dogbert:
http://sites.google.com/site/dogber1/blag/pwgen-5dec.py
**/
#define APPLE_RTC_CHECKSUM_POLYNOMIAL 0x2001
/**
Apple checksum rounds.
Only 7 shifts per byte are performed instead of the usual 8.
This might improve checksum quality against specific data, but the exact
reasons are unknown. The algorithm did not change since its introduction
in 10.4.x, and since Apple Developer Transition Kit was based on Phoenix
firmware, this could just be a quick change to get a different checksum.
**/
#define APPLE_RTC_CHECKSUM_ROUNDS 7
/**
Checksum for Apple RTC with core part of the memory hashed:
[APPLE_RTC_CHECKSUM_SART, APPLE_RTC_CORE_SIZE).
**/
#define APPLE_RTC_CORE_CHECKSUM_ADDR1 0x3E
#define APPLE_RTC_CORE_CHECKSUM_ADDR2 0x3F
/**
Apple RTC core checksum to byte convertion macros.
BYTE1 BIT0~BIT7 = CHECKSUM BIT0~BIT7
BYTE2 BIT1~BIT7 = CHECKSUM BIT8~BIT14
**/
#define APPLE_RTC_CORE_CHECKSUM_BYTE1(Checksum) ((UINT8) ((UINT32) (Checksum) & 0xFFU))
#define APPLE_RTC_CORE_CHECKSUM_BYTE2(Checksum) ((UINT8) (((UINT32) (Checksum) >> 7U) & 0xFEU))
/**
Checksum for Apple RTC with all the memory hashed:
[APPLE_RTC_CHECKSUM_SART, APPLE_RTC_TOTAL_SIZE).
**/
#define APPLE_RTC_MAIN_CHECKSUM_ADDR1 0x58
#define APPLE_RTC_MAIN_CHECKSUM_ADDR2 0x59
/**
Apple RTC main checksum to byte convertion macros.
BYTE1 BIT0~BIT7 = CHECKSUM BIT0~BIT7
BYTE2 BIT0~BIT7 = CHECKSUM BIT8~BIT15
**/
#define APPLE_RTC_MAIN_CHECKSUM_BYTE1(Checksum) ((UINT8) (((UINT32) (Checksum) >> 8U) & 0xFFU))
#define APPLE_RTC_MAIN_CHECKSUM_BYTE2(Checksum) ((UINT8) ((UINT32) (Checksum) & 0xFFU))
#endif // APPLE_RTC_H

View File

@ -18,9 +18,20 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#include <IndustryStandard/SmBios.h>
///
/// Apple Firmware Volume.
///
#pragma pack (1)
#define APPLE_SMBIOS_TYPE_FIRMWARE_INFORMATION 128
#define APPLE_SMBIOS_TYPE_MEMORY_SPD_DATA 130
#define APPLE_SMBIOS_TYPE_PROCESSOR_TYPE 131
#define APPLE_SMBIOS_TYPE_PROCESSOR_BUS_SPEED 132
#define APPLE_SMBIOS_TYPE_PLATFORM_FEATURE 133
#define APPLE_SMBIOS_TYPE_SMC_INFORMATION 134
#define APPLE_NUMBER_OF_FLASHMAP_ENTRIES 8
#define APPLE_SMBIOS_SMC_VERSION_SIZE 16
// APPLE_REGION_TYPE
enum {
FW_REGION_RESERVED = 0,
FW_REGION_RECOVERY = 1,
@ -31,7 +42,16 @@ enum {
NUM_FLASHMAP_ENTRIES = 8
};
#pragma pack(1)
enum {
AppleRegionTypeReserved = 0,
AppleRegionTypeRecovery = 1,
AppleRegionTypeMain = 2,
AppleRegionTypeNvram = 3,
AppleRegionTypeConfig = 4,
AppleRegionTypeDiagvault = 5
};
typedef UINT8 APPLE_REGION_TYPE;
///
/// Apple Firmware Volume - Region Info Type.
@ -52,6 +72,8 @@ typedef struct {
UINT32 FirmwareFeaturesMask;
UINT8 RegionType[NUM_FLASHMAP_ENTRIES];
FW_REGION_INFO FlashMap[NUM_FLASHMAP_ENTRIES];
UINT32 ExtendedFirmwareFeatures;
UINT32 ExtendedFirmwareFeaturesMask;
} SMBIOS_TABLE_TYPE128;
///
@ -63,15 +85,192 @@ typedef struct {
UINT16 Offset;
UINT16 Size;
UINT16 Data[];
} SMBIOS_TABLE_TYPE130;
} APPLE_SMBIOS_TABLE_TYPE130, SMBIOS_TABLE_TYPE130;
//
// It might be that 0x01 was intended for Pentium, and 0x08 for Atom.
// Reference binaries: AppleSmBios.efi and AppleSystemInfo.framework
//
// typedef struct {
// UINT32 MajorType;
// UINT32 MinorType;
// UINT32 NumberOfCores;
// CONST CHAR8 *MarketingName;
// CONST CHAR8 *TechnicalName;
// } PROCESSOR_INFO;
//
// The cpu types listed here originate from AppleSystemInfo.framework and are not
// complete per se. The match of a certain CPU is firstly done by MajorType and
// NumberOfCores, and MinorType does not need to match. For a more complete
// table refer to AppleProcessorType enum, which is built based on Mac dumps.
//
// <0201> 01 cores Intel Core Solo Intel Core Solo
// <0201> 02 cores Intel Core Duo Intel Core Duo
// <0301> 01 cores Intel Core 2 Solo Intel Core 2 Solo
// <0301> 02 cores Intel Core 2 Duo Intel Core 2 Duo
// <0401> 01 cores Single-Core Intel Xeon Single-Core Intel Xeon
// <0401> 02 cores Dual-Core Intel Xeon Dual-Core Intel Xeon
// <0402> 01 cores Single-Core Intel Xeon Single-Core Intel Xeon
// <0402> 02 cores Dual-Core Intel Xeon Dual-Core Intel Xeon
// <0402> 03 cores Unknown Intel Xeon Unknown Intel Xeon
// <0402> 04 cores Quad-Core Intel Xeon Quad-Core Intel Xeon
// <0501> 01 cores Single-Core Intel Xeon Single-Core Intel Xeon
// <0501> 02 cores Dual-Core Intel Xeon Dual-Core Intel Xeon
// <0501> 03 cores Unknown Intel Xeon Unknown Intel Xeon
// <0501> 04 cores Quad-Core Intel Xeon Quad-Core Intel Xeon
// <0501> 06 cores 6-Core Intel Xeon 6-Core Intel Xeon
// <0601> 01 cores Intel Core i5 Intel Core i5
// <0601> 02 cores Intel Core i5 Intel Core i5
// <0601> 03 cores Intel Core i5 Intel Core i5
// <0601> 04 cores Intel Core i5 Intel Core i5
// <0601> 06 cores Intel Core i5 Intel Core i5
// <0701> 01 cores Intel Core i7 Intel Core i7
// <0701> 02 cores Intel Core i7 Intel Core i7
// <0701> 03 cores Intel Core i7 Intel Core i7
// <0701> 04 cores Intel Core i7 Intel Core i7
// <0701> 06 cores Intel Core i7 Intel Core i7
// <0901> 01 cores Intel Core i3 Intel Core i3
// <0901> 02 cores Intel Core i3 Intel Core i3
// <0901> 03 cores Intel Core i3 Intel Core i3
// <0901> 04 cores Intel Core i3 Intel Core i3
// <0A01> 04 cores Quad-Core Intel Xeon E5 Quad-Core Intel Xeon E5
// <0A01> 06 cores 6-Core Intel Xeon E5 6-Core Intel Xeon E5
// <0A01> 08 cores 8-Core Intel Xeon E5 8-Core Intel Xeon E5
// <0A01> 10 cores 10-Core Intel Xeon E5 10-Core Intel Xeon E5
// <0A01> 12 cores 12-Core Intel Xeon E5 12-Core Intel Xeon E5
// <0B01> 01 cores Intel Core M Intel Core M
// <0B01> 02 cores Intel Core M Intel Core M
// <0B01> 03 cores Intel Core M Intel Core M
// <0B01> 04 cores Intel Core M Intel Core M
// <0C01> 01 cores Intel Core m3 Intel Core m3
// <0C01> 02 cores Intel Core m3 Intel Core m3
// <0C01> 03 cores Intel Core m3 Intel Core m3
// <0C01> 04 cores Intel Core m3 Intel Core m3
// <0D01> 01 cores Intel Core m5 Intel Core m5
// <0D01> 02 cores Intel Core m5 Intel Core m5
// <0D01> 03 cores Intel Core m5 Intel Core m5
// <0D01> 04 cores Intel Core m5 Intel Core m5
// <0E01> 01 cores Intel Core m7 Intel Core m7
// <0E01> 02 cores Intel Core m7 Intel Core m7
// <0E01> 03 cores Intel Core m7 Intel Core m7
// <0E01> 04 cores Intel Core m7 Intel Core m7
// <0F01> 08 cores Intel Xeon W Intel Xeon W
// <0F01> 10 cores Intel Xeon W Intel Xeon W
// <0F01> 14 cores Intel Xeon W Intel Xeon W
// <0F01> 18 cores Intel Xeon W Intel Xeon W
// <1001> 06 cores Intel Core i9 Intel Core i9
//
// Also see here for a list of CPUs used on Mac models:
// https://docs.google.com/spreadsheets/d/1x09b5-DGh8ozNwN5ZjAi7TMnOp4TDm6DbmrKu86i_bQ
//
//
// Apple Processor Type Information - Processor Types.
//
enum {
AppleProcessorTypeUnknown = 0x0000,
AppleProcessorTypeCoreSolo = 0x0201,
AppleProcessorTypeCore2DuoType1 = 0x0301,
AppleProcessorTypeCore2DuoType2 = 0x0302,
AppleProcessorTypeXeonPenrynType1 = 0x0401, // may not be used
AppleProcessorTypeXeonPenrynType2 = 0x0402,
AppleProcessorTypeXeon = 0x0501,
AppleProcessorTypeXeonE5 = 0x0A01,
AppleProcessorTypeCorei5Type1 = 0x0601,
AppleProcessorTypeCorei7Type1 = 0x0701,
AppleProcessorTypeCorei3Type1 = 0x0901,
AppleProcessorTypeCorei5Type2 = 0x0602,
AppleProcessorTypeCorei7Type2 = 0x0702,
AppleProcessorTypeCorei3Type2 = 0x0902,
AppleProcessorTypeCorei5Type3 = 0x0603,
AppleProcessorTypeCorei7Type3 = 0x0703,
AppleProcessorTypeCorei3Type3 = 0x0903,
AppleProcessorTypeCorei5Type4 = 0x0604,
AppleProcessorTypeCorei7Type4 = 0x0704,
AppleProcessorTypeCorei3Type4 = 0x0904,
AppleProcessorTypeCorei5Type5 = 0x0605, // NOTE: we are putting 0x0609 on IM191 (i5-8600), although it should be 0x0605.
AppleProcessorTypeCorei7Type5 = 0x0705,
AppleProcessorTypeCorei3Type5 = 0x0905,
AppleProcessorTypeCorei5Type6 = 0x0606, // i5 5250U (iMac16,1, MacBookAir7,1 and 7,2), i5 5675R (iMac16,2), i5 5257U (MacBookPro12,1)
AppleProcessorTypeCorei7Type6 = 0x0706, // ideal value for Broadwell i7, need confirmation
AppleProcessorTypeCorei3Type6 = 0x0906, // ideal value for Broadwell i3, need confirmation
// placeholder for i5Type7 (maybe 0x0607 ???)
AppleProcessorTypeCorei7Type7 = 0x0707, // i7 6700HQ (MacBookPro13,3)
// placeholder for i3Type7 (maybe 0x0907 ???)
AppleProcessorTypeCorei5Type8 = 0x0608, // i5 8210Y (MacBookAir8,1)
// placeholder for i7Type8 (maybe 0x0708 ???)
// placeholder for i3Type8 (maybe 0x0908 ???)
AppleProcessorTypeCorei5Type9 = 0x0609, // i5 8259U (MacBookPro15,2), i5 8500B (Macmini8,1)
AppleProcessorTypeCorei7Type9 = 0x0709, // i7 8850H (MacBookPro15,1), i7 8700B (Macmini8,1)
// placeholder for i3Type9 (maybe 0x0909 ???)
AppleProcessorTypeCoreMType1 = 0x0B01, // may not be used
AppleProcessorTypeCoreMType6 = 0x0B06, // M 5Y51 (MacBook8,1)
AppleProcessorTypeCoreM3Type1 = 0x0C01, // may not be used
AppleProcessorTypeCoreM3Type7 = 0x0C07, // m3-7Y32 (MacBook10,1)
AppleProcessorTypeCoreM5Type1 = 0x0D01, // may not be used
AppleProcessorTypeCoreM5Type7 = 0x0D07, // m5-6Y54 (MacBook9,1)
AppleProcessorTypeCoreM7Type1 = 0x0E01, // may not be used
AppleProcessorTypeCoreM7Type7 = 0x0E07, // might be used on Core m7 (SKL), need confirmation
AppleProcessorTypeXeonW = 0x0F01, // iMacPro1,1
AppleProcessorTypeCorei9Type1 = 0x1001, // may not be used
AppleProcessorTypeCorei9Type5 = 0x1005, // SKL-X i9, most likely to be invalid!
AppleProcessorTypeCorei9Type9 = 0x1009 // ideal value for Coffee Lake i9, need confirmation
};
// APPLE_PROCESSOR_TYPE_CLASS
enum {
AppleProcessorMajorUnknown = 0x00,
AppleProcessorMajorCore = 0x02,
AppleProcessorMajorCore2 = 0x03,
AppleProcessorMajorXeonPenryn = 0x04,
AppleProcessorMajorXeonNehalem = 0x05,
AppleProcessorMajorI5 = 0x06,
AppleProcessorMajorI7 = 0x07,
AppleProcessorMajorI3 = 0x09,
AppleProcessorMajorI9 = 0x10,
AppleProcessorMajorXeonE5 = 0x0A,
AppleProcessorMajorM = 0x0B,
AppleProcessorMajorM3 = 0x0C,
AppleProcessorMajorM5 = 0x0D,
AppleProcessorMajorM7 = 0x0E,
AppleProcessorMajorXeonW = 0x0F
};
///
/// Apple Processor Type (Type 131).
///
typedef struct {
UINT8 MinorType;
UINT8 MajorType;
} APPLE_PROCESSOR_TYPE_INFO;
typedef union {
APPLE_PROCESSOR_TYPE_INFO Detail;
UINT16 Type;
} APPLE_PROCESSOR_TYPE;
// APPLE_SMBIOS_TABLE_TYPE131
typedef struct {
SMBIOS_STRUCTURE Hdr;
UINT16 ProcessorType;
} SMBIOS_TABLE_TYPE131;
APPLE_PROCESSOR_TYPE ProcessorType;
UINT8 Reserved[2];
} APPLE_SMBIOS_TABLE_TYPE131, SMBIOS_TABLE_TYPE131;
///
/// Apple Processor Bus Speed (Type 132).
@ -94,8 +293,8 @@ typedef struct {
///
typedef struct {
SMBIOS_STRUCTURE Hdr;
UINT64 SMCVersion;
} SMBIOS_TABLE_TYPE134;
UINT8 SmcVersion[APPLE_SMBIOS_SMC_VERSION_SIZE];
} APPLE_SMBIOS_TABLE_TYPE134, SMBIOS_TABLE_TYPE134;
///
/// Union of all the possible SMBIOS record types.

218
Include/IndustryStandard/CpuId.h Executable file
View File

@ -0,0 +1,218 @@
/** @file
Copyright (C) 2016, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 CPUID_H
#define CPUID_H
#include <Register/Cpuid.h>
#define CPUID_L2_CACHE_FEATURE 0x80000006
// Feature Flag Values Reported in the EDX Register
#define CPUID_FEATURE_FPU BIT0 ///< Floating point unit on-chip
#define CPUID_FEATURE_VME BIT1 ///< Virtual Mode Extension
#define CPUID_FEATURE_DE BIT2 ///< Debugging Extension
#define CPUID_FEATURE_PSE BIT3 ///< Page Size Extension
#define CPUID_FEATURE_TSC BIT4 ///< Time Stamp Counter
#define CPUID_FEATURE_MSR BIT5 ///< Model Specific Registers
#define CPUID_FEATURE_PAE BIT6 ///< Physical Address Extension
#define CPUID_FEATURE_MCE BIT7 ///< Machine Check Exception
#define CPUID_FEATURE_CX8 BIT8 ///< CMPXCHG8B
#define CPUID_FEATURE_APIC BIT9 ///< On-chip APIC
#define CPUID_FEATURE_SEP BIT11 ///< Fast System Call
#define CPUID_FEATURE_MTRR BIT12 ///< Memory Type Range Register
#define CPUID_FEATURE_PGE BIT13 ///< Page Global Enable
#define CPUID_FEATURE_MCA BIT14 ///< Machine Check Architecture
#define CPUID_FEATURE_CMOV BIT15 ///< Conditional Move Instruction
#define CPUID_FEATURE_PAT BIT16 ///< Page Attribute Table
#define CPUID_FEATURE_PSE36 BIT17 ///< 36-bit Page Size Extension
#define CPUID_FEATURE_PSN BIT18 ///< Processor Serial Number
#define CPUID_FEATURE_CLFSH BIT19 ///< CLFLUSH Instruction Supported
#define CPUID_FEATURE_RESV20 BIT20 ///< Reserved
#define CPUID_FEATURE_DS BIT21 ///< Debug Store
#define CPUID_FEATURE_ACPI BIT22 ///< Thermal Monitor and Clock Control
#define CPUID_FEATURE_MMX BIT23 ///< MMX Supported
#define CPUID_FEATURE_FXSR BIT24 ///< Fast Floating Point Save/Restore
#define CPUID_FEATURE_SSE BIT25 ///< Streaming SIMD Extensions
#define CPUID_FEATURE_SSE2 BIT26 ///< Streaming SIMD Extensions 2
#define CPUID_FEATURE_SS BIT27 ///< Self-Snoop
#define CPUID_FEATURE_HTT BIT28 ///< Hyper-Threading Technology
#define CPUID_FEATURE_TM BIT29 ///< Thermal Monitor (TM1)
#define CPUID_FEATURE_IA64 BIT30 ///< Itanium Family Emulating IA-32
#define CPUID_FEATURE_PBE BIT31 ///< Pending Break Enable
// Feature Flag Values Reported in the ECX Register
#define CPUID_FEATURE_SSE3 BIT32 ///< Streaming SIMD extensions 3
#define CPUID_FEATURE_PCLMULQDQ BIT33 ///< PCLMULQDQ Instruction
#define CPUID_FEATURE_DTES64 BIT34 ///< 64-Bit Debug Store
#define CPUID_FEATURE_MONITOR BIT35 ///< MONITOR/MWAIT
#define CPUID_FEATURE_DSCPL BIT36 ///< CPL Qualified Debug Store
#define CPUID_FEATURE_VMX BIT37 ///< Virtual Machine Extensions (VMX)
#define CPUID_FEATURE_SMX BIT38 ///< Safer Mode Extensions (SMX)
#define CPUID_FEATURE_EST BIT39 ///< Enhanced Intel SpeedStep (GV3)
#define CPUID_FEATURE_TM2 BIT40 ///< Thermal Monitor 2
#define CPUID_FEATURE_SSSE3 BIT41 ///< Supplemental SSE3 Instructions
#define CPUID_FEATURE_CID BIT42 ///< L1 Context ID
#define CPUID_FEATURE_SEGLIM64 BIT43 ///< 64-bit segment limit checking
#define CPUID_FEATURE_RESVH12 BIT44 ///< Reserved
#define CPUID_FEATURE_CX16 BIT45 ///< CMPXCHG16B Instruction
#define CPUID_FEATURE_xTPR BIT46 ///< Task Priority Update Control
#define CPUID_FEATURE_PDCM BIT47 ///< Perfmon/Debug Capability MSR
#define CPUID_FEATURE_RESVH16 BIT48 ///< Reserved
#define CPUID_FEATURE_PCID BIT49 ///< ASID-PCID support
#define CPUID_FEATURE_DCA BIT50 ///< Direct Cache Access
#define CPUID_FEATURE_SSE4_1 BIT51 ///< Streaming SIMD Extensions 4.1
#define CPUID_FEATURE_SSE4_2 BIT52 ///< Streaming SIMD Extensions 4.1
#define CPUID_FEATURE_xAPIC BIT53 ///< Extended xAPIC Support
#define CPUID_FEATURE_MOVBE BIT54 ///< MOVBE Instruction
#define CPUID_FEATURE_POPCNT BIT55 ///< POPCNT Instruction
#define CPUID_FEATURE_TSCTMR BIT56 ///< TSC deadline timer
#define CPUID_FEATURE_AES BIT57 ///< AES instructions
#define CPUID_FEATURE_XSAVE BIT58 ///< XSAVE/XSTOR States
#define CPUID_FEATURE_OSXSAVE BIT59 ///< OS Has Enabled XSETBV/XGETBV
#define CPUID_FEATURE_AVX1_0 BIT60 ///< AVX 1.0 instructions
#define CPUID_FEATURE_RDRAND BIT61 ///< RDRAND instruction
#define CPUID_FEATURE_F16C BIT62 ///< Float16 convert instructions
#define CPUID_FEATURE_VMM BIT63 ///< VMM (Hypervisor) present
// The CPUID_EXTFEATURE_XXX values define 64-bit values
// returned in %ecx:%edx to a CPUID request with %eax of 0x80000001:
#define CPUID_EXTFEATURE_SYSCALL BIT11 ///< SYSCALL/sysret
#define CPUID_EXTFEATURE_XD BIT20 ///< eXecute Disable
#define CPUID_EXTFEATURE_1GBPAGE BIT21 ///< 1GB pages
#define CPUID_EXTFEATURE_RDTSCP BIT27 ///< RDTSCP
#define CPUID_EXTFEATURE_EM64T BIT29 ///< Extended Mem 64 Technology
#define CPUID_EXTFEATURE_LAHF BIT32 ///< LAFH/SAHF instructions
// The CPUID_EXTFEATURE_XXX values define 64-bit values
// returned in %ecx:%edx to a CPUID request with %eax of 0x80000007:
#define CPUID_EXTFEATURE_TSCI BIT8 ///< TSC Invariant
// When the EAX register contains a value of 2, the CPUID instruction loads
// the EAX, EBX, ECX, and EDX registers with descriptors that indicate the
// processor's cache and TLB characteristics.
// CPUID_CACHE_SIZE
/// Number of 8-bit descriptor values
#define CPUID_CACHE_SIZE 16
enum {
CpuIdCacheNull = 0x00, ///< NULL
CpuIdCacheItlb4K_32_4 = 0x01, ///< Inst TLB: 4K pages, 32 ents, 4-way
CpuIdCacheItlb4M_2 = 0x02, ///< Inst TLB: 4M pages, 2 ents
CpuIdCacheDtlb4K_64_4 = 0x03, ///< Data TLB: 4K pages, 64 ents, 4-way
CpuIdCacheDtlb4M_8_4 = 0x04, ///< Data TLB: 4M pages, 8 ents, 4-way
CpuIdCacheDtlb4M_32_4 = 0x05, ///< Data TLB: 4M pages, 32 ents, 4-way
CpuIdCacheL1I_8K = 0x06, ///< Icache: 8K
CpuIdCacheL1I_16K = 0x08, ///< Icache: 16K
CpuIdCacheL1I_32K = 0x09, ///< Icache: 32K, 4-way, 64 bytes
CpuIdCacheL1D_8K = 0x0A, ///< Dcache: 8K
CpuIdCacheL1D_16K = 0x0C, ///< Dcache: 16K
CpuIdCacheL1D_16K_4_32 = 0x0D, ///< Dcache: 16K, 4-way, 64 byte, ECC
CpuIdCacheL2_256K_8_64 = 0x21, ///< L2: 256K, 8-way, 64 bytes
CpuIdCacheL3_512K = 0x22, ///< L3: 512K
CpuIdCacheL3_1M = 0x23, ///< L3: 1M
CpuIdCacheL3_2M = 0x25, ///< L3: 2M
CpuIdCacheL3_4M = 0x29, ///< L3: 4M
CpuIdCacheL1D_32K_8 = 0x2C, ///< Dcache: 32K, 8-way, 64 byte
CpuIdCacheL1I_32K_8 = 0x30, ///< Icache: 32K, 8-way
CpuIdCacheL2_128K_S4 = 0x39, ///< L2: 128K, 4-way, sectored, 64B
CpuIdCacheL2_192K_S6 = 0x3A, ///< L2: 192K, 6-way, sectored, 64B
CpuIdCacheL2_128K_S2 = 0x3B, ///< L2: 128K, 2-way, sectored, 64B
CpuIdCacheL2_256K_S4 = 0x3C, ///< L2: 256K, 4-way, sectored, 64B
CpuIdCacheL2_384K_S6 = 0x3D, ///< L2: 384K, 6-way, sectored, 64B
CpuIdCacheL2_512K_S4 = 0x3E, ///< L2: 512K, 4-way, sectored, 64B
CpuIdCacheNoCache = 0x40, ///< No 2nd level or 3rd-level cache
CpuIdCacheL2_128K = 0x41, ///< L2: 128K
CpuIdCacheL2_256K = 0x42, ///< L2: 256K
CpuIdCacheL2_512K = 0x43, ///< L2: 512K
CpuIdCacheL2_1M_4 = 0x44, ///< L2: 1M, 4-way
CpuIdCacheL2_2M_4 = 0x45, ///< L2: 2M, 4-way
CpuIdCacheL3_4M_4_64 = 0x46, ///< L3: 4M, 4-way, 64 bytes
CpuIdCacheL3_8M_8_64 = 0x47, ///< L3: 8M, 8-way, 64 bytes*/
CpuIdCacheL2_3M_12_64 = 0x48, ///< L3: 3M, 8-way, 64 bytes*/
CpuIdCacheL2_4M_16_64 = 0x49, ///< L2: 4M, 16-way, 64 bytes
CpuIdCacheL2_6M_12_64 = 0x4A, ///< L2: 6M, 12-way, 64 bytes
CpuIdCacheL2_8M_16_64 = 0x4B, ///< L2: 8M, 16-way, 64 bytes
CpuIdCacheL2_12M_12_64 = 0x4C, ///< L2: 12M, 12-way, 64 bytes
CpuIdCacheL2_16M_16_64 = 0x4D, ///< L2: 16M, 16-way, 64 bytes
CpuIdCacheL2_6M_24_64 = 0x4E, ///< L2: 6M, 24-way, 64 bytes
CpuIdCacheItlb64 = 0x50, ///< Inst TLB: 64 entries
CpuIdCacheItlb128 = 0x51, ///< Inst TLB: 128 entries
CpuIdCacheItlb256 = 0x52, ///< Inst TLB: 256 entries
CpuIdCacheItlb4M2M_7 = 0x55, ///< Inst TLB: 4M/2M, 7 entries
CpuIdCacheDtlb4M_16_4 = 0x56, ///< Data TLB: 4M, 16 entries, 4-way
CpuIdCacheDtlb4K_16_4 = 0x57, ///< Data TLB: 4K, 16 entries, 4-way
CpuIdCacheDtlb4M2M_32_4 = 0x5A, ///< Data TLB: 4M/2M, 32 entries
CpuIdCacheDtlb64 = 0x5B, ///< Data TLB: 64 entries
CpuIdCacheDtlb128 = 0x5C, ///< Data TLB: 128 entries
CpuIdCacheDtlb256 = 0x5D, ///< Data TLB: 256 entries
CpuIdCacheL1D_16K_8_64 = 0x60, ///< Data cache: 16K, 8-way, 64 bytes
CpuIdCacheL1D_8K_4_64 = 0x66, ///< Data cache: 8K, 4-way, 64 bytes
CpuIdCacheL1D_16K_4_64 = 0x67, ///< Data cache: 16K, 4-way, 64 bytes
CpuIdCacheL1D_32K_4_64 = 0x68, ///< Data cache: 32K, 4-way, 64 bytes
CpuIdCacheTRACE_12K_8 = 0x70, ///< Trace cache 12K-uop, 8-way
CpuIdCacheTRACE_16K_8 = 0x71, ///< Trace cache 16K-uop, 8-way
CpuIdCacheTRACE_32K_8 = 0x72, ///< Trace cache 32K-uop, 8-way
CpuIdCacheTRACE_64K_8 = 0x73, ///< Trace cache 64K-uop, 8-way
CpuIdCacheL2_1M_4_64 = 0x78, ///< L2: 1M, 4-way, 64 bytes
CpuIdCacheL2_128K_8_64_2 = 0x79, ///< L2: 128K, 8-way, 64b, 2 lines/sec
CpuIdCacheL2_256K_8_64_2 = 0x7A, ///< L2: 256K, 8-way, 64b, 2 lines/sec
CpuIdCacheL2_512K_8_64_2 = 0x7B, ///< L2: 512K, 8-way, 64b, 2 lines/sec
CpuIdCacheL2_1M_8_64_2 = 0x7C, ///< L2: 1M, 8-way, 64b, 2 lines/sec
CpuIdCacheL2_2M_8_64 = 0x7D, ///< L2: 2M, 8-way, 64 bytes
CpuIdCacheL2_512K_2_64 = 0x7F, ///< L2: 512K, 2-way, 64 bytes
CpuIdCacheL2_256K_8_32 = 0x82, ///< L2: 256K, 8-way, 32 bytes
CpuIdCacheL2_512K_8_32 = 0x83, ///< L2: 512K, 8-way, 32 bytes
CpuIdCacheL2_1M_8_32 = 0x84, ///< L2: 1M, 8-way, 32 bytes
CpuIdCacheL2_2M_8_32 = 0x85, ///< L2: 2M, 8-way, 32 bytes
CpuIdCacheL2_512K_4_64 = 0x86, ///< L2: 512K, 4-way, 64 bytes
CpuIdCacheL2_1M_8_64 = 0x87, ///< L2: 1M, 8-way, 64 bytes
CpuIdCacheItlb4K_128_4 = 0xB0, ///< ITLB: 4KB, 128 entries, 4-way
CpuIdCacheItlb4M_4_4 = 0xB1, ///< ITLB: 4MB, 4 entries, 4-way, or
CpuIdCacheItlb2M_8_4 = 0xB1, ///< ITLB: 2MB, 8 entries, 4-way, or
CpuIdCacheItlb4M_8 = 0xB1, ///< ITLB: 4MB, 8 entries
CpuIdCacheItlb4K_64_4 = 0xB2, ///< ITLB: 4KB, 64 entries, 4-way
CpuIdCacheDtlb4K_128_4 = 0xB3, ///< DTLB: 4KB, 128 entries, 4-way
CpuIdCacheDtlb4K_256_4 = 0xB4, ///< DTLB: 4KB, 256 entries, 4-way
CpuIdCache2TLB_4K_512_4 = 0xCA, ///< 2nd-level TLB: 4KB, 512, 4-way
CpuIdCacheL3_512K_4_64 = 0xD0, ///< L3: 512KB, 4-way, 64 bytes
CpuIdCacheL3_1M_4_64 = 0xD1, ///< L3: 1M, 4-way, 64 bytes
CpuIdCacheL3_2M_4_64 = 0xD2, ///< L3: 2M, 4-way, 64 bytes
CpuIdCacheL3_1M_8_64 = 0xD6, ///< L3: 1M, 8-way, 64 bytes
CpuIdCacheL3_2M_8_64 = 0xD7, ///< L3: 2M, 8-way, 64 bytes
CpuIdCacheL3_4M_8_64 = 0xD8, ///< L3: 4M, 8-way, 64 bytes
CpuIdCacheL3_1M5_12_64 = 0xDC, ///< L3: 1.5M, 12-way, 64 bytes
CpuIdCacheL3_3M_12_64 = 0xDD, ///< L3: 3M, 12-way, 64 bytes
CpuIdCacheL3_6M_12_64 = 0xDE, ///< L3: 6M, 12-way, 64 bytes
CpuIdCacheL3_2M_16_64 = 0xE2, ///< L3: 2M, 16-way, 64 bytes
CpuIdCacheL3_4M_16_64 = 0xE3, ///< L3: 4M, 16-way, 64 bytes
CpuIdCacheL3_8M_16_64 = 0xE4, ///< L3: 8M, 16-way, 64 bytes
CpuIdCachePrefetch64 = 0xF0, ///< 64-Byte Prefetching
CpuIdCachePrefetch128 = 0xF1, ///< 128-Byte Prefetching
};
#define CPUID_VENDOR_INTEL 0x756E6547
#define CPUID_VENDOR_AMD 0x68747541
#endif // CPUID_H

View File

@ -0,0 +1,84 @@
/** @file
Copyright (C) 2016, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 GENERIC_ICH_H
#define GENERIC_ICH_H
// GenericIchDefs Generic ICH Definitions.
//
// Definitions beginning with "R_" are registers.
// Definitions beginning with "B_" are bits within registers.
// Definitions beginning with "V_" are meaningful values of bits within the registers.
// IchPciAddressing PCI Bus Address for ICH.
#define PCI_BUS_NUMBER_ICH 0x00 ///< ICH is on PCI Bus 0.
#define PCI_DEVICE_NUMBER_ICH 31 ///< ICH is Device 31.
#define PCI_FUNCTION_NUMBER_ICH_LPC 0 ///< LPC is Function 0.
#define PCI_FUNCTION_NUMBER_ICH_PMC 2 ///< PMC is Function 2.
#define V_ICH_PCI_VENDOR_ID 0x8086 ///< Intel vendor-id
// IchAcpiCntr Control for the ICH's ACPI Counter.
#define R_ICH_ACPI_BASE 0x40
#define B_ICH_ACPI_BASE_BAR 0x0000FF80
#define R_ICH_ACPI_CNTL 0x44 ///< See ACPI_CNTL
#define B_ICH_ACPI_CNTL_ACPI_EN 0x80
#define R_ICH_BAR2_BASE 0x20
#define B_ICH_BAR2_BASE_BAR 0x0000FFC0
#define B_ICH_BAR2_BASE_BAR_EN 0x1
// Pre Intel Sunrisepoint
#define R_ICH_LPC_ACPI_BASE R_ICH_ACPI_BASE
#define B_ICH_LPC_ACPI_BASE_BAR B_ICH_ACPI_BASE_BAR
#define R_ICH_LPC_ACPI_CNTL R_ICH_ACPI_CNTL
#define B_ICH_LPC_ACPI_CNTL_ACPI_EN B_ICH_ACPI_CNTL_ACPI_EN
// Intel Sunrisepoint
#define R_ICH_PMC_ACPI_BASE R_ICH_ACPI_BASE
#define B_ICH_PMC_ACPI_BASE_BAR B_ICH_ACPI_BASE_BAR
#define R_ICH_PMC_ACPI_CNTL R_ICH_ACPI_CNTL
#define B_ICH_PMC_ACPI_CNTL_ACPI_EN B_ICH_ACPI_CNTL_ACPI_EN
// Intel Coffee Lake
#define R_ICH_PMC_BAR2_BASE R_ICH_BAR2_BASE
#define B_ICH_PMC_BAR2_BASE_BAR B_ICH_BAR2_BASE_BAR
#define B_ICH_PMC_BAR2_BASE_BAR_EN B_ICH_BAR2_BASE_BAR_EN
// AMD Bolton (AMD Bolton Register Reference Guide 3.03)
#define R_AMD_ACPI_MMIO_BASE 0xFED80000 ///< AcpiMMioAddr (3-268)
#define R_AMD_ACPI_MMIO_PMIO_BASE 0x300 ///< PMIO (3-268)
#define R_AMD_ACPI_PM_TMR_BLOCK 0x64 ///< AcpiPmTmrBlk (3-289)
// IchAcpiTimer The ICH's ACPI Timer.
#define R_ACPI_PM1_TMR 0x08
#define V_ACPI_TMR_FREQUENCY 3579545
#define V_ACPI_PM1_TMR_MAX_VAL 0x01000000 ///< The timer is 24 bit overflow.
/// Macro to generate the PCI address of any given ICH LPC Register.
#define PCI_ICH_LPC_ADDRESS(Register) \
((UINTN)(PCI_LIB_ADDRESS (PCI_BUS_NUMBER_ICH, PCI_DEVICE_NUMBER_ICH, PCI_FUNCTION_NUMBER_ICH_LPC, (Register))))
/// Macro to generate the PCI address of any given ICH PMC Register.
#define PCI_ICH_PMC_ADDRESS(Register) \
((UINTN)(PCI_LIB_ADDRESS (PCI_BUS_NUMBER_ICH, PCI_DEVICE_NUMBER_ICH, PCI_FUNCTION_NUMBER_ICH_PMC, (Register))))
#endif // GENERIC_ICH_H

View File

@ -0,0 +1,227 @@
/** @file
Copyright (C) 2016 - 2018, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_PROCESSOR_INFO_H
#define OC_PROCESSOR_INFO_H
// SandyBridge/IvyBridge bus clock is fixed at 100MHz
#define BRIDGE_BCLK 100
#define BASE_NHM_CLOCK_SOURCE 133333333ULL
//
// Skylake bus clock is fixed at 100MHz
// This constant is also known as BASE_ART_CLOCK_SOURCE in XNU
//
#define CLIENT_ART_CLOCK_SOURCE 24000000ULL
#define SERVER_ART_CLOCK_SOURCE 25000000ULL
#define ATOM_ART_CLOCK_SOURCE 19200000ULL
#define DEFAULT_ART_CLOCK_SOURCE CLIENT_ART_CLOCK_SOURCE
#define MSR_PIC_MSG_CONTROL 0x2E
#define MSR_CORE_THREAD_COUNT 0x35
#define EFI_PLATFORM_INFORMATION 0x000000CE
#define N_EFI_PLATFORM_INFO_MIN_RATIO 40
#define B_EFI_PLATFORM_INFO_RATIO_MASK 0xFF
#define N_EFI_PLATFORM_INFO_MAX_RATIO 8
#define B_EFI_PLATFORM_INFO_TDC_TDP_LIMIT (1 << 29)
#define N_EFI_PLATFORM_INFO_RATIO_LIMIT 28
#define B_EFI_PLATFORM_INFO_RATIO_LIMIT (1 << 28)
#define B_EFI_PLATFORM_INFO_SMM_SAVE_CONTROL (1 << 16)
#define N_EFI_PLATFORM_INFO_PROG_TCC_ACTIVATION_OFFSET 30
#define B_EFI_PLATFORM_INFO_PROG_TCC_ACTIVATION_OFFSET (1 << 30)
//#define PLATFORM_INFO_SET_TDP
#define MSR_PMG_IO_CAPTURE_BASE 0xE4
#define MSR_IA32_EXT_CONFIG 0xEE
#define MSR_FEATURE_CONFIG 0x13C
#define MSR_FLEX_RATIO 0x194
#define FLEX_RATIO_LOCK (1U << 20U)
#define FLEX_RATIO_EN (1U << 16U)
#define MSR_IA32_PERF_CONTROL 0x199
#define MSR_THERM2_CTL 0x19D
#define MSR_IA32_MISC_ENABLES 0x1A0
#define TURBO_DISABLE_MASK ((UINT64)1 << 38)
#define TURBO_MODE_DISABLE_BIT 38
#define MSR_TEMPERATURE_TARGET 0x1A2
#define MSR_MISC_PWR_MGMT 0x1AA
#define MISC_PWR_MGMT_EIST_HW_DIS (1 << 0)
#define MISC_PWR_MGMT_LOCK (1 << 13)
#define MAX_RATIO_LIMIT_8C_OFFSET 56
#define MAX_RATIO_LIMIT_7C_OFFSET 48
#define MAX_RATIO_LIMIT_6C_OFFSET 40
#define MAX_RATIO_LIMIT_5C_OFFSET 32
#define MAX_RATIO_LIMIT_4C_OFFSET 24
#define MAX_RATIO_LIMIT_3C_OFFSET 16
#define MAX_RATIO_LIMIT_2C_OFFSET 8
#define MAX_RATIO_LIMIT_1C_OFFSET 0
#define MAX_RATIO_LIMIT_MASK 0xff
#define MSR_IA32_ENERGY_PERFORMANCE_BIAS 0x1B0
#define ENERGY_POLICY_PERFORMANCE 0
#define ENERGY_POLICY_NORMAL 6
#define ENERGY_POLICY_POWERSAVE 15
#define MSR_POWER_CTL 0x1FC
#define MSR_LT_LOCK_MEMORY 0x2E7
#define MSR_IA32_CR_PAT 0x277
// Sandy Bridge & JakeTown specific 'Running Average Power Limit' MSR's.
#define MSR_PP0_CURRENT_CONFIG 0x601
#define PP0_CURRENT_LIMIT (112 << 3) ///< 112 A
#define MSR_PP1_CURRENT_CONFIG 0x602
#define PP1_CURRENT_LIMIT (35 << 3) ///< 35 A
#define MSR_PKG_POWER_SKU_UNIT 0x606
#define MSR_PKGC3_IRTL 0x60A
#define MSR_PKGC6_IRTL 0x60B
#define MSR_PKGC7_IRTL 0x60C
#define IRTL_VALID (1 << 15)
#define IRTL_1_NS (0 << 10)
#define IRTL_32_NS (1 << 10)
#define IRTL_1024_NS (2 << 10)
#define IRTL_32768_NS (3 << 10)
#define IRTL_1048576_NS (4 << 10)
#define IRTL_33554432_NS (5 << 10)
#define IRTL_RESPONSE_MASK (0x3ff)
// long duration in low dword, short duration in high dword
#define MSR_PKG_POWER_LIMIT 0x610
#define PKG_POWER_LIMIT_MASK 0x7fff
#define PKG_POWER_LIMIT_EN (1 << 15)
#define PKG_POWER_LIMIT_CLAMP (1 << 16)
#define PKG_POWER_LIMIT_TIME_SHIFT 17
#define PKG_POWER_LIMIT_TIME_MASK 0x7f
#define MSR_PKG_ENERGY_STATUS 0x611
#define MSR_PKG_PERF_STATUS 0x613
#define MSR_PKG_POWER_SKU 0x614
// Sandy Bridge IA (Core) domain MSR's.
#define MSR_PP0_POWER_LIMIT 0x638
#define MSR_PP0_ENERGY_STATUS 0x639
#define MSR_PP0_POLICY 0x63A
#define MSR_PP0_PERF_STATUS 0x63B
// Sandy Bridge Uncore (IGPU) domain MSR's (Not on JakeTown).
#define MSR_PP1_POWER_LIMIT 0x640
#define MSR_PP1_ENERGY_STATUS 0x641
#define MSR_PP1_POLICY 0x642
// JakeTown only Memory MSR's.
#define MSR_DRAM_POWER_LIMIT 0x618
#define MSR_DRAM_ENERGY_STATUS 0x619
#define MSR_DRAM_PERF_STATUS 0x61B
#define MSR_DRAM_POWER_INFO 0x61C
/// x86 Page Address Translation
enum {
PageAddressTranslationUncached = 0,
PageAddressTranslationWriteCombining = 1,
PageAddressTranslationWriteThrough = 4,
PageAddressTranslationWriteProtected = 5,
PageAddressTranslationWriteBack = 6,
/// Uncached, but can be overriden by MTRR
PageAddressTranslationOverridableUncached = 7,
};
#define K8_FIDVID_STATUS 0xC0010042
#define K10_COFVID_STATUS 0xC0010071
#define K10_PSTATE_STATUS 0xC0010064
#define CPU_MODEL_DOTHAN 0x0D ///< Dothan
#define CPU_MODEL_YONAH 0x0E ///< Sossaman, Yonah
#define CPU_MODEL_MEROM 0x0F ///< Allendale, Conroe, Kentsfield, Woodcrest, Clovertown, Tigerton, Merom
#define CPU_MODEL_PENRYN 0x17 ///< Wolfdale, Yorkfield, Harpertown, Penryn
#define CPU_MODEL_NEHALEM 0x1A ///< Bloomfield. Nehalem-EP, Nehalem-WS, Gainestown
#define CPU_MODEL_ATOM 0x1C ///< Atom
#define CPU_MODEL_FIELDS 0x1E ///< Lynnfield, Clarksfield, Jasper Forest
#define CPU_MODEL_DALES 0x1F ///< Havendale, Auburndale
#define CPU_MODEL_NEHALEM_EX 0x2E ///< Beckton
#define CPU_MODEL_DALES_32NM 0x25 ///< Clarkdale, Arrandale
#define CPU_MODEL_WESTMERE 0x2C ///< Gulftown, Westmere-EP, Westmere-WS
#define CPU_MODEL_WESTMERE_EX 0x2F
#define CPU_MODEL_SANDYBRIDGE 0x2A ///< Sandy Bridge
#define CPU_MODEL_JAKETOWN 0x2D ///< Sandy Bridge Xeon E5, Core i7 Extreme
#define CPU_MODEL_IVYBRIDGE 0x3A ///< Ivy Bridge
#define CPU_MODEL_IVYBRIDGE_EP 0x3E
#define CPU_MODEL_CRYSTALWELL 0x46
#define CPU_MODEL_HASWELL 0x3C
#define CPU_MODEL_HASWELL_EP 0x3F ///< Haswell MB
#define CPU_MODEL_HASWELL_ULT 0x45 ///< Haswell ULT
#define CPU_MODEL_BROADWELL 0x3D ///< Broadwell
#define CPU_MODEL_BROADWELL_EP 0x4F ///< Broadwell_EP
#define CPU_MODEL_BROADWELL_ULX 0x3D
#define CPU_MODEL_BROADWELL_ULT 0x3D
#define CPU_MODEL_BRYSTALWELL 0x47
#define CPU_MODEL_AIRMONT 0x4C ///< CherryTrail / Braswell
#define CPU_MODEL_AVOTON 0x4D ///< Avaton/Rangely
#define CPU_MODEL_SKYLAKE 0x4E ///< Skylake-S
#define CPU_MODEL_SKYLAKE_ULT 0x4E
#define CPU_MODEL_SKYLAKE_ULX 0x4E
#define CPU_MODEL_SKYLAKE_DT 0x5E
#define CPU_MODEL_SKYLAKE_W 0x55
#define CPU_MODEL_GOLDMONT 0x5C ///< Apollo Lake
#define CPU_MODEL_DENVERTON 0x5F ///< Goldmont Microserver
#define CPU_MODEL_CANNONLAKE 0x66
#define CPU_MODEL_XEON_MILL 0x85 ///< Knights Mill
#define CPU_MODEL_KABYLAKE 0x8E ///< Kabylake Dektop
#define CPU_MODEL_KABYLAKE_ULT 0x8E
#define CPU_MODEL_KABYLAKE_ULX 0x8E
#define CPU_MODEL_KABYLAKE_DT 0x9E
#define CPU_MODEL_COFFEELAKE 0x9E
#define CPU_MODEL_COFFEELAKE_ULT 0x9E
#define CPU_MODEL_COFFEELAKE_ULX 0x9E
#define CPU_MODEL_COFFEELAKE_DT 0x9E
#define CPU_MODEL_ICELAKE_Y 0x7D
#define CPU_MODEL_ICELAKE_U 0x7E
#define CPU_MODEL_ICELAKE_SP 0x9F /* Some variation of Ice Lake */
#define CPU_MODEL_COMETLAKE_S 0xA5 /* desktop CometLake */
#define CPU_MODEL_COMETLAKE_Y 0xA5 /* aka 10th generation Amber Lake Y */
#define CPU_MODEL_COMETLAKE_U 0xA6
#define CPU_SOCKET_UNKNOWN 0x02
#define CPU_SOCKET_PGA478 0x0F
#define CPU_SOCKET_LGA771 0x14
#define CPU_SOCKET_LGA775 0x15
#define CPU_SOCKET_LGA1156 0x1D
#define CPU_SOCKET_LGA1366 0x19
#define AMD_CPU_FAMILY 0xF
#define AMD_CPU_EXT_FAMILY_15H 0x6
#define AMD_CPU_EXT_FAMILY_16H 0x7
#define AMD_CPU_EXT_FAMILY_17H 0x8
// CPU_P_STATE_COORDINATION
/// P-State Coordination
typedef enum {
/// The OS Power Manager is responsible for coordinating the P-state among logical
/// processors with dependencies and must initiate the transition on all of those Logical Processors.
CpuPStateCoordinationSoftwareAll = 0xFC,
/// The OS Power Manager is responsible for coordinating the P-state among logical
/// processors with dependencies and may initiate the transition on any of those Logical Processors.
CpuPStateCoordinationSoftwareAny = 0xFD,
/// The processor hardware is responsible for coordinating the P-state among logical
/// processors dependencies. The OS is responsible for keeping the P-state request up to date on all
/// logical processors.
CpuPStateCoordinationHardwareAll = 0xFE
} CPU_P_STATE_COORDINATION;
#endif // OC_PROCESSOR_INFO_H

View File

@ -0,0 +1,153 @@
/** @file
x64 Long Mode Virtual Memory Management Definitions
References:
1) IA-32 Intel(R) Architecture Software Developer's Manual Volume 1:Basic Architecture, Intel
2) IA-32 Intel(R) Architecture Software Developer's Manual Volume 2:Instruction Set Reference, Intel
3) IA-32 Intel(R) Architecture Software Developer's Manual Volume 3:System Programmer's Guide, Intel
4) AMD64 Architecture Programmer's Manual Volume 2: System Programming
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
Copyright (c) 2011, dmazar. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef VIRTUAL_MEMORY_H
#define VIRTUAL_MEMORY_H
#pragma pack(push, 1)
//
// Page-Map Level-4 Offset (PML4) and
// Page-Directory-Pointer Offset (PDPE) entries 4K & 2MB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Reserved:1; // Reserved
UINT64 MustBeZero:2; // Must Be Zero
UINT64 Available:3; // Available for use by system software
UINT64 PageTableBaseAddress:40; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // No Execute bit
} Bits;
UINT64 Uint64;
} PAGE_MAP_AND_DIRECTORY_POINTER;
//
// Page Table Entry 4KB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page
UINT64 PAT:1; //
UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
UINT64 Available:3; // Available for use by system software
UINT64 PageTableBaseAddress:40; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution
} Bits;
UINT64 Uint64;
} PAGE_TABLE_4K_ENTRY;
//
// Page Table Entry 2MB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page
UINT64 MustBe1:1; // Must be 1
UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
UINT64 Available:3; // Available for use by system software
UINT64 PAT:1; //
UINT64 MustBeZero:8; // Must be zero;
UINT64 PageTableBaseAddress:31; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution
} Bits;
UINT64 Uint64;
} PAGE_TABLE_2M_ENTRY;
//
// Page Table Entry 1GB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page
UINT64 MustBe1:1; // Must be 1
UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
UINT64 Available:3; // Available for use by system software
UINT64 PAT:1; //
UINT64 MustBeZero:17; // Must be zero;
UINT64 PageTableBaseAddress:22; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution
} Bits;
UINT64 Uint64;
} PAGE_TABLE_1G_ENTRY;
typedef union {
struct {
UINT64 PhysPgOffset:12; // 0 = Physical Page Offset
UINT64 PTOffset:9; // 0 = Page Table Offset
UINT64 PDOffset:9; // 0 = Page Directory Offset
UINT64 PDPOffset:9; // 0 = Page Directory Pointer Offset
UINT64 PML4Offset:9; // 0 = Page Map Level 4 Offset
UINT64 SignExtend:16; // 0 = Sign Extend
} Pg4K;
struct {
UINT64 PhysPgOffset:21; // 0 = Physical Page Offset
UINT64 PDOffset:9; // 0 = Page Directory Offset
UINT64 PDPOffset:9; // 0 = Page Directory Pointer Offset
UINT64 PML4Offset:9; // 0 = Page Map Level 4 Offset
UINT64 SignExtend:16; // 0 = Sign Extend
} Pg2M;
struct {
UINT64 PhysPgOffset:30; // 0 = Physical Page Offset
UINT64 PDPOffset:9; // 0 = Page Directory Pointer Offset
UINT64 PML4Offset:9; // 0 = Page Map Level 4 Offset
UINT64 SignExtend:16; // 0 = Sign Extend
} Pg1G;
UINT64 Uint64;
} VIRTUAL_ADDR;
#define VA_FIX_SIGN_EXTEND(VA) ((VA).Pg4K.SignExtend = ((VA).Pg4K.PML4Offset & 0x100U) ? 0xFFFFU : 0U);
#pragma pack(pop)
#define CR3_ADDR_MASK 0x000FFFFFFFFFF000ull
#define CR3_FLAG_PWT 0x0000000000000008ull
#define CR3_FLAG_PCD 0x0000000000000010ull
#define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull
#define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull
#define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull
#endif // VIRTUAL_MEMORY_H

View File

@ -0,0 +1,77 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_CHUNKLIST_LIB_H
#define APPLE_CHUNKLIST_LIB_H
#include <IndustryStandard/AppleChunklist.h>
#include <Library/OcAppleRamDiskLib.h>
#include <Library/OcCryptoLib.h>
//
// Chunklist context.
//
typedef struct OC_APPLE_CHUNKLIST_CONTEXT_ {
UINTN ChunkCount;
CONST APPLE_CHUNKLIST_CHUNK *Chunks;
APPLE_CHUNKLIST_SIG *Signature;
UINT8 Hash[SHA256_DIGEST_SIZE];
} OC_APPLE_CHUNKLIST_CONTEXT;
//
// Chunklist functions.
//
/**
Initializes a chunklist context.
@param[out] Context The Context to initialize.
@param[in] Buffer A pointer to a buffer containing the chunklist data.
@param[in] BufferSize The size of the buffer specified in Buffer.
@retval EFI_SUCCESS The Context was intialized successfully.
@retval EFI_INVALID_PARAMETER One or more parameters are invalid.
@retval EFI_UNSUPPORTED The chunklist is unsupported.
**/
BOOLEAN
OcAppleChunklistInitializeContext (
OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN OUT VOID *Buffer,
IN UINT32 BufferSize
);
BOOLEAN
OcAppleChunklistVerifySignature (
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN CONST OC_RSA_PUBLIC_KEY *PublicKey
);
/**
Verifies the specified data against a chunklist context.
@param[in] Context The Context to verify against.
@param[in] ExtentTable A pointer to the RAM disk extent table to be
verified.
@retval EFI_SUCCESS The data was verified successfully.
@retval EFI_INVALID_PARAMETER One or more parameters are invalid.
@retval EFI_END_OF_FILE The end of Buffer was reached.
@retval EFI_COMPROMISED_DATA The data failed verification.
**/
BOOLEAN
OcAppleChunklistVerifyData (
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable
);
#endif // APPLE_CHUNKLIST_LIB_H

View File

@ -0,0 +1,85 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_DISK_IMAGE_LIB_H_
#define APPLE_DISK_IMAGE_LIB_H_
#include <IndustryStandard/AppleDiskImage.h>
#include <Protocol/SimpleFileSystem.h>
#include <Library/OcAppleChunklistLib.h>
#include <Library/OcAppleRamDiskLib.h>
//
// Disk image context.
//
typedef struct {
CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable;
UINTN SectorCount;
UINT32 BlockCount;
APPLE_DISK_IMAGE_BLOCK_DATA **Blocks;
} OC_APPLE_DISK_IMAGE_CONTEXT;
BOOLEAN
OcAppleDiskImageInitializeContext (
OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable,
IN UINTN FileSize
);
BOOLEAN
OcAppleDiskImageInitializeFromFile (
OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN EFI_FILE_PROTOCOL *File
);
VOID
OcAppleDiskImageFreeContext (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context
);
VOID
OcAppleDiskImageFreeFile (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context
);
BOOLEAN
OcAppleDiskImageVerifyData (
IN OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *ChunklistContext
);
BOOLEAN
OcAppleDiskImageRead (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
EFI_HANDLE
OcAppleDiskImageInstallBlockIo (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN FileSize,
OUT CONST EFI_DEVICE_PATH_PROTOCOL **DevicePath OPTIONAL,
OUT UINTN *DevicePathSize OPTIONAL
);
VOID
OcAppleDiskImageUninstallBlockIo (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN VOID *BlockIoHandle
);
#endif

View File

@ -0,0 +1,100 @@
/** @file
Copyright (C) 2019, Download-Fritz. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_APPLE_KEY_MAP_LIB_H
#define OC_APPLE_KEY_MAP_LIB_H
#include <Protocol/AppleKeyMapDatabase.h>
#include <Protocol/AppleKeyMapAggregator.h>
/**
Default buffer size for key map.
**/
#define OC_KEY_MAP_DEFAULT_SIZE 8
#define APPLE_KEY_CODE APPLE_KEY
/**
Returns the previously install Apple Key Map Database protocol.
@retval installed or located protocol or NULL
**/
APPLE_KEY_MAP_DATABASE_PROTOCOL *
OcAppleKeyMapGetDatabase (
VOID
);
/**
Install and initialise Apple Key Map protocols.
@param[in] Reinstall Overwrite installed protocols.
@retval installed or located protocol or NULL
**/
APPLE_KEY_MAP_AGGREGATOR_PROTOCOL *
OcAppleKeyMapInstallProtocols (
IN BOOLEAN Reinstall
);
/**
Checks whether or not a list of keys is contained within another.
@param[in] Keys The reference keys.
@param[in] NumKeys The number of keys in Keys.
@param[in] CheckKeys The keys to locate in Keys.
@param[in] NumCheckKeys The number of keys in CheckKeys.
@param[in] ExactMatch Specifies whether matches must be exact.
@returns Whether the reference keys contain the checked keys.
**/
BOOLEAN
OcKeyMapHasKeys (
IN CONST APPLE_KEY_CODE *Keys,
IN UINTN NumKeys,
IN CONST APPLE_KEY_CODE *CheckKeys,
IN UINTN NumCheckKeys,
IN BOOLEAN ExactMatch
);
/**
Checks whether or not a KeyCode is contained within Keys.
@param[in] Keys The reference keys.
@param[in] NumKeys The number of keys in Keys.
@param[in] KeyCode The key to locate in Keys.
@returns Whether the reference keys contain the checked key.
**/
BOOLEAN
OcKeyMapHasKey (
IN CONST APPLE_KEY_CODE *Keys,
IN UINTN NumKeys,
IN CONST APPLE_KEY_CODE KeyCode
);
/**
Performs keyboard input flush.
@param[in] KeyMap Apple Key Map Aggregator protocol.
@param[in] Key Key to wait for removal or 0.
@param[in] FlushConsole Also flush console input.
**/
VOID
OcKeyMapFlush (
IN APPLE_KEY_MAP_AGGREGATOR_PROTOCOL *KeyMap,
IN APPLE_KEY_CODE Key,
IN BOOLEAN FlushConsole
);
#endif // OC_APPLE_KEY_MAP_LIB_H

View File

@ -0,0 +1,33 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_APPLE_KEYS_LIB_H
#define OC_APPLE_KEYS_LIB_H
#include <Library/OcGuardLib.h>
#include <Library/OcCryptoLib.h>
#define NUM_OF_PK 2
typedef struct APPLE_PK_ENTRY_ {
UINT8 Hash[SHA256_DIGEST_SIZE];
CONST OC_RSA_PUBLIC_KEY *PublicKey;
} APPLE_PK_ENTRY;
extern CONST APPLE_PK_ENTRY PkDataBase[NUM_OF_PK];
extern CONST UINT8 gAppleX86SecureBootRootCaCert[];
extern CONST UINTN gAppleX86SecureBootRootCaCertSize;
#endif // OC_APPLE_KEYS_LIB_H

View File

@ -0,0 +1,97 @@
/** @file
Apple RAM Disk library.
Copyright (C) 2019, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 OC_APPLE_RAM_DISK_LIB_H
#define OC_APPLE_RAM_DISK_LIB_H
#include <Protocol/AppleRamDisk.h>
#include <Protocol/SimpleFileSystem.h>
/**
Request allocation of Size bytes in extents table.
@param[in] Size Requested memory size.
@param[in] MemoryType Requested memory type.
@retval Allocated extent table.
**/
CONST APPLE_RAM_DISK_EXTENT_TABLE *
OcAppleRamDiskAllocate (
IN UINTN Size,
IN EFI_MEMORY_TYPE MemoryType
);
/**
Read RAM disk data.
@param[in] ExtentTable Allocated extent table.
@param[in] Offset Offset in RAM disk.
@param[in] Size Amount of data to read.
@param[out] Buffer Resulting data.
@retval TRUE on success.
**/
BOOLEAN
OcAppleRamDiskRead (
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable,
IN UINTN Offset,
IN UINTN Size,
OUT VOID *Buffer
);
/**
Write RAM disk data.
@param[in] ExtentTable Allocated extent table.
@param[in] Offset Offset in RAM disk.
@param[in] Size Amount of data to write.
@param[in] Buffer Source data.
@retval TRUE on success.
**/
BOOLEAN
OcAppleRamDiskWrite (
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable,
IN UINTN Offset,
IN UINTN Size,
IN CONST VOID *Buffer
);
/**
Load file into RAM disk as it is.
@param[in] ExtentTable Allocated extent table.
@param[in] File File protocol open for reading.
@param[in] FileSize Amount of data to write.
@retval TRUE on success.
**/
BOOLEAN
OcAppleRamDiskLoadFile (
IN OUT CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable,
IN EFI_FILE_PROTOCOL *File,
IN UINTN FileSize
);
/**
Free RAM disk.
@param[in] ExtentTable Allocated extent table.
**/
VOID
OcAppleRamDiskFree (
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable
);
#endif // OC_APPLE_RAM_DISK_LIB_H

View File

@ -0,0 +1,145 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_COMPRESSION_LIB_H
#define OC_COMPRESSION_LIB_H
/**
Maximumum compression and decompression buffer size may vary from
0 to OC_COMPRESSION_MAX_LENGTH inclusive.
**/
#define OC_COMPRESSION_MAX_LENGTH BASE_1GB
/**
Allow the use of extra adler32 validation.
Not very useful as dmg has own checks.
**/
// #define OC_INFLATE_VERIFY_DATA
/**
Compress buffer with LZSS algorithm.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@return Dst + CompressedLen on success otherwise NULL.
**/
UINT8 *
CompressLZSS (
OUT UINT8 *Dst,
IN UINT32 DstLen,
IN UINT8 *Src,
IN UINT32 SrcLen
);
/**
Decompress buffer with LZSS algorithm.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@return DecompressedLen on success otherwise 0.
**/
UINT32
DecompressLZSS (
OUT UINT8 *Dst,
IN UINT32 DstLen,
IN UINT8 *Src,
IN UINT32 SrcLen
);
/**
Decompress buffer with LZVN algorithm.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@return DecompressedLen on success otherwise 0.
**/
UINTN
DecompressLZVN (
OUT UINT8 *Dst,
IN UINTN DstLen,
IN CONST UINT8 *Src,
IN UINTN SrcLen
);
/**
Compress buffer with ZLIB algorithm.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@return Dst + CompressedLen on success otherwise NULL.
**/
UINT8 *
CompressZLIB (
OUT UINT8 *Dst,
IN UINT32 DstLen,
IN CONST UINT8 *Src,
IN UINT32 SrcLen
);
/**
Decompress buffer with ZLIB algorithm.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@return DecompressedLen on success otherwise 0.
**/
UINTN
DecompressZLIB (
OUT UINT8 *Dst,
IN UINTN DstLen,
IN CONST UINT8 *Src,
IN UINTN SrcLen
);
/**
Decompress buffer with RLE24 algorithm and 8-bit alpha.
This algorithm is used for encoding IT32/T8MK images in ICNS.
@param[out] Dst Destination buffer.
@param[in] DstLen Destination buffer size.
@param[in] Src Source buffer.
@param[in] SrcLen Source buffer size.
@param[in] Mask Source buffer.
@param[in] MaskLen Source buffer size.
@param[in] Premultiply Multiply source channels by alpha.
@return DecompressedLen on success otherwise 0.
**/
UINT32
DecompressMaskedRLE24 (
OUT UINT8 *Dst,
IN UINT32 DstLen,
IN UINT8 *Src,
IN UINT32 SrcLen,
IN UINT8 *Mask,
IN UINT32 MaskLen,
IN BOOLEAN Premultiply
);
#endif // OC_COMPRESSION_LIB_H

View File

@ -0,0 +1,196 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_CONSOLE_LIB_H
#define OC_CONSOLE_LIB_H
#include <Protocol/efiConsoleControl.h>
#include <Protocol/AppleFramebufferInfo.h>
/**
Console renderer to use.
**/
typedef enum {
OcConsoleRendererBuiltinGraphics,
OcConsoleRendererSystemGraphics,
OcConsoleRendererSystemText,
OcConsoleRendererSystemGeneric
} OC_CONSOLE_RENDERER;
/**
Special commands sent to Builtin text renderer through TestString.
**/
#define OC_CONSOLE_MARK_CONTROLLED L"MarkControlled"
#define OC_CONSOLE_MARK_UNCONTROLLED L"MarkUncontrolled"
/**
Configure console control protocol with given options.
@param[in] Renderer Renderer to use.
@param[in] IgnoreTextOutput Skip console output in text mode.
@param[in] SanitiseClearScreen Workaround ClearScreen breaking resolution.
@param[in] ClearScreenOnModeSwitch Clear graphic screen when switching to text mode.
@param[in] ReplaceTabWithSpace Replace invisible tab characters with spaces in OutputString.
**/
VOID
OcSetupConsole (
IN OC_CONSOLE_RENDERER Renderer,
IN BOOLEAN IgnoreTextOutput,
IN BOOLEAN SanitiseClearScreen,
IN BOOLEAN ClearScreenOnModeSwitch,
IN BOOLEAN ReplaceTabWithSpace
);
/**
Update console control screen mode.
@param[in] Mode Desired mode.
@retval previous console control mode.
**/
EFI_CONSOLE_CONTROL_SCREEN_MODE
OcConsoleControlSetMode (
IN EFI_CONSOLE_CONTROL_SCREEN_MODE Mode
);
/**
Parse screen resolution from string.
@param[in] String Resolution in WxH@B or WxH format.
@param[out] Width Parsed resolution width or 0.
@param[out] Height Parsed resolution height or 0.
@param[out] Bpp Parsed resolution bpp or 0.
@param[out] Max Set to TRUE when String equals to Max.
**/
VOID
OcParseScreenResolution (
IN CONST CHAR8 *String,
OUT UINT32 *Width,
OUT UINT32 *Height,
OUT UINT32 *Bpp,
OUT BOOLEAN *Max
);
/**
Parse console mode from string.
@param[in] String Resolution in WxH format.
@param[out] Width Parsed mode width or 0.
@param[out] Height Parsed mode height or 0.
@param[out] Max Set to TRUE when String equals to Max.
**/
VOID
OcParseConsoleMode (
IN CONST CHAR8 *String,
OUT UINT32 *Width,
OUT UINT32 *Height,
OUT BOOLEAN *Max
);
/**
Set screen resolution on console handle.
@param[in] Width Resolution width or 0 for Max.
@param[in] Height Resolution height or 0 for Max.
@param[in] Bpp Resolution bpp or 0 for automatic.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcSetConsoleResolution (
IN UINT32 Width,
IN UINT32 Height,
IN UINT32 Bpp OPTIONAL
);
/**
Set console mode.
@param[in] Width Resolution width or 0 for Max.
@param[in] Height Resolution height or 0 for Max.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcSetConsoleMode (
IN UINT32 Width,
IN UINT32 Height
);
/**
Ensure installed GOP protocol on ConOut handle.
**/
VOID
OcProvideConsoleGop (
IN BOOLEAN Route
);
/**
Perform console reconnection.
**/
VOID
OcReconnectConsole (
VOID
);
/**
Use direct GOP renderer for console.
@param[in] CacheType Caching type, e.g. CacheWriteCombining or -1 to disable.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcUseDirectGop (
IN INT32 CacheType
);
/**
Allocate new System Table with disabled text output.
@param[in] SystemTable Base System Table.
@retval non NULL The System Table table was allocated successfully.
**/
EFI_SYSTEM_TABLE *
AllocateNullTextOutSystemTable (
IN EFI_SYSTEM_TABLE *SystemTable
);
/**
Provide UGA protocol instances on top of existing GOP instances.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcProvideUgaPassThrough (
VOID
);
/**
Install and initialise Apple Framebuffer Info protocol
on top of GOP protocol. For EfiBoot 10.4, which can only
use UGA, this is the only way to obtain framebuffer base
for XNU kernel PE Boot_args.
@param[in] Reinstall Overwrite installed protocol.
@retval installed or located protocol or NULL.
**/
APPLE_FRAMEBUFFER_INFO_PROTOCOL *
OcAppleFbInfoInstallProtocol (
IN BOOLEAN Reinstall
);
#endif // OC_CONSOLE_LIB_H

223
Include/Library/OcCpuLib.h Executable file
View File

@ -0,0 +1,223 @@
/** @file
Copyright (C) 2016 - 2017, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_CPU_LIB_H
#define OC_CPU_LIB_H
#include <IndustryStandard/CpuId.h>
#include <IndustryStandard/AppleIntelCpuInfo.h>
/**
Assumed CPU frequency when it cannot be detected.
Can be overridden by e.g. emulator.
**/
#ifndef OC_FALLBACK_CPU_FREQUENCY
#define OC_FALLBACK_CPU_FREQUENCY 1000000000
#endif
typedef struct {
//
// Note, Vendor and BrandString are reordered for proper alignment.
//
UINT32 Vendor[4];
CHAR8 BrandString[48];
CPUID_VERSION_INFO_EAX CpuidVerEax;
CPUID_VERSION_INFO_EBX CpuidVerEbx;
CPUID_VERSION_INFO_ECX CpuidVerEcx;
CPUID_VERSION_INFO_EDX CpuidVerEdx;
UINT32 MicrocodeRevision;
BOOLEAN Hypervisor; ///< indicate whether we are under virtualization
UINT8 Type;
UINT8 Family;
UINT8 Model;
UINT8 ExtModel;
UINT8 ExtFamily;
UINT8 Stepping;
UINT64 Features;
UINT64 ExtFeatures;
UINT32 Signature;
UINT8 Brand;
UINT16 AppleProcessorType;
BOOLEAN CstConfigLock;
UINT32 MaxId;
UINT32 MaxExtId;
UINT8 MaxDiv;
UINT8 CurBusRatio; ///< Current Multiplier
UINT8 MinBusRatio; ///< Min Bus Ratio
UINT8 MaxBusRatio; ///< Max Bus Ratio
UINT8 TurboBusRatio1;
UINT8 TurboBusRatio2;
UINT8 TurboBusRatio3;
UINT8 TurboBusRatio4;
UINT16 PackageCount;
UINT16 CoreCount;
UINT16 ThreadCount;
//
// External clock for SMBIOS Type4 table.
//
UINT16 ExternalClock;
//
// Platform-dependent frequency for the Always Running Timer (ART), normally
// 24Mhz. Firmwares may choose to override this. Some CPUs like Xeon Scalable
// use a different frequency. CPUs report the frequency through CPUID.15H.ECX.
// If unreported, the frequency is looked up based on the model and family.
//
// Nominal Core Crystal Clock Frequency for known processor families:
// Intel Xeon Scalable with CPUID signature 0x0655: 25 Mhz (server segment)
// 6th and 7th generation Intel Core & Xeon W: 24 Mhz (client segment)
// Nex Generation Intel Atom with CPUID 0x065C: 19.2 Mhz (atom segment)
//
UINT64 ARTFrequency;
//
// The CPU frequency derived from either CPUFrequencyFromTSC (legacy) or
// CPUFrequencyFromART (preferred for Skylake and presumably newer processors
// that have an Always Running Timer).
//
// CPUFrequencyFromTSC should approximate equal CPUFrequencyFromART. If not,
// there is likely a bug or miscalculation.
//
UINT64 CPUFrequency;
//
// The CPU frequency as reported by the Time Stamp Counter (TSC).
//
UINT64 CPUFrequencyFromTSC;
//
// The CPU frequency derived from the Always Running Timer (ART) frequency:
// TSC Freq = (ART Freq * CPUID.15H:EBX[31:0]) / CPUID.15H:EAX[31:0]
//
// 0 if ART is not present.
//
UINT64 CPUFrequencyFromART;
//
// TSC adjustment value read from MSR_IA32_TSC_ADJUST if present.
//
UINT64 TscAdjust;
//
// The CPU frequency derived from the CPUID VMWare Timing leaf.
// 0 if VMWare Timing leaf is not present.
//
UINT64 CPUFrequencyFromVMT;
//
// The Front Side Bus (FSB) frequency calculated from dividing the CPU
// frequency by the Max Ratio.
//
UINT64 FSBFrequency;
} OC_CPU_INFO;
typedef enum {
OcCpuGenerationUnknown,
OcCpuGenerationPenryn,
OcCpuGenerationNehalem,
OcCpuGenerationWestmere,
OcCpuGenerationSandyBridge,
OcCpuGenerationIvyBridge,
OcCpuGenerationHaswell,
OcCpuGenerationBroadwell,
OcCpuGenerationSkylake,
OcCpuGenerationKabyLake,
OcCpuGenerationCoffeeLake,
OcCpuGenerationCannonLake,
OcCpuGenerationMaxGeneration
} OC_CPU_GENERATION;
/**
Scan the processor and fill the cpu info structure with results.
@param[in] Cpu A pointer to the cpu info structure to fill with results.
**/
VOID
OcCpuScanProcessor (
IN OUT OC_CPU_INFO *Cpu
);
/**
Disable flex ratio if it has invalid value.
Commonly fixes early reboot on APTIO IV (Ivy/Haswell).
@param[in] Cpu A pointer to the cpu info.
**/
VOID
OcCpuCorrectFlexRatio (
IN OC_CPU_INFO *Cpu
);
/**
Synchronise TSC on all cores (needed on server chipsets and some laptops).
This does not fully replace VoodooTscSync or TSCAdjustReset due to
the need to sync on S3 as well and may also work far less reliably
due to the limitation of UEFI firmwares not letting us run MSR updates in
parallel with BSP and AP cores. However, it lets debug kernels work
most of the time till the time TSC kexts start.
@param[in] Cpu A pointer to the cpu info.
@param[in] Timeout Amount of time to wait for CPU core rendezvous.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcCpuCorrectTscSync (
IN OC_CPU_INFO *Cpu,
IN UINTN Timeout
);
/**
Converts CPUID Family and Model extracted from EAX
CPUID (1) call to AppleFamily value. This implements
cpuid_set_cpufamily functionality as it is in XNU.
@param[in] VersionEax CPUID (1) EAX value.
@retval Apple Family (e.g. CPUFAMILY_UNKNOWN)
**/
UINT32
OcCpuModelToAppleFamily (
IN CPUID_VERSION_INFO_EAX VersionEax
);
/**
Obtain CPU's generation.
@retval CPU's generation (e.g. OcCpuGenerationUnknown).
*/
OC_CPU_GENERATION
OcCpuGetGeneration (
VOID
);
/**
Obtain CPU's invariant TSC frequency.
@retval CPU's TSC frequency or OC_FALLBACK_CPU_FREQUENCY.
**/
UINT64
OcGetTSCFrequency (
VOID
);
#endif // OC_CPU_LIB_H_

View File

@ -0,0 +1,176 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_DEBUG_LOG_LIB_H
#define OC_DEBUG_LOG_LIB_H
#include <Library/DebugLib.h>
#include <Protocol/OcLog.h>
#include <Protocol/AppleDebugLog.h>
#define OC_HEX_LOWER(x) "0123456789ABCDEF"[((UINT32) (x) & 0x0FU)]
#define OC_HEX_UPPER(x) "0123456789ABCDEF"[((UINT32) (x) & 0xF0U) >> 4U]
#ifndef OC_TARGET_RELEASE
#define OC_TARGET_RELEASE RELEASE
#endif
/**
Expand device path to human readable string.
**/
#define OC_HUMAN_STRING(TextDevicePath) \
((TextDevicePath) == NULL ? L"<nil>" : (TextDevicePath)[0] == '\0' ? L"<empty>" : (TextDevicePath))
/**
Debug information that is not logged when NVRAM logging is on.
**/
#ifndef DEBUG_BULK_INFO
#define DEBUG_BULK_INFO (DEBUG_VERBOSE|DEBUG_INFO)
#endif
/**
This is a place print debug messages when they happen after ExitBootServices.
**/
#define RUNTIME_DEBUG(x) do { } while (0)
/**
Pointer debug kit.
**/
#if defined(OC_TARGET_DEBUG) || defined(OC_TARGET_NOOPT)
#define DEBUG_POINTER(x) x
#elif defined(OC_TARGET_RELEASE)
#define DEBUG_POINTER(x) NULL
#else
#error "Define target macro: OC_TARGET_<TARGET>!"
#endif
/**
Install or update the OcLog protocol with specified options.
@param[in] Options Logging options.
@param[in] DisplayDelay Delay in microseconds after each log entry.
@param[in] DisplayLevel Console visible error level.
@param[in] HaltLevel Error level causing CPU halt.
@param[in] LogPrefixPath Log path (without timestamp).
@param[in] LogFileSystem Log filesystem, optional.
@retval EFI_SUCCESS The entry point is executed successfully.
**/
EFI_STATUS
OcConfigureLogProtocol (
IN OC_LOG_OPTIONS Options,
IN UINT32 DisplayDelay,
IN UINTN DisplayLevel,
IN UINTN HaltLevel,
IN CONST CHAR16 *LogPrefixPath OPTIONAL,
IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *LogFileSystem OPTIONAL
);
/**
Install and initialise the Apple Debug Log protocol.
@param[in] Reinstall Replace any installed protocol.
@returns Installed or located protocol.
@retval NULL There was an error locating or installing the protocol.
**/
APPLE_DEBUG_LOG_PROTOCOL *
OcAppleDebugLogInstallProtocol (
IN BOOLEAN Reinstall
);
/**
Configure Apple Debug Log protocol.
@param[in] Enable Enable logging to OcLog.
**/
VOID
OcAppleDebugLogConfigure (
IN BOOLEAN Enable
);
/**
Configure Apple performance log location.
@param[in,out] PerfBuffer Performance buffer location.
@param[in] PerfBufferSize Performance buffer size.
**/
VOID
OcAppleDebugLogPerfAllocated (
IN OUT VOID *PerfBuffer,
IN UINTN PerfBufferSize
);
/**
Prints via gST->ConOut without any pool allocations.
Otherwise equivalent to Print.
Note: EFIAPI must be present for VA_ARGS forwarding (causes bugs with gcc).
@param[in] Format Formatted string.
**/
VOID
EFIAPI
OcPrintScreen (
IN CONST CHAR16 *Format,
...
);
/**
Dummy function that debuggers may break on.
**/
VOID
DebugBreak (
VOID
);
/**
Wait for user input after printing message.
@param[in] Message Message to print.
**/
VOID
WaitForKeyPress (
CONST CHAR16 *Message
);
/**
Print Device Path to log.
@param[in] ErrorLevel Debug error level.
@param[in] Message Prefixed message.
@param[in] DevicePath Device path to print.
**/
VOID
DebugPrintDevicePath (
IN UINTN ErrorLevel,
IN CONST CHAR8 *Message,
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Print hex dump to log.
@param[in] ErrorLevel Debug error level.
@param[in] Message Prefixed message.
@param[in] Bytes Byte sequence.
@param[in] Size Byte sequence size.
**/
VOID
DebugPrintHexDump (
IN UINTN ErrorLevel,
IN CONST CHAR8 *Message,
IN UINT8 *Bytes,
IN UINTN Size
);
#endif // OC_DEBUG_LOG_LIB_H

View File

@ -0,0 +1,539 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_MEMORY_LIB_H
#define OC_MEMORY_LIB_H
#include <Uefi.h>
#include <Guid/MemoryAttributesTable.h>
#include <IndustryStandard/VirtualMemory.h>
/**
Reverse equivalent of NEXT_MEMORY_DESCRIPTOR.
**/
#define PREV_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))
/**
Get last descriptor address.
It is assumed that the descriptor contains pages.
**/
#define LAST_DESCRIPTOR_ADDR(Desc) \
((Desc)->PhysicalStart + (EFI_PAGES_TO_SIZE ((UINTN) (Desc)->NumberOfPages) - 1))
/**
Check if area is within the specified descriptor.
It is assumed that the descriptor contains pages and AreaSize is not 0.
**/
#define AREA_WITHIN_DESCRIPTOR(Desc, Area, AreaSize) \
((Area) >= (Desc)->PhysicalStart && ((Area) + ((AreaSize) - 1)) <= LAST_DESCRIPTOR_ADDR (Desc))
/**
Reasonable default virtual memory page pool size (2 MB).
**/
#define OC_DEFAULT_VMEM_PAGE_COUNT 0x200
/**
Reasonable default memory map size used when allocations are problematic.
Note, that MacPro5,1 is known to have 8880 memory map.
**/
#define OC_DEFAULT_MEMORY_MAP_SIZE (EFI_PAGE_SIZE*3)
/**
Lock the legacy region specified to enable modification.
@param[in] LegacyAddress The address of the region to lock.
@param[in] LegacyLength The size of the region to lock.
@retval EFI_SUCCESS The region was locked successfully.
**/
EFI_STATUS
LegacyRegionLock (
IN UINT32 LegacyAddress,
IN UINT32 LegacyLength
);
/**
Unlock the legacy region specified to enable modification.
@param[in] LegacyAddress The address of the region to unlock.
@param[in] LegacyLength The size of the region to unlock.
@retval EFI_SUCCESS The region was unlocked successfully.
**/
EFI_STATUS
LegacyRegionUnlock (
IN UINT32 LegacyAddress,
IN UINT32 LegacyLength
);
/**
Get current memory map allocated on pool with reserved entries.
@param[out] MemoryMapSize Resulting memory map size in bytes.
@param[out] DescriptorSize Resulting memory map descriptor size in bytes.
@param[out] MapKey Memory map key, optional.
@param[out] DescriptorVersion Memory map descriptor version, optional.
@param[out] OriginalMemoryMapSize Actual pool allocation memory, optional.
@param[out] IncludeSplitSpace Allocate memory to permit splitting memory map.
@retval current memory map or NULL.
**/
EFI_MEMORY_DESCRIPTOR *
OcGetCurrentMemoryMap (
OUT UINTN *MemoryMapSize,
OUT UINTN *DescriptorSize,
OUT UINTN *MapKey OPTIONAL,
OUT UINT32 *DescriptorVersion OPTIONAL,
OUT UINTN *OriginalMemoryMapSize OPTIONAL,
IN BOOLEAN IncludeSplitSpace
);
/**
Get current memory map of custom allocation.
@param[out] MemoryMapSize Resulting memory map size in bytes.
@param[out] MemoryMap Resulting memory map.
@param[out] MapKey Memory map key.
@param[out] DescriptorSize Resulting memory map descriptor size in bytes.
@param[out] DescriptorVersion Memory map descriptor version.
@param[in] GetMemoryMap Custom GetMemoryMap implementation to use, optional.
@param[in,out] TopMemory Base top address for OcAllocatePagesFromTop allocation, number of pages after return.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcGetCurrentMemoryMapAlloc (
OUT UINTN *MemoryMapSize,
OUT EFI_MEMORY_DESCRIPTOR **MemoryMap,
OUT UINTN *MapKey,
OUT UINTN *DescriptorSize,
OUT UINT32 *DescriptorVersion,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL,
IN OUT EFI_PHYSICAL_ADDRESS *TopMemory OPTIONAL
);
/**
Sort memory map entries based upon PhysicalStart, from low to high.
@param MemoryMapSize Size, in bytes, of the MemoryMap buffer.
@param MemoryMap A pointer to the buffer in which firmware places
the current memory map.
@param DescriptorSize Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
**/
VOID
OcSortMemoryMap (
IN UINTN MemoryMapSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Shrink memory map by joining non-runtime records.
Requires sorted memory map.
@param[in,out] MemoryMapSize Memory map size in bytes, updated on shrink.
@param[in,out] MemoryMap Memory map to shrink.
@param[in] DescriptorSize Memory map descriptor size in bytes.
@retval EFI_SUCCESS on success.
@retval EFI_NOT_FOUND when cannot join anything.
**/
EFI_STATUS
OcShrinkMemoryMap (
IN OUT UINTN *MemoryMapSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Deduplicate memory descriptors. Requires sorted entry list.
@param[in,out] EntryCount Memory map size in entries, updated on shrink.
@param[in,out] MemoryMap Memory map to shrink.
@param[in] DescriptorSize Memory map descriptor size in bytes.
@retval EFI_SUCCESS on success.
@retval EFI_NOT_FOUND when cannot join anything.
**/
EFI_STATUS
OcDeduplicateDescriptors (
IN OUT UINT32 *EntryCount,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Check range allocation compatibility callback.
@param[in] Address Starting address.
@param[in] Size Size of memory range.
@retval TRUE when suitable for allocation.
**/
typedef
BOOLEAN
(*CHECK_ALLOCATION_RANGE) (
IN EFI_PHYSICAL_ADDRESS Address,
IN UINTN Size
);
/**
Filter memory map entries.
@param[in] Context Parameterised filter data.
@param[in,out] MemoryMapSize Memory map size in bytes.
@param[in,out] MemoryMap Memory map to filter.
@param[in] DescriptorSize Memory map descriptor size in bytes.
**/
typedef
VOID
(*OC_MEMORY_FILTER) (
IN VOID *Context OPTIONAL,
IN UINTN MemoryMapSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Allocate pages from the top of physical memory up to address specified in Memory.
Unlike AllocateMaxAddress, this method guarantees to choose top most address.
@param[in] MemoryType Allocated memory type.
@param[in] Pages Amount of pages to allocate.
@param[in,out] Memory Top address for input, allocated address for output.
@param[in] GetMemoryMap Custom GetMemoryMap implementation to use, optional.
@param[in] CheckRange Handler allowing to not allocate select ranges, optional.
@retval EFI_SUCCESS on successful allocation.
**/
EFI_STATUS
OcAllocatePagesFromTop (
IN EFI_MEMORY_TYPE MemoryType,
IN UINTN Pages,
IN OUT EFI_PHYSICAL_ADDRESS *Memory,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL,
IN CHECK_ALLOCATION_RANGE CheckRange OPTIONAL
);
/**
Calculate number of runtime pages in the memory map.
@param[in] MemoryMapSize Memory map size in bytes.
@param[in] MemoryMap Memory map to inspect.
@param[in] DescriptorSize Memory map descriptor size in bytes.
@param[out] DescriptorCount Number of relevant descriptors, optional.
@retval Number of runtime pages.
**/
UINT64
OcCountRuntimePages (
IN UINTN MemoryMapSize,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize,
OUT UINTN *DescriptorCount OPTIONAL
);
/**
Calculate number of free pages in the memory map.
@param[out] LowerMemory Number of free pages below 4 GB, optional.
@retval Number of free pages.
**/
UINTN
OcCountFreePages (
OUT UINTN *LowerMemory OPTIONAL
);
/**
Print memory attributes table if present.
**/
VOID
OcPrintMemoryAttributesTable (
VOID
);
/**
Print memory map.
@param[in] MemoryMapSize Memory map size in bytes.
@param[in] MemoryMap Memory map to print.
@param[in] DescriptorSize Memory map descriptor size in bytes.
**/
VOID
OcPrintMemoryMap (
IN UINTN MemoryMapSize,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Refresh memory descriptor containing the specified address.
@param[in] MemoryMapSize Memory map size in bytes.
@param[in] MemoryMap Memory map to refresh.
@param[in] DescriptorSize Memory map descriptor size in bytes.
@param[in] Address Address contained in the updated entry.
@param[in] Type Memory type to assign to the entry.
@param[in] SetAttributes Attributes to set.
@param[in] DropAttributes Attributes to remove.
@retval EFI_SUCCESS on success.
@retval EFI_NOT_FOUND no entry contains the specified address.
@retval EFI_UNSUPPORTED memory attributes are not supported by the platform.
**/
EFI_STATUS
OcUpdateDescriptors (
IN UINTN MemoryMapSize,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize,
IN EFI_PHYSICAL_ADDRESS Address,
IN EFI_MEMORY_TYPE Type,
IN UINT64 SetAttributes,
IN UINT64 DropAttributes
);
/**
Obtain memory attributes table.
@param[out] MemoryAttributesEntry memory descriptor pointer, optional.
@retval pointer to memory attributes table.
@retval NULL if memory attributes table is unsupported.
**/
EFI_MEMORY_ATTRIBUTES_TABLE *
OcGetMemoryAttributes (
OUT EFI_MEMORY_DESCRIPTOR **MemoryAttributesEntry OPTIONAL
);
/**
Refresh memory attributes entry containing the specified address.
@param[in] Address Address contained in the updated entry.
@param[in] GetMemoryMap
@retval EFI_SUCCESS on success.
@retval EFI_NOT_FOUND no entry contains the specified address.
@retval EFI_UNSUPPORTED memory attributes are not supported by the platform.
**/
EFI_STATUS
OcRebuildAttributes (
IN EFI_PHYSICAL_ADDRESS Address,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL
);
/**
Count upper bound of split runtime descriptors.
@retval amount of runtime descriptors.
**/
UINTN
OcCountSplitDescritptors (
VOID
);
/**
Split memory map by memory attributes if available.
Requires sorted memory map!
@param[in] MaxMemoryMapSize Upper memory map size bound for growth.
@param[in,out] MemoryMapSize Current memory map size, updated on return.
@param[in,out] MemoryMap Memory map to split.
@param[in] DescriptorSize Memory map descriptor size.
Note, the function is guaranteed to return valid memory map, though not necessarily split.
@retval EFI_SUCCESS on success.
@retval EFI_UNSUPPORTED memory attributes are not supported by the platform.
@retval EFI_OUT_OF_RESOURCES new memory map did not fit.
**/
EFI_STATUS
OcSplitMemoryMapByAttributes (
IN UINTN MaxMemoryMapSize,
IN OUT UINTN *MemoryMapSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN UINTN DescriptorSize
);
/**
Return pointer to PML4 table in PageTable and PWT and PCD flags in Flags.
@param[out] Flags Current page table PWT and PCT flags.
@retval Current page table address.
**/
PAGE_MAP_AND_DIRECTORY_POINTER *
OcGetCurrentPageTable (
OUT UINTN *Flags OPTIONAL
);
/**
Return physical addrress for given virtual addrress.
@param[in] PageTable Page table to use for solving.
@param[in] VirtualAddr Virtual address to look up.
@param[out] PhysicalAddr Physical address to return.
@retval EFI_SUCCESS on successful lookup.
**/
EFI_STATUS
OcGetPhysicalAddress (
IN PAGE_MAP_AND_DIRECTORY_POINTER *PageTable OPTIONAL,
IN EFI_VIRTUAL_ADDRESS VirtualAddr,
OUT EFI_PHYSICAL_ADDRESS *PhysicalAddr
);
/**
Virtual memory context
**/
typedef struct OC_VMEM_CONTEXT_ {
///
/// Memory pool containing memory to be spread across allocations.
///
UINT8 *MemoryPool;
///
/// Free pages in the memory pool.
///
UINTN FreePages;
} OC_VMEM_CONTEXT;
/**
Allocate EfiBootServicesData virtual memory pool from boot services
in the end of BASE_4GB of RAM. Should be called while boot services are
still usable.
@param[out] Context Virtual memory pool context.
@param[in] NumPages Number of pages to be allocated in the pool.
@param[in] GetMemoryMap Custom GetMemoryMap implementation to use, optional.
@retval EFI_SUCCESS on successful allocation.
**/
EFI_STATUS
VmAllocateMemoryPool (
OUT OC_VMEM_CONTEXT *Context,
IN UINTN NumPages,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL
);
/**
Allocate pages for e.g. vm page maps.
@param[in,out] Context Virtual memory pool context.
@param[in] NumPages Number of pages to allocate.
@retval allocated pages or NULL.
**/
VOID *
VmAllocatePages (
IN OUT OC_VMEM_CONTEXT *Context,
IN UINTN NumPages
);
/**
Map (remap) given page at physical address to given virtual address in
the specified page table.
@param[in,out] Context Virtual memory pool context.
@param[in] PageTable Page table to update.
@param[in] VirtualAddr Virtual memory address to map at.
@param[in] PhysicalAddr Physical memory address to map from.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
VmMapVirtualPage (
IN OUT OC_VMEM_CONTEXT *Context,
IN OUT PAGE_MAP_AND_DIRECTORY_POINTER *PageTable OPTIONAL,
IN EFI_VIRTUAL_ADDRESS VirtualAddr,
IN EFI_PHYSICAL_ADDRESS PhysicalAddr
);
/**
Map (remap) a range of 4K pages at physical address to given virtual address
in the specified page table.
@param[in,out] Context Virtual memory pool context.
@param[in] PageTable Page table to update.
@param[in] VirtualAddr Virtual memory address to map at.
@param[in] NumPages Number of 4K pages to map.
@param[in] PhysicalAddr Physical memory address to map from.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
VmMapVirtualPages (
IN OUT OC_VMEM_CONTEXT *Context,
IN OUT PAGE_MAP_AND_DIRECTORY_POINTER *PageTable OPTIONAL,
IN EFI_VIRTUAL_ADDRESS VirtualAddr,
IN UINT64 NumPages,
IN EFI_PHYSICAL_ADDRESS PhysicalAddr
);
/**
Flushes TLB caches.
**/
VOID
VmFlushCaches (
VOID
);
/**
Check whether built-in allocator is initialized.
@retval TRUE on success.
**/
BOOLEAN
UmmInitialized (
VOID
);
/**
Initialize built-in allocator.
@param[in] Heap Memory pool used for allocations.
@param[in] Size Memory pool size.
**/
VOID
UmmSetHeap (
IN VOID *Heap,
IN UINT32 Size
);
/**
Perform allocation from built-in allocator.
@param[in] Size Allocation size.
@retval allocated memory on success.
**/
VOID *
UmmMalloc (
IN UINT32 Size
);
/**
Perform free of allocated memory. Accepts NULL pointer
and checks whether memory belongs to itself.
@param[in] Ptr Memory to free.
@retval TRUE on success
**/
BOOLEAN
UmmFree (
IN VOID *Ptr
);
#endif // OC_MEMORY_LIB_H

View File

@ -18,162 +18,16 @@
#include <Uefi.h>
#include <Library/OcStringLib.h>
/**
The size, in Bits, of one Byte.
**/
#define OC_CHAR_BIT 8
/**
Convert seconds to microseconds for use in e.g. gBS->Stall.
**/
#define SECONDS_TO_MICROSECONDS(x) ((x)*1000000)
/**
TODO: EDK II has its implementation in BaseLib, but it is broken,
as it fails to update DecodedLength:
https://github.com/acidanthera/bugtracker/issues/372
@param[in] EncodedData A pointer to the data to convert.
@param[in] EncodedLength The length of data to convert.
@param[in] DecodedData A pointer to location to store the decoded data.
@param[in] DecodedSize A pointer to location to store the decoded size.
@retval TRUE on success.
**/
RETURN_STATUS
EFIAPI
OcBase64Decode (
IN CONST CHAR8 *EncodedData,
IN UINTN EncodedLength,
OUT UINT8 *DecodedData,
IN OUT UINTN *DecodedLength
);
// LegacyRegionlock
/** Lock the legacy region specified to enable modification.
@param[in] LegacyAddress The address of the region to lock.
@param[in] LegacyLength The size of the region to lock.
@retval EFI_SUCCESS The region was locked successfully.
**/
EFI_STATUS
LegacyRegionLock (
IN UINT32 LegacyAddress,
IN UINT32 LegacyLength
);
// LegacyRegionUnlock
/** Unlock the legacy region specified to enable modification.
@param[in] LegacyAddress The address of the region to unlock.
@param[in] LegacyLength The size of the region to unlock.
@retval EFI_SUCCESS The region was unlocked successfully.
**/
EFI_STATUS
LegacyRegionUnlock (
IN UINT32 LegacyAddress,
IN UINT32 LegacyLength
);
/** Log the boot options passed
@param[in] BootOrder A pointer to the boot order list.
@param[in] BootOrderLength Size of the boot order list.
@retval EFI_SUCCESS The entry point is executed successfully.
**/
EFI_STATUS
LogBootOrder (
IN INT16 *BootOrder,
IN UINTN BootOrderSize
);
// LogHexDump
/** Convert memory locations into hex strings and output to the boot log
@param[in] Address The address of the region to dump hex from.
@param[in] Address2 The address to show when dumping hex.
@param[in] Length The length of the string to show.
@param[in] LineSize How many bytes to show per line.
@param[in] DisplayAscii Flag to show ascii charater also.
@retval EFI_SUCCESS The region was unlocked successfully.
**/
EFI_STATUS
LogHexDump (
IN VOID *Address,
IN VOID *Address2,
IN UINTN Length,
IN UINTN LineSize,
IN BOOLEAN DisplayAscii
);
// SetPlatformData
/**
@param[in] DataRecordGuid The guid of the record to use.
@param[in] Key A pointer to the ascii key string.
@param[in] Data A pointer to the data to store.
@param[in] DataSize The length of the data to store.
@retval EFI_SUCCESS The datahub was updated successfully.
**/
EFI_STATUS
SetPlatformData (
IN EFI_GUID *DataRecordGuid,
IN CHAR8 *Key,
IN VOID *Data,
IN UINT32 DataSize
);
/**
Allocate new System Table with disabled text output.
@param[in] SystemTable Base System Table.
@retval non NULL The System Table table was allocated successfully.
**/
EFI_SYSTEM_TABLE *
AllocateNullTextOutSystemTable (
EFI_SYSTEM_TABLE *SystemTable
);
/**
Dummy function that debuggers may break on.
**/
VOID
DebugBreak (
VOID
);
/**
Wait for user input after printing message.
@param[in] Message Message to print.
**/
VOID
WaitForKeyPress (
CONST CHAR16 *Message
);
/**
Default index mapping macros.
**/
#define OC_INPUT_STR "123456789ABCDEFGHIJKLMNOPQRSTUVXWZ"
#define OC_INPUT_MAX L_STR_LEN (OC_INPUT_STR)
#define OC_INPUT_ABORTED -1 ///< Esc or 0
#define OC_INPUT_INVALID -2 ///< Some other key
#define OC_INPUT_TIMEOUT -3 ///< Timeout
/**
Obtains key index from user input.
@param TimeOutSeconds Timeout to wait for.
@returns key index [0, OC_INPUT_MAX), OC_INPUT_ABORTED, or OC_INPUT_INVALID.
**/
INTN
WaitForKeyIndex (
UINTN TimeOutSeconds
);
INT32
FindPattern (
IN CONST UINT8 *Pattern,
@ -198,16 +52,48 @@ ApplyPatch (
);
/**
@param[in] Protocol The published unique identifier of the protocol. It is the callers responsibility to pass in
Obtain application arguments.
@param[out] Argc Argument count.
@param[out] Argv Argument list.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
GetArguments (
OUT UINTN *Argc,
OUT CHAR16 ***Argv
);
/**
Uninstall all protocols with the specified GUID.
@param[in] Protocol The published unique identifier of the protocol. It is the caller's responsibility to pass in
a valid GUID.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
UninstallAllProtocolInstances (
OcUninstallAllProtocolInstances (
EFI_GUID *Protocol
);
/**
Handle protocol on handle and fallback to any protocol when missing.
@param[in] Handle Handle to search for protocol.
@param[in] Protocol Protocol to search for.
@param[out] Interface Protocol interface if found.
@retval EFI_SUCCESS on success.
**/
EFI_STATUS
OcHandleProtocolFallback (
IN EFI_HANDLE Handle,
IN EFI_GUID *Protocol,
OUT VOID **Interface
);
/**
Release UEFI ownership from USB controllers at booting.
**/
@ -217,21 +103,81 @@ ReleaseUsbOwnership (
);
/**
Get current memory map allocated on pool.
@param[out] MemoryMapSize Resulting memory map size in bytes.
@param[out] DescriptorSize Resulting memory map descriptor size in bytes.
@param[out] MapKey Memory map key, optional.
@param[out] DescriptorVersion Memory map version, optional.
@retval current memory map or NULL.
Perform cold reboot directly bypassing UEFI services. Does not return.
Supposed to work in any modern physical or virtual environment.
**/
EFI_MEMORY_DESCRIPTOR *
GetCurrentMemoryMap (
OUT UINTN *MemoryMapSize,
OUT UINTN *DescriptorSize,
OUT UINTN *MapKey OPTIONAL,
OUT UINT32 *DescriptorVersion OPTIONAL
VOID
DirectRestCold (
VOID
);
/**
Return the result of (Multiplicand * Multiplier / Divisor).
@param Multiplicand A 64-bit unsigned value.
@param Multiplier A 64-bit unsigned value.
@param Divisor A 32-bit unsigned value.
@param Remainder A pointer to a 32-bit unsigned value. This parameter is
optional and may be NULL.
@return Multiplicand * Multiplier / Divisor.
**/
UINT64
MultThenDivU64x64x32 (
IN UINT64 Multiplicand,
IN UINT64 Multiplier,
IN UINT32 Divisor,
OUT UINT32 *Remainder OPTIONAL
);
/**
Internal worker macro that calls DebugPrint().
This macro calls DebugPrint(), passing in the filename, line number, an
expression that failed the comparison with expected value,
the expected value and the actual value.
@param Expression Integer expression that evaluated to value different from Value (should be convertible to INTN)
@param ExpectedValue Expected value of the expression (should be convertible to INTN)
**/
#define _ASSERT_EQUALS(Expression, ExpectedValue) \
DebugPrint( \
DEBUG_ERROR, \
"ASSERT %a(%d): %a (expected: %d, actual: %d)\n", \
__FILE__, \
__LINE__, \
#Expression, \
(INTN)(ExpectedValue), \
(INTN)(Expression))
/**
Macro that calls DebugAssert() if the value of an expression differs from the expected value.
If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED
bit of PcdDebugProperyMask is set, then this macro evaluates the integer
expression specified by Expression. If the value of Expression differs from ExpectedValue, then
DebugPrint() is called passing in the source filename, source line number,
Expression, it's value and ExpectedValue; then ASSERT(FALSE) is called to
cause a breakpoint, deadloop or no-op depending on PcdDebugProperyMask.
@param Expression Integer expression (should be convertible to INTN).
@param ExpectedValue Expected value (should be convertible to INTN).
**/
#if !defined(MDEPKG_NDEBUG)
#define ASSERT_EQUALS(Expression, ExpectedValue) \
do { \
if (DebugAssertEnabled ()) { \
if ((Expression) != (ExpectedValue)) { \
_ASSERT_EQUALS (Expression, ExpectedValue); \
ASSERT(FALSE); \
ANALYZER_UNREACHABLE (); \
} \
} \
} while (FALSE)
#else
#define ASSERT_EQUALS(Expression, ExpectedValue)
#endif
#endif // OC_MISC_LIB_H

View File

@ -0,0 +1,32 @@
/** @file
Copyright (C) 2020, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_OS_INFO_LIB_H
#define OC_OS_INFO_LIB_H
#include <Protocol/OSInfo.h>
/**
Install and initialise OS Info protocol.
@param[in] Reinstall Overwrite installed protocol.
@retval installed or located protocol or NULL.
**/
EFI_OS_INFO_PROTOCOL *
OcOSInfoInstallProtocol (
IN BOOLEAN Reinstall
);
#endif // OC_OS_INFO_LIB_H

View File

@ -0,0 +1,59 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_RNG_LIB_H
#define OC_RNG_LIB_H
#include <Library/RngLib.h>
/**
Generates a 16-bit pseudo random number.
This generator is still guaranteed to be cryptographically secure
by the use of CPRNG with entropy.
@retval 16-bit pseudo random number.
**/
UINT16
EFIAPI
GetPseudoRandomNumber16 (
VOID
);
/**
Generates a 32-bit pseudo random number.
This generator is still guaranteed to be cryptographically secure
by the use of CPRNG with entropy.
@retval 32-bit pseudo random number.
**/
UINT32
EFIAPI
GetPseudoRandomNumber32 (
VOID
);
/**
Generates a 64-bit pseudo random number.
This generator is still guaranteed to be cryptographically secure
by the use of CPRNG with entropy.
@retval 64-bit pseudo random number.
**/
UINT64
EFIAPI
GetPseudoRandomNumber64 (
VOID
);
#endif // OC_RNG_LIB_H

View File

@ -0,0 +1,94 @@
/** @file
OcRtcLib - library with RTC I/O functions
Copyright (c) 2017-2018, vit9696
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_RTC_LIB_H
#define OC_RTC_LIB_H
#include <Protocol/AppleRtcRam.h>
//
// Standard interface, available on most Intel chipsets
//
UINT8
OcRtcRead (
IN UINT8 Offset
);
VOID
OcRtcWrite (
IN UINT8 Offset,
IN UINT8 Value
);
/**
Calculate Apple CMOS checksum.
This is a modified version of ANSI CRC16 in REFIN mode (0xA001 poly).
See http://zlib.net/crc_v3.txt for more details.
1. Effective poly is 0x2001 due to a bitwise OR with BIT15.
The change turns CRC16 into CRC14, making BIT14 and BIT15 always zero.
This modification is commonly found in legacy Phoenix firmwares,
where it was used for password hashing as found by dogbert:
http://sites.google.com/site/dogber1/blag/pwgen-5dec.py
2. Only 7 shifts per byte are performed instead of the usual 8.
This might improve checksum quality against specific data, but the exact
reasons are unknown. The algorithm did not change since its introduction
in 10.4.x, and since Apple Developer Transition Kit was based on Phoenix
firmware, this could just be a quick change to get a different checksum.
@param[in] Data Pointer to data to calculate the checksum of.
@param[in] Size Size of data.
@retval Resulting checksum.
**/
UINT16
OcRtcChecksumApple (
IN CONST VOID *Data,
IN UINTN Size
);
/**
Install and initialise Apple RTC RAM protocol.
@param[in] Reinstall Overwrite installed protocol.
@retval installed or located protocol or NULL.
**/
APPLE_RTC_RAM_PROTOCOL *
OcAppleRtcRamInstallProtocol (
IN BOOLEAN Reinstall
);
//
// Modern faster interface, available on IvyBridge or newer
//
UINT8
OcRtcReadIvy (
IN UINT8 Offset
);
VOID
OcRtcWriteIvy (
IN UINT8 Offset,
IN UINT8 Value
);
#endif // OC_RTC_LIB_H

View File

@ -12,8 +12,10 @@
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef OC_STRING_LIB_H_
#define OC_STRING_LIB_H_
#ifndef OC_STRING_LIB_H
#define OC_STRING_LIB_H
#include <Uefi.h>
/**
Returns the length of a Null-terminated string literal.
@ -65,7 +67,7 @@ IsAsciiSpace (
/** Convert null terminated ascii string to unicode.
@param[in] String1 A pointer to the ascii string to convert to unicode.
@param[in] String A pointer to the ascii string to convert to unicode.
@param[in] Length Length or 0 to calculate the length of the ascii string to convert.
@retval A pointer to the converted unicode string allocated from pool.
@ -90,6 +92,28 @@ AsciiUint64ToLowerHex (
IN UINT64 Value
);
/**
Alternative to AsciiSPrint, which checks that the buffer can contain all the characters.
@param StartOfBuffer A pointer to the output buffer for the produced Null-terminated
ASCII string.
@param BufferSize The size, in bytes, of the output buffer specified by StartOfBuffer.
@param FormatString A Null-terminated ASCII format string.
@param ... Variable argument list whose contents are accessed based on the
format string specified by FormatString.
@retval EFI_SUCCESS When data was printed to supplied buffer.
@retval EFI_OUT_OF_RESOURCES When supplied buffer cannot contain all the characters.
**/
EFI_STATUS
EFIAPI
OcAsciiSafeSPrint (
OUT CHAR8 *StartOfBuffer,
IN UINTN BufferSize,
IN CONST CHAR8 *FormatString,
...
);
/**
Performs a case insensitive comparison of two Null-terminated Unicode strings,
and returns the difference between the first mismatched Unicode characters.
@ -121,7 +145,7 @@ AsciiUint64ToLowerHex (
**/
INTN
EFIAPI
StriCmp (
OcStriCmp (
IN CHAR16 *FirstString,
IN CHAR16 *SecondString
);
@ -166,12 +190,85 @@ StriCmp (
**/
INTN
EFIAPI
StrniCmp (
OcStrniCmp (
IN CONST CHAR16 *FirstString,
IN CONST CHAR16 *SecondString,
IN UINTN Length
);
/**
Returns the first occurrence of a Null-terminated Unicode sub-string
in a Null-terminated Unicode string through a case insensitive comparison.
This function scans the contents of the Null-terminated Unicode string
specified by String and returns the first occurrence of SearchString.
If SearchString is not found in String, then NULL is returned. If
the length of SearchString is zero, then String is returned.
If String is NULL, then ASSERT().
If String is not aligned on a 16-bit boundary, then ASSERT().
If SearchString is NULL, then ASSERT().
If SearchString is not aligned on a 16-bit boundary, then ASSERT().
If PcdMaximumUnicodeStringLength is not zero, and SearchString
or String contains more than PcdMaximumUnicodeStringLength Unicode
characters, not including the Null-terminator, then ASSERT().
@param String The pointer to a Null-terminated Unicode string.
@param SearchString The pointer to a Null-terminated Unicode string to search for.
@retval NULL If the SearchString does not appear in String.
@return others If there is a match.
**/
CHAR16 *
EFIAPI
OcStriStr (
IN CONST CHAR16 *String,
IN CONST CHAR16 *SearchString
);
/**
Search substring in string.
@param[in] String Search string.
@param[in] StringLength Search string length.
@param[in] SearchString String to search.
@param[in] SearchStringLength String to search length.
@retval NULL If the SearchString does not appear in String.
@retval others If there is a match.
**/
CONST CHAR16 *
OcStrStrLength (
IN CONST CHAR16 *String,
IN UINTN StringLength,
IN CONST CHAR16 *SearchString,
IN UINTN SearchStringLength
);
/**
Alternative to UnicodeSPrint, which checks that the buffer can contain all the characters.
@param StartOfBuffer A pointer to the output buffer for the produced Null-terminated
Unicode string.
@param BufferSize The size, in bytes, of the output buffer specified by StartOfBuffer.
@param FormatString A Null-terminated Unicode format string.
@param ... Variable argument list whose contents are accessed based on the
format string specified by FormatString.
@retval EFI_SUCCESS When data was printed to supplied buffer.
@retval EFI_OUT_OF_RESOURCES When supplied buffer cannot contain all the characters.
**/
EFI_STATUS
EFIAPI
OcUnicodeSafeSPrint (
OUT CHAR16 *StartOfBuffer,
IN UINTN BufferSize,
IN CONST CHAR16 *FormatString,
...
);
/**
Convert path with mixed slashes to UEFI slashes (\\).
@ -194,4 +291,4 @@ UnicodeFilterString (
IN BOOLEAN SingleLine
);
#endif // OC_STRING_LIB_H_
#endif // OC_STRING_LIB_H

30
Include/Library/OcTimerLib.h Executable file
View File

@ -0,0 +1,30 @@
/** @file
Copyright (C) 2016, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_TIMER_LIB_H
#define OC_TIMER_LIB_H
#include <Library/TimerLib.h>
/**
Calculate the TSC frequency
@retval The calculated TSC frequency.
**/
UINT64
RecalculateTSC (
VOID
);
#endif // OC_TIMER_LIB_H

View File

@ -0,0 +1,15 @@
/** @file
Copyright (c) 2020, vit9696. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
**/
#ifndef MICROSOFT_WINDOWS_H
#define MICROSOFT_WINDOWS_H
///
/// Windows bootloader path.
/// REF: https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/bcd-system-store-settings-for-uefi
///
#define MS_BOOTER_DEFAULT_FILE_NAME L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi"
#endif // MICROSOFT_WINDOWS_H

View File

@ -0,0 +1,150 @@
/** @file
Apple Debug Log protocol.
Copyright (C) 2020, vit9696. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_DEBUG_LOG_H
#define APPLE_DEBUG_LOG_H
/**
Apple Debug Log protocol GUID.
DDFA34FB-FE1F-48EA-B213-FB4A4CD57BE3
**/
#define APPLE_DEBUG_LOG_PROTOCOL_GUID \
{ 0xDDFA34FB, 0xFE1F, 0x48EA, \
{ 0xB2, 0x13, 0xFB, 0x4A, 0x4C, 0xD5, 0x7B, 0xE3 } }
/**
Current supported revision.
**/
#define APPLE_DEBUG_LOG_PROTOCOL_REVISION 0x10000
/**
Maximum logfile size.
**/
#define APPLE_DEBUG_LOG_PROTOCOL_FILESIZE BASE_2MB
/**
Logfile name on EFI system partition (indices 1~8).
**/
#define APPLE_DEBUG_LOG_PROTOCOL_FILENAME L"\\EFI\\APPLE\\LOG\\BOOT-%u.LOG"
/**
Legacy boot.efi logfile.
**/
#define APPLE_DEBUG_LOG_PROTOCOL_BOOTLOG L"\\BOOTLOG"
/**
Legacy previous boot.efi logfile.
**/
#define APPLE_DEBUG_LOG_PROTOCOL_BOOTLOG_OLD L"\\BOOTLOG.OLD"
/**
Apple Debug Log protocol structure forward declaration.
**/
typedef struct APPLE_DEBUG_LOG_PROTOCOL_ APPLE_DEBUG_LOG_PROTOCOL;
/**
Send debug message to the protocol.
@param[in] Message ASCII message to log.
@retval EFI_SUCCESS on success.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DEBUG_LOG_PRINT) (
IN CONST CHAR8 *Message
);
/**
Extract characters from the log buffer.
@param[in,out] Position Starting position for extraction.
@param[in,out] BufferSize Extraction buffer size.
@param[out] Buffer Extraction buffer, optional.
@param[out] LostCharacters Amount of characters that did not fit the buffer, optional.
- Position is automatically updated to point to the end of the buffer if provided
value is too large.
- Position is automatically updated to point after extracted characters if Buffer is
not NULL.
@retval EFI_INVALID_PARAMETER if Position or BufferSize are NULL.
@retval EFI_SUCCESS on successful extraction.
@retval EFI_SUCCESS on reported size in BufferSize if Buffer is NULL.
@retval EFI_END_OF_FILE on empty buffer.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DEBUG_LOG_EXTRACT_BUFFER) (
IN OUT UINT32 *Position,
IN OUT UINTN *BufferSize,
OUT CHAR8 *Buffer OPTIONAL,
OUT UINT32 *LostCharacters OPTIONAL
);
/**
Save debug log to 1st APPLE_DEBUG_LOG_PROTOCOL_FILENAME
on logging partition. Saving debug log includes extracting
all previously unsaved characters from the debug log buffer.
On first call this function performs log rotation:
- 8th APPLE_DEBUG_LOG_PROTOCOL_FILENAME is removed.
- APPLE_DEBUG_LOG_PROTOCOL_FILENAMEs from 1st to 7th are renamed to 2nd to 8th.
Truncated character amount is reflected in the log before writing to file.
@retval EFI_SUCCESS on success.
@retval EFI_UNSUPPORTED if current TPL is above TPL_CALLBACK.
@retval EFI_NOT_FOUND on write failure.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DEBUG_LOG_WRITE_FILES) (
VOID
);
/**
Performs a one-time operation of setting up an event for
EfiSimpleFileSystem protocol installation and triggering
its handler for all currently present file systems.
Event handler is supposed to handle all ESP partitions:
- Set modification time of APPLE_DEBUG_LOG_PROTOCOL_FILENAME
to current if it is before 2000 year.
- Remove APPLE_DEBUG_LOG_PROTOCOL_FILENAME created or modified
more than a month ago.
- Remove APPLE_DEBUG_LOG_PROTOCOL_BOOTLOG and
APPLE_DEBUG_LOG_PROTOCOL_BOOTLOG_OLD files if present.
- Update logging partition to current handled partition.
**/
typedef
VOID
(EFIAPI *APPLE_DEBUG_LOG_SETUP_FILES) (
VOID
);
/**
Apple debug log protocol.
**/
struct APPLE_DEBUG_LOG_PROTOCOL_ {
UINTN Revision;
APPLE_DEBUG_LOG_PRINT Print;
APPLE_DEBUG_LOG_EXTRACT_BUFFER ExtractBuffer;
APPLE_DEBUG_LOG_WRITE_FILES WriteFiles;
APPLE_DEBUG_LOG_SETUP_FILES SetupFiles;
};
extern EFI_GUID gAppleDebugLogProtocolGuid;
#endif // APPLE_DEBUG_LOG_H

View File

@ -0,0 +1,110 @@
/** @file
Apple Disk Image protocol.
Copyright (C) 2019, vit9696. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_DISK_IMAGE_PROTOCOL_H
#define APPLE_DISK_IMAGE_PROTOCOL_H
/**
Apple Disk Image protocol GUID.
004B07E8-0B9C-427E-B0D4-A466E6E57A62
**/
#define APPLE_DISK_IMAGE_PROTOCOL_GUID \
{ 0x004B07E8, 0x0B9C, 0x427E, \
{ 0xB0, 0xD4, 0xA4, 0x66, 0xE6, 0xE5, 0x7A, 0x62 } }
/**
Apple Disk Image protocol revision.
**/
#define APPLE_DISK_IMAGE_PROTOCOL_REVISION 2
/**
Checks whether dmg file at DevicePath is valid.
Essentially this is done by verifying last 512 bytes
of the file.
@param[in] DevicePath Path to dmg file.
@retval EFI_SUCCESS Dmg looks valid and can be loaded.
@retval EFI_UNSUPPORTED Dmg is unsupported.
@retval EFI_NOT_FOUND Dmg was not found at this device path.
@retval EFI_OUT_OF_RESOURCES Memory allocation error happened.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DISK_IMAGE_SUPPORTED) (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Mounts dmg file at DevicePath providing relevant protocols:
- gEfiDevicePathProtocolGuid
- gEfiBlockIoProtocolGuid
- gTDMApprovedGuid
- gAppleDiskImageProtocolGuid (as NULL)
Mounted dmg handle is to be connnected recursively on all protocols
with connection status unchecked.
Note, that DiskImage protocol does not protect DMG memory from the kernel.
It only works in UEFI scope. For the kernel to boot the parent protocol,
namely RamDisk, should have us covered by allocating DMG extent memory
as wired (EfiACPIMemoryNVS).
@param[in] DevicePath Path to dmg file.
@param[out] Handle Dmg handle.
@retval EFI_SUCCESS Dmg was mounted with relevant protocols.
@retval EFI_INVALID_PARAMETER Dmg is not valid.
@retval EFI_UNSUPPORTED Dmg is less than 512 bytes.
@retval EFI_NOT_FOUND Dmg was not found at this device path.
@retval EFI_OUT_OF_RESOURCES Memory allocation error happened.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DISK_IMAGE_MOUNT_IMAGE) (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
OUT EFI_HANDLE *Handle OPTIONAL
);
/**
Unmounts dmg file at handle and uninstalls the following protocols:
- gEfiDevicePathProtocolGuid
- gEfiBlockIoProtocolGuid
- gAppleDiskImageProtocolGuid
All the resources consumed by the dmg will be freed.
@param[in] Handle Dmg handle.
@retval EFI_SUCCESS Dmg was unmounted with relevant protocols.
@retval EFI_INVALID_PARAMETER Dmg handle is not valid.
@retval EFI_NOT_FOUND Relevant protocols were not found.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_DISK_IMAGE_UNMOUNT_IMAGE) (
IN EFI_HANDLE Handle
);
/**
Apple disk imge protocol.
**/
typedef struct {
UINT32 Revision;
APPLE_DISK_IMAGE_SUPPORTED Supported;
APPLE_DISK_IMAGE_MOUNT_IMAGE MountImage;
APPLE_DISK_IMAGE_UNMOUNT_IMAGE UnmountImage;
} APPLE_DISK_IMAGE_PROTOCOL;
extern EFI_GUID gAppleDiskImageProtocolGuid;
#endif // APPLE_DISK_IMAGE_PROTOCOL_H

View File

@ -0,0 +1,43 @@
/** @file
Copyright (C) 2020, vit9696. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_FRAMEBUFFER_INFO_H
#define APPLE_FRAMEBUFFER_INFO_H
///
/// The GUID of the APPLE_FRAMEBUFFER_INFO_PROTOCOL.
///
#define APPLE_FRAMEBUFFER_INFO_PROTOCOL_GUID \
{ 0xE316E100, 0x0751, 0x4C49, \
{ 0x90, 0x56, 0x48, 0x6C, 0x7E, 0x47, 0x29, 0x03 } }
typedef struct APPLE_FRAMEBUFFER_INFO_PROTOCOL_ APPLE_FRAMEBUFFER_INFO_PROTOCOL;
typedef
EFI_STATUS
(EFIAPI *APPLE_FRAMEBUFFER_INFO_GET_INFO) (
IN APPLE_FRAMEBUFFER_INFO_PROTOCOL *This,
OUT EFI_PHYSICAL_ADDRESS *FramebufferBase,
OUT UINT32 *FramebufferSize,
OUT UINT32 *ScreenRowBytes,
OUT UINT32 *ScreenWidth,
OUT UINT32 *ScreenHeight,
OUT UINT32 *ScreenDepth
);
struct APPLE_FRAMEBUFFER_INFO_PROTOCOL_ {
APPLE_FRAMEBUFFER_INFO_GET_INFO GetInfo;
};
extern EFI_GUID gAppleFramebufferInfoProtocolGuid;
#endif // APPLE_FRAMEBUFFER_INFO_H

View File

@ -88,7 +88,7 @@ struct APPLE_KEY_MAP_AGGREGATOR_PROTOCOL {
KEY_MAP_CONTAINS_KEY_STROKES ContainsKeyStrokes;
};
// gAppleKeyMapAggregatorProtocolGuid
extern EFI_GUID gAppleKeyMapAggregatorProtocolGuid;
// gAppleKeyStateProtocolGuid
extern EFI_GUID gAppleKeyStateProtocolGuid;
#endif // APPLE_KEY_MAP_AGGREGATOR_H

View File

@ -18,7 +18,10 @@
#ifndef APPLE_KEY_MAP_DATABASE_H_
#define APPLE_KEY_MAP_DATABASE_H_
// APPLE_KEY_MAP_DATABASE_PROTOCOL_GUID
#include <IndustryStandard/AppleHid.h>
// APPLE_KEY_MAP_DATABASE_PROTOCOL_REVISION
#define APPLE_KEY_MAP_DATABASE_PROTOCOL_REVISION 0x00010000
#define APPLE_KEY_MAP_DATABASE_PROTOCOL_GUID \
{0x584B9EBE, 0x80C1, 0x4BD6, \

View File

@ -0,0 +1,386 @@
/** @file
Apple RAM Disk protocol.
Copyright (C) 2019, vit9696. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_RAM_DISK_PROTOCOL_H
#define APPLE_RAM_DISK_PROTOCOL_H
#include <Library/DebugLib.h>
#include <Protocol/BlockIo.h>
#include <Protocol/DevicePath.h>
/**
Apple RAM Disk protocol GUID.
957932CC-7E8E-433B-8F41-D391EA3C10F8
**/
#define APPLE_RAM_DISK_PROTOCOL_GUID \
{ 0x957932CC, 0x7E8E, 0x433B, \
{ 0x8F, 0x41, 0xD3, 0x91, 0xEA, 0x3C, 0x10, 0xF8 } }
/**
Apple RAM Disk protocol revision.
**/
#define APPLE_DMG_BOOT_PROTOCOL_REVISION 3
/**
RAM Disk extent signature, "RAMDXTNT".
**/
#define APPLE_RAM_DISK_EXTENT_SIGNATURE 0x544E5458444D4152ULL
/**
RAM Disk extent version.
**/
#define APPLE_RAM_DISK_EXTENT_VERSION 0x10000U
/**
RAM Disk maximum extent count.
**/
#define APPLE_RAM_DISK_MAX_EXTENTS 0xFE
#pragma pack(push, 1)
/**
RAM Disk extent.
When automatically allocating at RAM disk creation, extents are created
on demand as long as contiguous memory is found in the firmware.
Please note, that this must match IOAddressRange type in XNU,
which can be found in iokit/IOKit/IOTypes.h.
**/
typedef PACKED struct {
///
/// Extentent address pointing to a sequence of allocated pages from
/// EfiACPIMemoryNVS or EfiBootServicesData depending on RamDisk init.
///
UINT64 Start;
///
/// Actual size of the extent. Allocated area size may be >= Length.
///
UINT64 Length;
} APPLE_RAM_DISK_EXTENT;
/**
RAM Disk externally accessible header containing references to extents.
**/
typedef PACKED struct {
///
/// Set to APPLE_RAM_DISK_EXTENT_SIGNATURE.
///
UINT64 Signature;
///
/// Set to APPLE_RAM_DISK_EXTENT_VERSION.
///
UINT32 Version;
///
/// Externally visible amount of extents.
///
UINT32 ExtentCount;
///
/// Externally visible extent array.
///
APPLE_RAM_DISK_EXTENT Extents[APPLE_RAM_DISK_MAX_EXTENTS];
///
/// Currently reserved or rather unknown.
///
UINT64 Reserved;
///
/// Set to APPLE_RAM_DISK_EXTENT_SIGNATURE.
///
UINT64 Signature2;
} APPLE_RAM_DISK_EXTENT_TABLE;
/**
RAM Disk protocol context. This might be called scatter pool.
**/
typedef PACKED struct {
///
/// Internally visible amount of extents.
///
UINT64 ExtentCount;
///
/// Currently reserved or rather unknown. Padding?
///
UINT64 Reserved1;
///
/// Total addressible disk size specified at creation.
///
UINT64 DiskSize;
///
/// Internally visible extent array.
///
APPLE_RAM_DISK_EXTENT Extents[APPLE_RAM_DISK_MAX_EXTENTS];
///
/// Currently reserved or rather unknown. Padding?
///
UINT64 Reserved2;
///
/// Normal extent table.
///
APPLE_RAM_DISK_EXTENT_TABLE ExtentTable;
///
/// More data may follow, for Apple implementation it will be 0x9FD000 bytes.
/// (This struct and 1 page for internal header.)
///
} APPLE_RAM_DISK_CONTEXT;
/**
RAM Disk vendor device path, 24 bytes in total.
**/
typedef PACKED struct {
///
/// Vendor device path.
/// Type = HARDWARE_DEVICE_PATH.
/// Subtype = HW_VENDOR_DP.
/// Length = sizeof (VENDOR_DEVICE_PATH) + sizeof (UINT32).
/// Guid = APPLE_RAM_DISK_PROTOCOL_GUID.
///
VENDOR_DEVICE_PATH Vendor;
///
/// Globally incremented counter to make every path unique.
///
UINT32 Counter;
} APPLE_RAM_DISK_DP_VENDOR;
/**
RAM Disk device path header for endpoint devices.
**/
typedef PACKED struct {
///
/// Vendor device path.
///
APPLE_RAM_DISK_DP_VENDOR Vendor;
///
/// Memmap device path.
///
MEMMAP_DEVICE_PATH MemMap;
} APPLE_RAM_DISK_DP_HEADER;
/**
RAM Disk device path, 52 bytes in total.
**/
typedef PACKED struct {
///
/// Vendor device path with APPLE_RAM_DISK_PROTOCOL_GUID.
/// Type = HARDWARE_DEVICE_PATH.
/// Subtype = HW_MEMMAP_DP.
/// Length = sizeof (APPLE_RAM_DISK_ENTRY_DP).
/// StartingAddresss = APPLE_RAM_DISK_EXTENT_TABLE pointer.
/// EndingAddress = StartingAddresss + sizeof (APPLE_RAM_DISK_EXTENT_TABLE).
/// MemoryType = EfiACPIMemoryNVS or EfiBootServicesData as allocated.
///
/// Note: EndingAddress, per UEFI specification and edk2 implementation, is supposed
/// to be the top usable address, not the top of the buffer. Perhaps there is a mistake here.
///
APPLE_RAM_DISK_DP_VENDOR Vendor;
///
/// Memmap device path.
///
MEMMAP_DEVICE_PATH MemMap;
///
/// Device path end.
///
EFI_DEVICE_PATH_PROTOCOL End;
} APPLE_RAM_DISK_DP;
#pragma pack(pop)
/**
Create new RAM disk providing relevant protocols:
- gEfiDevicePathProtocolGuid
- gEfiBlockIoProtocolGuid
- gAppleRamDiskProtocolGuid (as NULL)
When AllocateMemory is TRUE, a writeable RAM disk is created.
Its contents are initially zeroed, and then may be modified through normal writing
and via RAM Disk context, which is accessible through GetRamDiskContext.
When AllocateMemory is FALSE, a read only RAM disk is created.
Its contents are not allocated but reported to be all zero.
MemMap StartingAddresss will be 0 and EndingAddress will be sizeof (APPLE_RAM_DISK_EXTENT_TABLE).
Vit: Since no context is allocated, there is no way to initialise this disk image except in an
implementatation specific way. AllocateMemory = FALSE is never used, so it may be a bug.
@param[in] BlockCount Block amount, ignored if AllocateMemory is FALSE.
@param[in] BlockSize Block size, ignored if AllocateMemory is FALSE.
@param[in] AllocateMemory Allocate disk memory.
@param[in] ReserveMemory Mark memory as EfiACPIMemoryNVS, otherwise EfiBootServicesData.
@param[in] Handle Resulting handle.
@retval EFI_SUCCESS RAM disk was successfully created.
@retval EFI_OUT_OF_RESOURCES Requested RAM disk of more than SIZE_16TB.
@retval EFI_OUT_OF_RESOURCES Memory allocation error happened.
@retval EFI_INVALID_PARAMETER Too many extents are needed for the allocation.
@retval EFI_BUFFER_TOO_SMALL Not enough extents to allocate context extent.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RAM_DISK_CREATE) (
IN UINT64 BlockCount OPTIONAL,
IN UINT32 BlockSize OPTIONAL,
IN BOOLEAN AllocateMemory,
IN BOOLEAN ReserveMemory,
OUT EFI_HANDLE *Handle
);
/**
Destroy RAM disk freeing resources and uninstalling relevant protocols:
- gEfiDevicePathProtocolGuid
- gEfiBlockIoProtocolGuid
- gAppleRamDiskProtocolGuid
- gTDMApprovedGuid
@param[in] Handle RAM disk handle.
@retval EFI_INVALID_PARAMETER Not a RAM disk handle.
@retval EFI_NOT_FOUND Missing Block I/O protocol.
@retval EFI_SUCCESS Destroyed successfully.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RAM_DISK_DESTROY) (
IN EFI_HANDLE Handle
);
/**
Obtain RAM disk context. Context exists only for "allocated" RAM disks,
i.e. disks created with AllocateMemory = TRUE. When an unallocated
RAM disk is created, NULL Context will be returned.
@param[in] Handle RAM disk handle.
@param[out] Context RAM disk context.
@retval EFI_INVALID_PARAMETER Not a RAM disk handle.
@retval EFI_NOT_FOUND Missing Block I/O protocol.
@retval EFI_SUCCESS Obtained NULL or non-NULL context successfully.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RAM_DISK_GET_CONTEXT) (
IN EFI_HANDLE Handle,
OUT APPLE_RAM_DISK_CONTEXT *Context
);
/**
Apple RAM Disk protocol.
**/
typedef struct {
UINT64 Revision;
APPLE_RAM_DISK_CREATE CreateRamDisk;
APPLE_RAM_DISK_DESTROY DestroyRamDisk;
APPLE_RAM_DISK_GET_CONTEXT GetRamDiskContext;
} APPLE_RAM_DISK_PROTOCOL;
/*
STATIC_ASSERT (sizeof (APPLE_RAM_DISK_DP_VENDOR) == 24, "Invalid APPLE_RAM_DISK_DP_VENDOR size");
STATIC_ASSERT (sizeof (APPLE_RAM_DISK_DP) == 52, "Invalid APPLE_RAM_DISK_DP size");
STATIC_ASSERT (sizeof (APPLE_RAM_DISK_EXTENT) == 16, "Invalid APPLE_RAM_DISK_EXTENT size");
STATIC_ASSERT (sizeof (APPLE_RAM_DISK_EXTENT_TABLE) == 4096, "Invalid APPLE_RAM_DISK_EXTENT_TABLE size");
STATIC_ASSERT (sizeof (APPLE_RAM_DISK_CONTEXT) == 8192, "Invalid APPLE_RAM_DISK_CONTEXT size");
*/
extern EFI_GUID gAppleRamDiskProtocolGuid;
/**
Vit: Below come the implementation specific details, which probably do not belong here.
Since this is the only way to initialize RAM disk when it was not allocated at creation time,
I put it here for now.
**/
/**
RAM Disk instance signature, "RAMD".
**/
#define APPLE_RAM_DISK_INSTANCE_SIGNATURE 0x444D4152U
/**
RAM Disk default size.
This value is used when allocating APPLE_RAM_DISK structure.
**/
#define APPLE_RAM_DISK_DEFAULT_SIZE 0xA00000U
/**
RAM Disk outermost structure. Allocated in pages with matching MemoryType.
**/
typedef struct {
///
/// Amount of allocated extents in the RAM disk.
///
UINT64 AllocatedExtents;
///
/// Amount of allocated pages in APPLE_RAM_DISK structure.
/// Normally EFI_SIZE_TO_PAGES (APPLE_RAM_DISK_DEFAULT_SIZE).
///
UINT64 PageCount;
///
/// Total disk size allocated from memory map.
/// It is bigger by sizeof(APPLE_RAM_DISK_CONTEXT) than actual requested size,
/// when AllocateMemory = TRUE is specified.
///
UINT64 TotalSize;
///
/// All allocated and owned extents.
/// First extent is special, as it points to OwnExtentData, and thus
/// has APPLE_RAM_DISK_DEFAULT_SIZE - sizeof (APPLE_RAM_DISK) bytes.
///
APPLE_RAM_DISK_EXTENT Extents[APPLE_RAM_DISK_MAX_EXTENTS];
///
/// Currently reserved or rather unknown. Padding?
///
UINT64 Reserved;
///
/// Own extent data lasting till PageCount end.
///
UINT8 OwnExtentData[];
} APPLE_RAM_DISK;
/**
Apple RAM Disk instance structure.
**/
typedef struct {
///
/// Set to APPLE_RAM_DISK_INSTANCE_SIGNATURE.
///
UINT32 Magic;
///
/// Set to RAM disk handle, formerly returned with CreateRamDisk.
///
EFI_HANDLE Handle;
///
/// RAM disk device path.
///
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
///
/// RAM disk Block I/O protocol.
///
EFI_BLOCK_IO_PROTOCOL BlockIo;
///
/// Outer RAM disk structure, which owns all allocated extents.
/// This field is NULL when AllocateMemory = FALSE.
///
APPLE_RAM_DISK *RamDisk;
///
/// RAM disk context allocated within RAM disk structure memory.
/// Apple implementation puts it to the end of RamDisk structure.
/// This field is NULL when AllocateMemory = FALSE.
///
APPLE_RAM_DISK_CONTEXT *Context;
///
/// Extra pointer to Context->Extents.
/// This field is NULL when AllocateMemory = FALSE.
///
APPLE_RAM_DISK_EXTENT_TABLE *Extents;
///
/// Total addressible disk size specified at creation.
/// This field is -1 when AllocateMemory = FALSE.
///
INT64 DiskSize;
} APPLE_RAM_DISK_INSTANCE;
#endif // APPLE_RAM_DISK_PROTOCOL_H

View File

@ -0,0 +1,144 @@
/** @file
Apple RTC RAM.
Copyright (C) 2020, vit9696. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
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 APPLE_RTC_RAM_PROTOCOL_H
#define APPLE_RTC_RAM_PROTOCOL_H
#include <IndustryStandard/AppleRtc.h>
/**
Installed by RTC driver.
E121EC07-9C42-45EE-B0B6-FFF8EF03C521
Found in AppleRtcRam (CC54F583-3F9E-4AB0-9F7C-D2C7ED1C87A5).
Note, there is a sibling driver in PEI:
13CFE225-E07B-40F3-9703-EBE99318766E
Found in AppleRtcRamPeim (1B99796D-2A26-437E-BEE0-014F0EBBECE1).
**/
#define APPLE_RTC_RAM_PROTOCOL_GUID \
{ 0xE121EC07, 0x9C42, 0x45EE, \
{ 0xB0, 0xB6, 0xFF, 0xF8, 0xEF, 0x03, 0xC5, 0x21 } }
typedef struct APPLE_RTC_RAM_PROTOCOL_ APPLE_RTC_RAM_PROTOCOL;
/**
Obtain available RTC memory in bytes.
@param[in] This Apple RTC RAM protocol instance.
@retval 256 under normal circumstances.
**/
typedef
UINTN
(EFIAPI *APPLE_RTC_RAM_GET_AVAILABLE_MEMORY) (
IN APPLE_RTC_RAM_PROTOCOL *This
);
/**
Read memory from RTC.
@param[in] This Apple RTC RAM protocol instance.
@param[out] Buffer Destination buffer to read to.
@param[in] BufferSize The amount of memory to read in bytes.
@param[in] Address The starting RTC offset to read from.
The implementation should respect data consistency:
- If APPLE_RTC_BG_COLOR_ADDR ^ APPLE_RTC_BG_COMPLEMENT_ADDR != 0xFF
APPLE_RTC_BG_COLOR_GRAY should be returned for APPLE_RTC_BG_COLOR_ADDR.
@retval EFI_INVALID_PARAMETER when Buffer is NULL.
@retval EFI_INVALID_PARAMETER when BufferSize is 0.
@retval EFI_INVALID_PARAMETER when the requested memory is out of range.
@retval EFI_ACCESS_DENIED when an RTC I/O operating is in progress.
@retval EFI_TIMEOUT when RTC device is not ready.
@retval EFI_SUCCESS on success.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RTC_RAM_READ_MEMORY) (
IN APPLE_RTC_RAM_PROTOCOL *This,
OUT UINT8 *Buffer,
IN UINTN BufferSize,
IN UINTN Address
);
/**
Write memory to RTC.
@param[in] This Apple RTC RAM protocol instance.
@param[in] Buffer Source buffer to write to RTC.
@param[in] BufferSize The amount of memory to write in bytes.
@param[in] Address The starting RTC offset to write to.
The implementation should maintain data consistency:
- APPLE_RTC_BG_COMPLEMENT_ADDR should be set to ~APPLE_RTC_BG_COLOR_ADDR.
- APPLE_RTC_CORE_CHECKSUM_ADDR1 / APPLE_RTC_CORE_CHECKSUM_ADDR2 should
be recalculated if necessary.
- APPLE_RTC_MAIN_CHECKSUM_ADDR1 / APPLE_RTC_MAIN_CHECKSUM_ADDR2 should
be recalculated if necessary.
@retval EFI_INVALID_PARAMETER when Buffer is NULL.
@retval EFI_INVALID_PARAMETER when BufferSize is 0.
@retval EFI_INVALID_PARAMETER when the requested memory is out of range.
@retval EFI_INVALID_PARAMETER when trying to update system memory
before APPLE_RTC_CHECKSUM_START.
@retval EFI_OUT_OF_RESOURCES when a memory allocation error happened.
@retval EFI_ACCESS_DENIED when an RTC I/O operating is in progress.
@retval EFI_TIMEOUT when RTC device is not ready.
@retval EFI_SUCCESS on success.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RTC_RAM_WRITE_MEMORY) (
IN APPLE_RTC_RAM_PROTOCOL *This,
IN CONST UINT8 *Buffer,
IN UINTN BufferSize,
IN UINTN Address
);
/**
Reset RTC memory to default values. For uses like CMD+OPT+P+R.
The implementation should maintain data consistency:
- Core memory as defined by APPLE_RTC_CORE_SIZE should not be changed.
- Preserve APPLE_RTC_RESERVED_ADDR area.
- Preserve APPLE_RTC_FIRMWARE_57_ADDR address.
@param[in] This Apple RTC RAM protocol instance.
@retval EFI_OUT_OF_RESOURCES when a memory allocation error happened.
@retval EFI_ACCESS_DENIED when an RTC I/O operating is in progress.
@retval EFI_TIMEOUT when RTC device is not ready.
@retval EFI_SUCCESS on success.
**/
typedef
EFI_STATUS
(EFIAPI *APPLE_RTC_RAM_RESET_MEMORY) (
IN APPLE_RTC_RAM_PROTOCOL *This
);
/**
Apple RTC protocol structure.
**/
struct APPLE_RTC_RAM_PROTOCOL_ {
APPLE_RTC_RAM_GET_AVAILABLE_MEMORY GetAvailableMemory;
APPLE_RTC_RAM_READ_MEMORY ReadMemory;
APPLE_RTC_RAM_WRITE_MEMORY WriteMemory;
APPLE_RTC_RAM_RESET_MEMORY ResetMemory;
};
extern EFI_GUID gAppleRtcRamProtocolGuid;
#endif // APPLE_RTC_RAM_PROTOCOL_H

View File

@ -1,59 +1,66 @@
/** @file
Copyright (C) 2005 - 2015, Apple Inc. All rights reserved.<BR>
Copyright (C) 2014 - 2017, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
This program and the accompanying materials have not been licensed.
Neither is its usage, its redistribution, in source or binary form,
licensed, nor implicitely or explicitely permitted, except when
required by applicable law.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Unless required by applicable law or agreed to in writing, software
distributed is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied.
**/
#ifndef EFI_OS_INFO_H_
#define EFI_OS_INFO_H_
#ifndef EFI_OS_INFO_H
#define EFI_OS_INFO_H
// EFI_OS_INFO_PROTOCOL_REVISION
#define EFI_OS_INFO_PROTOCOL_REVISION3 0x00000003
// EFI_OS_INFO_PROTOCOL_GUID
#define EFI_OS_INFO_PROTOCOL_GUID \
{ 0xC5C5DA95, 0x7D5C, 0x45E6, \
#define EFI_OS_INFO_PROTOCOL_GUID \
{ 0xC5C5DA95, 0x7D5C, 0x45E6, \
{ 0xB2, 0xF1, 0x3F, 0xD5, 0x2B, 0xB1, 0x00, 0x77 } }
typedef struct _EFI_OS_INFO_PROTOCOL EFI_OS_INFO_PROTOCOL;
// OS_INFO_OS_VENDOR
typedef
VOID
(EFIAPI *OS_INFO_OS_VENDOR)(
IN CHAR8 *OSName
);
#define EFI_OS_INFO_APPLE_VENDOR_NAME "Apple Inc."
// OS_INFO_OS_NAME
typedef
VOID
(EFIAPI *OS_INFO_OS_NAME)(
IN CHAR8 *OSName
);
// OS_INFO_OS_VENDOR
typedef
VOID
(EFIAPI *OS_INFO_EMPTY)(
(EFIAPI *OS_INFO_OS_VENDOR)(
IN CHAR8 *OSName
);
IN CHAR8 *OSName
);
// OS_INFO_SET_VTD_ENABLED
typedef
VOID
(EFIAPI *OS_INFO_SET_VTD_ENABLED)(
IN UINTN *BootVTdEnabled
);
// OS_INFO_GET_VTD_ENABLED
typedef
VOID
(EFIAPI *OS_INFO_GET_VTD_ENABLED)(
OUT UINTN *BootVTdEnabled
);
// EFI_OS_INFO_PROTOCOL
struct _EFI_OS_INFO_PROTOCOL {
UINT64 Revision; ///<
OS_INFO_OS_NAME OSName; ///<
OS_INFO_OS_VENDOR OSVendor; ///<
OS_INFO_EMPTY OSEmpty; ///<
};
typedef struct {
UINTN Revision; ///< Revision.
OS_INFO_OS_NAME OSName; ///< Present as of Revision 1.
OS_INFO_OS_VENDOR OSVendor; ///< Present as of Revision 2.
OS_INFO_SET_VTD_ENABLED SetBootVTdEnabled; ///< Present as of Revision 3.
OS_INFO_GET_VTD_ENABLED GetBootVTdEnabled; ///< Present as of Revision 3.
} EFI_OS_INFO_PROTOCOL;
// gEfiOSInfoProtocolGuid
extern EFI_GUID gEfiOSInfoProtocolGuid;
#endif // EFI_OS_INFO_H_
#endif // EFI_OS_INFO_H

136
Include/Protocol/OcLog.h Executable file
View File

@ -0,0 +1,136 @@
/** @file
Copyright (C) 2016, The HermitCrabs Lab. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 OC_LOG_PROTOCOL_H
#define OC_LOG_PROTOCOL_H
#include <Uefi.h>
#include <Protocol/SimpleFileSystem.h>
///
/// Current supported log protocol revision.
///
#define OC_LOG_REVISION 0x01000A
///
/// The defines for the log flags.
///
#define OC_LOG_ENABLE BIT0
#define OC_LOG_CONSOLE BIT1
#define OC_LOG_DATA_HUB BIT2
#define OC_LOG_SERIAL BIT3
#define OC_LOG_VARIABLE BIT4
#define OC_LOG_NONVOLATILE BIT5
#define OC_LOG_FILE BIT6
typedef UINT32 OC_LOG_OPTIONS;
/**
The GUID of the OC_LOG_PROTOCOL.
**/
#define OC_LOG_PROTOCOL_GUID \
{ 0xDBB6008F, 0x89E4, 0x4272, \
{ 0x98, 0x81, 0xCE, 0x3A, 0xFD, 0x97, 0x24, 0xD0 } }
/**
The forward declaration for the protocol for the OC_LOG_PROTOCOL.
**/
typedef struct OC_LOG_PROTOCOL_ OC_LOG_PROTOCOL;
/**
Add an entry to the log buffer
@param[in] This This protocol.
@param[in] ErrorLevel Debug level.
@param[in] FormatString String containing the output format.
@param[in] Marker Address of the VA_ARGS marker.
@retval EFI_SUCCESS The entry was successfully added.
**/
typedef
EFI_STATUS
(EFIAPI *OC_LOG_ADD_ENTRY) (
IN OC_LOG_PROTOCOL *This,
IN UINTN ErrorLevel,
IN CONST CHAR8 *FormatString,
IN VA_LIST Marker
);
/**
Reset the internal timers
@param[in] This This protocol.
@retval EFI_SUCCESS The timers were reset successfully.
**/
typedef
EFI_STATUS
(EFIAPI *OC_LOG_RESET_TIMERS) (
IN OC_LOG_PROTOCOL *This
);
/**
Retrieve pointer to the log buffer
@param[in] This This protocol.
@param[in] OcLogBuffer Address to store the buffer pointer.
@retval EFI_SUCCESS The timers were reset successfully.
**/
typedef
EFI_STATUS
(EFIAPI *OC_LOG_GET_LOG) (
IN OC_LOG_PROTOCOL *This,
OUT CHAR8 **OcLogBuffer
);
/**
Save the current log
@param[in] This This protocol.
@param[in] NonVolatile Variable.
@param[in] FilePath Filepath to save the log. OPTIONAL
@retval EFI_SUCCESS The log was saved successfully.
**/
typedef
EFI_STATUS
(EFIAPI *OC_LOG_SAVE_LOG) (
IN OC_LOG_PROTOCOL *This,
IN UINT32 NonVolatile OPTIONAL,
IN EFI_DEVICE_PATH_PROTOCOL *FilePath OPTIONAL
);
/**
The structure exposed by the OC_LOG_PROTOCOL.
**/
struct OC_LOG_PROTOCOL_ {
UINT32 Revision; ///< The revision of the installed protocol.
UINTN Reserved; ///< Reserved for future extension.
OC_LOG_ADD_ENTRY AddEntry; ///< A pointer to the AddEntry function.
OC_LOG_GET_LOG GetLog; ///< A pointer to the GetLog function.
OC_LOG_SAVE_LOG SaveLog; ///< A pointer to the SaveLog function.
OC_LOG_RESET_TIMERS ResetTimers; ///< A pointer to the ResetTimers function.
OC_LOG_OPTIONS Options; ///< The current options of the installed protocol.
UINT32 DisplayDelay; ///< The delay after visible onscreen message in microseconds.
UINTN DisplayLevel; ///< The error level visible onscreen.
UINTN HaltLevel; ///< The error level causing CPU dead loop.
EFI_FILE_PROTOCOL *FileSystem; ///< Log file system root, not owned.
CHAR16 *FilePath; ///< Log file path.
};
/// A global variable storing the GUID of the OC_LOG_PROTOCOL.
extern EFI_GUID gOcLogProtocolGuid;
#endif // OC_LOG_PROTOCOL_H

View File

@ -0,0 +1 @@
#define OCQUIRKS_PROTOCOL_REVISION 23

View File

@ -0,0 +1,526 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 BOOT_COMPAT_INTERNAL_H
#define BOOT_COMPAT_INTERNAL_H
#include <Uefi.h>
#include <IndustryStandard/AppleBootArgs.h>
#include <Library/OcAfterBootCompatLib.h>
#include <Library/OcBootManagementLib.h>
#include <Library/OcDebugLogLib.h>
#include <Library/OcMemoryLib.h>
#include <Protocol/LoadedImage.h>
#include <Protocol/OcFirmwareRuntime.h>
#if defined(MDE_CPU_X64)
#include "X64/ContextSwitch.h"
#elif defined(MDE_CPU_IA32)
#include <Ia32/ContextSwitch.h>
#else
#error "Unsupported architecture!"
#endif
//
// The kernel is normally allocated at base 0x100000 + slide address.
//
// For slide=0x1~0x7F the kernel is allocated from
// 0x100000 + 0x200000 till 0x100000 + 0xFE00000.
//
// For slide = 0x80~0xFF on Sandy Bridge or Ivy Bridge CPUs from
// 0x100000 + 0x20200000 till 0x100000? + 0x30000000??.
//
// For slide = 0x80~0xFF on Other CPUs from
// 0x100000 + 0x10000000 till 0x100000 + 0x1FE00000.
//
/**
Maximum number of supported runtime reloc protection areas.
Currently hardocded for simplicity.
**/
#define RT_RELOC_PROTECT_MAX_NUM ((UINTN) 64)
/**
Runtime descriptor number to virtualise.
Currently hardocded for simplicity.
**/
#define RT_DESC_ENTRY_NUM ((UINTN) 64)
/**
Kernel __HIB segment virtual address.
**/
#define KERNEL_HIB_VADDR ((UINTN) (0xFFFFFF8000100000ULL & MAX_UINTN))
/**
Kernel __TEXT segment virtual address.
**/
#define KERNEL_TEXT_VADDR ((UINTN) (0xFFFFFF8000200000ULL & MAX_UINTN))
/**
Kernel physical base address.
**/
#define KERNEL_BASE_PADDR (KERNEL_TEXT_VADDR - KERNEL_HIB_VADDR)
/**
Slide offset per slide entry
**/
#define SLIDE_GRANULARITY ((UINTN) SIZE_2MB)
/**
Total possible number of KASLR slide offsets.
**/
#define TOTAL_SLIDE_NUM ((UINTN) 0x100)
/**
Slide errate number to skip range from.
**/
#define SLIDE_ERRATA_NUM ((UINTN) 0x80)
/**
Sandy/Ivy skip slide range for Intel HD graphics.
**/
#define SLIDE_ERRATA_SKIP_RANGE ((UINTN) 0x10200000)
/**
Assume the kernel is roughly 128 MBs.
**/
#define ESTIMATED_KERNEL_SIZE ((UINTN) SIZE_128MB)
/**
Preserved relocation entry.
**/
typedef struct RT_RELOC_PROTECT_INFO_ {
///
/// Physical address of descriptor start.
///
EFI_PHYSICAL_ADDRESS PhysicalStart;
///
/// Physical address of descriptor end.
///
EFI_PHYSICAL_ADDRESS PhysicalEnd;
///
/// Descriptor original memory type.
///
EFI_MEMORY_TYPE Type;
} RT_RELOC_PROTECT_INFO;
/**
Preserved relocation entry list.
**/
typedef struct RT_RELOC_PROTECT_DATA_ {
///
/// Number of currently used methods in the table.
///
UINTN NumEntries;
///
/// Reloc entries fitted.
///
RT_RELOC_PROTECT_INFO RelocInfo[RT_RELOC_PROTECT_MAX_NUM];
} RT_RELOC_PROTECT_DATA;
/**
UEFI Boot & Runtime Services original pointers.
**/
typedef struct UEFI_SERVICES_POINTERS_ {
///
/// Original page allocator. We override it to obtain
/// the location macOS kernel and hibernation images.
///
EFI_ALLOCATE_PAGES AllocatePages;
///
/// Original page deallocator. We override it to fix memory
/// attributes table as it is updated after page dealloc.
///
EFI_FREE_PAGES FreePages;
///
/// Original memory map function. We override it to make
/// memory map shrinking and CSM region protection.
///
EFI_GET_MEMORY_MAP GetMemoryMap;
///
/// Original pool allocator. We override it to fix memory
/// attributes table as it is updated after pool alloc.
///
EFI_ALLOCATE_POOL AllocatePool;
///
/// Original pool deallocator. We override it to fix memory
/// attributes table as it is updated after pool dealloc.
///
EFI_FREE_POOL FreePool;
///
/// Original exit boot services function. We override it
/// to ensure we always succeed exiting boot services.
///
EFI_EXIT_BOOT_SERVICES ExitBootServices;
///
/// Image starting routine. We override to catch boot.efi
/// loading and enable the rest of functions.
///
EFI_IMAGE_START StartImage;
///
/// Original get variable function. We override it to alter
/// boot.efi boot arguments for custom KASLR slide.
///
EFI_GET_VARIABLE GetVariable;
///
/// Original virtual address mapping function. We override
/// it to perform runtime area protection to prevent boot.efi
/// defragmentation and setup virtual memory for firmwares
/// accessing it after exit boot services.
///
EFI_SET_VIRTUAL_ADDRESS_MAP SetVirtualAddressMap;
} UEFI_SERVICES_POINTERS;
/**
UEFI services override internal state.
**/
typedef struct SERVICES_OVERRIDE_STATE_ {
///
/// GetVariable arrival event.
///
EFI_EVENT GetVariableEvent;
///
/// Firmware runtime protocol instance.
///
OC_FIRMWARE_RUNTIME_PROTOCOL *FwRuntime;
///
/// Minimum address allocated by AlocatePages.
///
EFI_PHYSICAL_ADDRESS MinAllocatedAddr;
///
/// Apple hibernate image address allocated by AlocatePages.
///
EFI_PHYSICAL_ADDRESS HibernateImageAddress;
///
/// Last descriptor size obtained from GetMemoryMap.
///
UINTN MemoryMapDescriptorSize;
///
/// Amount of nested boot.efi detected.
///
UINTN AppleBootNestedCount;
///
/// TRUE if we are doing boot.efi hibernate wake.
///
BOOLEAN AppleHibernateWake;
///
/// TRUE if we are using custom KASLR slide (via boot arg).
///
BOOLEAN AppleCustomSlide;
///
/// TRUE if we are done reporting MMIO cleanup.
///
BOOLEAN ReportedMmio;
///
/// TRUE if we are waiting for performance memory allocation.
///
BOOLEAN AwaitingPerfAlloc;
} SERVICES_OVERRIDE_STATE;
/**
Apple kernel support internal state..
**/
typedef struct KERNEL_SUPPORT_STATE_ {
///
/// Assembly support internal state.
///
ASM_SUPPORT_STATE AsmState;
///
/// Kernel jump trampoline.
///
ASM_KERNEL_JUMP KernelJump;
///
/// Original kernel memory.
///
UINT8 KernelOrg[sizeof (ASM_KERNEL_JUMP)];
///
/// Custom kernel UEFI System Table.
///
EFI_PHYSICAL_ADDRESS SysTableRtArea;
///
/// Custom kernel UEFI System Table size in bytes.
///
UINTN SysTableRtAreaSize;
///
/// Physical configuration table location.
///
EFI_CONFIGURATION_TABLE *ConfigurationTable;
///
/// Virtual memory mapper context.
///
OC_VMEM_CONTEXT VmContext;
///
/// Virtual memory map containing partial memory map with runtime areas only.
/// Actual number of entries may be less than RT_DESC_ENTRY_NUM due to DescriptorSize
/// being potentially bigger than sizeof (EFI_MEMORY_DESCRIPTOR).
///
EFI_MEMORY_DESCRIPTOR VmMap[RT_DESC_ENTRY_NUM];
///
/// Virtual memory map size in bytes.
///
UINTN VmMapSize;
///
/// Virtual memory map descriptor size in bytes.
///
UINTN VmMapDescSize;
} KERNEL_SUPPORT_STATE;
/**
Apple booter KASLR slide support internal state.
**/
typedef struct SLIDE_SUPPORT_STATE_ {
///
/// Memory map analysis status determining slide usage.
///
BOOLEAN HasMemoryMapAnalysis;
///
/// TRUE if we are running on Intel Sandy or Ivy bridge.
///
BOOLEAN HasSandyOrIvy;
///
/// TRUE if CsrActiveConfig was set.
///
BOOLEAN HasCsrActiveConfig;
///
/// TRUE if BootArgs was set.
///
BOOLEAN HasBootArgs;
///
/// Read or assumed csr-arctive-config variable value.
///
UINT32 CsrActiveConfig;
///
/// Max slide value provided.
///
UINT8 ProvideMaxSlide;
///
/// Valid slides to choose from when using custom slide.
///
UINT8 ValidSlides[TOTAL_SLIDE_NUM];
///
/// Number of entries in ValidSlides.
///
UINT32 ValidSlideCount;
///
/// Apple kernel boot arguments read from boot-args variable and then
/// modified with an additional slide parameter in case custom slide is used.
///
CHAR8 BootArgs[BOOT_LINE_LENGTH];
///
/// BootArgs data size.
///
UINTN BootArgsSize;
///
/// Estimated size for kernel itself, device tree, memory map, and rt pages.
///
UINTN EstimatedKernelArea;
} SLIDE_SUPPORT_STATE;
/**
Apple Boot Compatibility context.
**/
typedef struct BOOT_COMPAT_CONTEXT_ {
///
/// Apple Coot Compatibility settings.
///
OC_ABC_SETTINGS Settings;
///
/// Runtime relocations.
///
RT_RELOC_PROTECT_DATA RtReloc;
///
/// UEFI Boot & Runtime Services original pointers.
///
UEFI_SERVICES_POINTERS ServicePtrs;
///
/// UEFI services override internal state.
///
SERVICES_OVERRIDE_STATE ServiceState;
///
/// Apple kernel support internal state.
///
KERNEL_SUPPORT_STATE KernelState;
///
/// Apple booter KASLR slide support internal state.
///
SLIDE_SUPPORT_STATE SlideSupport;
} BOOT_COMPAT_CONTEXT;
/**
Obtain Apple Boot Compatibility context. This function must only
be called from wrapped services, where passing context arguments
is not possible.
@retval Apple Boot Compatibility context (not null).
**/
BOOT_COMPAT_CONTEXT *
GetBootCompatContext (
VOID
);
/**
Install UEFI services overrides as necessary.
@param[in,out] BootCompat Boot compatibility context.
**/
VOID
InstallServiceOverrides (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat
);
/**
Prepare virtual memory management environment for later usage.
@param[in,out] BootCompat Boot compatibility context.
**/
VOID
AppleMapPrepareMemoryPool (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat
);
/**
Prepare environment for Apple UEFI bootloader. See more details inside.
@param[in,out] BootCompat Boot compatibility context.
@param[in,out] LoadedImage UEFI loaded image protocol instance.
@param[in] GetMemoryMap Unmodified GetMemoryMap pointer, optional.
**/
VOID
AppleMapPrepareBooterState (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN OUT EFI_LOADED_IMAGE *LoadedImage,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL
);
/**
Save UEFI environment state in implementation specific way.
@param[in,out] AsmState Assembly state to update, can be preserved.
@param[out] KernelJump Kernel jump trampoline to fill.
**/
VOID
AppleMapPlatformSaveState (
IN OUT ASM_SUPPORT_STATE *AsmState,
OUT ASM_KERNEL_JUMP *KernelJump
);
/**
Patch kernel entry point with KernelJump to later land in AppleMapPrepareKernelState.
@param[in,out] BootCompat Boot compatibility context.
@param[in] ImageAddress Kernel or hibernation image address.
@param[in] AppleHibernateWake TRUE when ImageAddress points to hibernation image.
**/
VOID
AppleMapPrepareKernelJump (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN UINTN ImageAddress,
IN BOOLEAN AppleHibernateWake
);
/**
Prepare memory state and perform virtual address translation.
@param[in,out] BootCompat Boot compatibility context.
@param[in] MemoryMapSize SetVirtualAddresses memory map size argument.
@param[in] DescriptorSize SetVirtualAddresses descriptor size argument.
@param[in] DescriptorVersion SetVirtualAddresses descriptor version argument.
@param[in] MemoryMap SetVirtualAddresses memory map argument.
**/
EFI_STATUS
AppleMapPrepareMemState (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN UINTN MemoryMapSize,
IN UINTN DescriptorSize,
IN UINT32 DescriptorVersion,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap
);
/**
Prepare environment for Apple kernel bootloader in boot or wake cases.
This callback arrives when boot.efi jumps to kernel.
@param[in] Args Case-specific kernel argument handle.
@param[in] ModeX64 Debug flag about kernel context type, TRUE when X64.
@retval Args must be returned with the necessary modifications if any.
**/
UINTN
EFIAPI
AppleMapPrepareKernelState (
IN UINTN Args,
IN BOOLEAN ModeX64
);
/**
Patch boot.efi to support random and passed slide values in safe mode.
@param[in,out] ImageBase Apple booter image base.
@param[in] ImageSize Apple booter image size.
**/
VOID
AppleSlideUnlockForSafeMode (
IN OUT UINT8 *ImageBase,
IN UINTN ImageSize
);
/**
Primary custom KASLR support handler. This gets called on every
UEFI RuntimeServices GetVariable call and thus is useful to
perform KASLR slide injection through boot-args.
@param[in,out] BootCompat Boot compatibility context.
@param[in] GetVariable Original UEFI GetVariable service.
@param[in] GetMemoryMap Unmodified GetMemoryMap pointer, optional.
@param[in] FilterMap GetMemoryMap result filter, optional.
@param[in] FilterMapContext FilterMap context, optional.
@param[in] VariableName GetVariable variable name argument.
@param[in] VendorGuid GetVariable vendor GUID argument.
@param[out] Attributes GetVariable attributes argument.
@param[in,out] DataSize GetVariable data size argument.
@param[out] Data GetVariable data argument.
@retval GetVariable status code.
**/
EFI_STATUS
AppleSlideGetVariable (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN EFI_GET_VARIABLE GetVariable,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL,
IN OC_MEMORY_FILTER FilterMap OPTIONAL,
IN VOID *FilterMapContext OPTIONAL,
IN CHAR16 *VariableName,
IN EFI_GUID *VendorGuid,
OUT UINT32 *Attributes OPTIONAL,
IN OUT UINTN *DataSize,
OUT VOID *Data
);
/**
Ensures that the original csr-active-config is passed to the kernel,
and removes customised slide value for security reasons.
@param[in,out] BootCompat Boot compatibility context.
@param[in,out] BootArgs Apple kernel boot arguments.
**/
VOID
AppleSlideRestore (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN OUT OC_BOOT_ARGUMENTS *BootArgs
);
#endif // BOOT_COMPAT_INTERNAL_H

View File

@ -0,0 +1,821 @@
/** @file
Copyright (C) 2018, Downlod-Fritz. All rights reserved.
Copyright (C) 2018, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "BootCompatInternal.h"
#include <Guid/AppleVariable.h>
#include <Guid/OcVariable.h>
#include <IndustryStandard/AppleHibernate.h>
#include <IndustryStandard/AppleCsrConfig.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/OcBootManagementLib.h>
#include <Library/OcCpuLib.h>
#include <Library/OcCryptoLib.h>
#include <Library/DeviceTreeLib.h>
#include <Library/MachoLib.h>
#include <Library/OcMemoryLib.h>
#include <Library/OcMiscLib.h>
#include <Library/OcRngLib.h>
#include <Library/OcStringLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
/**
Obtain estimated kernel area start and end addresses for
specified slide number.
@param[in] EstimatedKernelArea Estimated kernel area size.
@param[in] HasSandyOrIvy CPU type.
@param[in] Slide Slide number.
@param[out] StartAddr Starting address.
@param[out] EndAddr Ending address (not inclusive).
**/
STATIC
VOID
GetSlideRangeForValue (
IN UINTN EstimatedKernelArea,
IN BOOLEAN HasSandyOrIvy,
IN UINT8 Slide,
OUT UINTN *StartAddr,
OUT UINTN *EndAddr
)
{
*StartAddr = Slide * SLIDE_GRANULARITY + KERNEL_BASE_PADDR;
//
// Skip ranges used by Intel HD 2000/3000.
//
if (Slide >= SLIDE_ERRATA_NUM && HasSandyOrIvy) {
*StartAddr += SLIDE_ERRATA_SKIP_RANGE;
}
*EndAddr = *StartAddr + EstimatedKernelArea;
}
/**
Generate more or less random slide value.
@param[in] SlideSupport Slide support state.
**/
STATIC
UINT8
GenerateSlideValue (
IN SLIDE_SUPPORT_STATE *SlideSupport
)
{
UINT32 Slide;
//
// Handle 0 slide case.
//
if (SlideSupport->ValidSlideCount == 1) {
return SlideSupport->ValidSlides[0];
}
do {
DivU64x32Remainder (GetPseudoRandomNumber64 (), SlideSupport->ValidSlideCount, &Slide);
} while (SlideSupport->ValidSlides[Slide] == 0);
return SlideSupport->ValidSlides[Slide];
}
/**
Decide on whether to use custom slide based on memory map analysis.
This additionally logs the decision through standard services.
@param[in,out] SlideSupport Slide support state.
@param[in] FallbackSlide Fallback slide number with largest area.
@param[in] MaxAvailableSize Maximum available contiguous area.
@retval TRUE in case custom slide is to be used.
**/
STATIC
BOOLEAN
ShouldUseCustomSlideOffsetDecision (
IN OUT SLIDE_SUPPORT_STATE *SlideSupport,
IN UINT8 FallbackSlide,
IN UINT64 MaxAvailableSize
)
{
UINTN Index;
UINTN NumEntries;
CHAR8 SlideList[256];
CHAR8 Temp[32];
//
// All slides are available.
//
if (SlideSupport->ValidSlideCount == TOTAL_SLIDE_NUM) {
DEBUG ((
DEBUG_INFO,
"OCABC: All slides are usable! You can disable ProvideCustomSlide!\n"
));
return FALSE;
}
//
// No slides are available, fallback to largest.
//
if (SlideSupport->ValidSlideCount == 0) {
DEBUG ((
DEBUG_INFO,
"OCABC: No slide values are usable! Falling back to %u with 0x%08LX bytes!\n",
(UINT32) FallbackSlide,
MaxAvailableSize
));
SlideSupport->ValidSlides[SlideSupport->ValidSlideCount++] = (UINT8) FallbackSlide;
return TRUE;
}
//
// Not all slides are available and thus we have to pass a custom slide
// value through boot-args to boot reliably.
//
// Pretty-print valid slides as ranges.
// For example, 1, 2, 3, 4, 5 will become 1-5.
//
DEBUG ((
DEBUG_INFO,
"OCABC: Only %u/%u slide values are usable!\n",
(UINT32) SlideSupport->ValidSlideCount,
(UINT32) TOTAL_SLIDE_NUM
));
SlideList[0] = '\0';
NumEntries = 0;
for (Index = 0; Index <= SlideSupport->ValidSlideCount; ++Index) {
if (Index == 0) {
AsciiSPrint (
Temp,
sizeof (Temp),
"Valid slides - %d",
SlideSupport->ValidSlides[Index]
);
AsciiStrCatS (SlideList, sizeof (SlideList), Temp);
} else if (Index == SlideSupport->ValidSlideCount
|| SlideSupport->ValidSlides[Index - 1] + 1 != SlideSupport->ValidSlides[Index]) {
if (NumEntries == 1) {
AsciiSPrint (
Temp,
sizeof (Temp),
", %d",
SlideSupport->ValidSlides[Index - 1]
);
AsciiStrCatS (SlideList, sizeof (SlideList), Temp);
} else if (NumEntries > 1) {
AsciiSPrint (
Temp,
sizeof (Temp),
"-%d",
SlideSupport->ValidSlides[Index - 1]
);
AsciiStrCatS (SlideList, sizeof (SlideList), Temp);
}
if (Index != SlideSupport->ValidSlideCount) {
AsciiSPrint (
Temp,
sizeof (Temp),
", %d",
SlideSupport->ValidSlides[Index]
);
AsciiStrCatS (SlideList, sizeof (SlideList), Temp);
}
NumEntries = 0;
} else {
NumEntries++;
}
}
DEBUG ((DEBUG_INFO, "OCABC: %a\n", SlideList));
return TRUE;
}
/**
Return cached decision or perform memory map analysis to decide
whether to use custom slide for reliable kernel booting or not.
@param[in,out] SlideSupport Slide support state.
@param[in] GetMemoryMap Function to get current memory map for analysis. optional.
@param[in] FilterMap Function to filter returned memory map, optional.
@param[in] FilterMapContext Filter map context, optional.
@retval TRUE in case custom slide is to be used.
**/
STATIC
BOOLEAN
ShouldUseCustomSlideOffset (
IN OUT SLIDE_SUPPORT_STATE *SlideSupport,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL,
IN OC_MEMORY_FILTER FilterMap OPTIONAL,
IN VOID *FilterMapContext OPTIONAL
)
{
EFI_PHYSICAL_ADDRESS AllocatedMapPages;
UINTN MemoryMapSize;
EFI_MEMORY_DESCRIPTOR *MemoryMap;
EFI_MEMORY_DESCRIPTOR *Desc;
UINTN MapKey;
EFI_STATUS Status;
UINTN DescriptorSize;
UINT32 DescriptorVersion;
OC_CPU_GENERATION CpuGeneration;
UINTN Index;
UINTN Slide;
UINTN NumEntries;
UINT64 MaxAvailableSize;
UINT8 FallbackSlide;
BOOLEAN Supported;
UINTN StartAddr;
UINTN EndAddr;
EFI_PHYSICAL_ADDRESS DescEndAddr;
UINT64 AvailableSize;
MaxAvailableSize = 0;
FallbackSlide = 0;
if (SlideSupport->HasMemoryMapAnalysis) {
return SlideSupport->ValidSlideCount > 0
&& SlideSupport->ValidSlideCount < TOTAL_SLIDE_NUM;
}
AllocatedMapPages = BASE_4GB;
Status = OcGetCurrentMemoryMapAlloc (
&MemoryMapSize,
&MemoryMap,
&MapKey,
&DescriptorSize,
&DescriptorVersion,
GetMemoryMap,
&AllocatedMapPages
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_WARN, "OCABC: Failed to obtain memory map for KASLR - %r\n", Status));
return FALSE;
}
if (FilterMap != NULL) {
FilterMap (FilterMapContext, MemoryMapSize, MemoryMap, DescriptorSize);
}
CpuGeneration = OcCpuGetGeneration ();
SlideSupport->HasSandyOrIvy = CpuGeneration == OcCpuGenerationSandyBridge ||
CpuGeneration == OcCpuGenerationIvyBridge;
SlideSupport->EstimatedKernelArea = (UINTN) EFI_PAGES_TO_SIZE (
OcCountRuntimePages (MemoryMapSize, MemoryMap, DescriptorSize, NULL)
) + ESTIMATED_KERNEL_SIZE;
//
// At this point we have a memory map that we could use to
// determine what slide values are allowed.
//
NumEntries = MemoryMapSize / DescriptorSize;
//
// Reset valid slides to zero and find actually working ones.
//
SlideSupport->ValidSlideCount = 0;
for (Slide = 0; Slide < TOTAL_SLIDE_NUM; ++Slide) {
Desc = MemoryMap;
Supported = TRUE;
GetSlideRangeForValue (
SlideSupport->EstimatedKernelArea,
SlideSupport->HasSandyOrIvy,
(UINT8) Slide,
&StartAddr,
&EndAddr
);
AvailableSize = 0;
for (Index = 0; Index < NumEntries; ++Index) {
if (Desc->NumberOfPages == 0) {
continue;
}
DescEndAddr = LAST_DESCRIPTOR_ADDR (Desc) + 1;
if ((Desc->PhysicalStart < EndAddr) && (DescEndAddr > StartAddr)) {
//
// The memory overlaps with the slide region.
//
if (Desc->Type != EfiConventionalMemory) {
//
// The memory is unusable atm.
//
Supported = FALSE;
break;
} else {
//
// The memory will be available for the kernel.
//
AvailableSize += EFI_PAGES_TO_SIZE (Desc->NumberOfPages);
if (Desc->PhysicalStart < StartAddr) {
//
// The region starts before the slide region.
// Subtract the memory that is located before the slide region.
//
AvailableSize -= (StartAddr - Desc->PhysicalStart);
}
if (DescEndAddr > EndAddr) {
//
// The region ends after the slide region.
// Subtract the memory that is located after the slide region.
//
AvailableSize -= (DescEndAddr - EndAddr);
}
}
}
Desc = NEXT_MEMORY_DESCRIPTOR (Desc, DescriptorSize);
}
if (AvailableSize > MaxAvailableSize) {
MaxAvailableSize = AvailableSize;
FallbackSlide = (UINT8) Slide;
}
//
// Stop evalutating slides after exceeding ProvideMaxSlide, may break when
// no slides are available.
//
if (SlideSupport->ProvideMaxSlide > 0 && Slide > SlideSupport->ProvideMaxSlide) {
break;
}
if ((StartAddr + AvailableSize) != EndAddr) {
//
// The slide region is not continuous.
//
Supported = FALSE;
}
if (Supported) {
SlideSupport->ValidSlides[SlideSupport->ValidSlideCount++] = (UINT8) Slide;
}
}
//
// Okay, we are done.
//
SlideSupport->HasMemoryMapAnalysis = TRUE;
gBS->FreePages (
(EFI_PHYSICAL_ADDRESS)(UINTN) MemoryMap,
(UINTN) AllocatedMapPages
);
return ShouldUseCustomSlideOffsetDecision (
SlideSupport,
FallbackSlide,
MaxAvailableSize
);
}
/**
UEFI GetVariable override specific to csr-active-config.
See caller for more details.
@param[in,out] SlideSupport Slide support state.
@param[in] GetVariable Original UEFI GetVariable service.
@param[in] VariableName GetVariable variable name argument.
@param[in] VendorGuid GetVariable vendor GUID argument.
@param[out] Attributes GetVariable attributes argument.
@param[in,out] DataSize GetVariable data size argument.
@param[out] Data GetVariable data argument.
@retval GetVariable status code.
**/
STATIC
EFI_STATUS
GetVariableCsrActiveConfig (
IN OUT SLIDE_SUPPORT_STATE *SlideSupport,
IN EFI_GET_VARIABLE GetVariable,
IN CHAR16 *VariableName,
IN EFI_GUID *VendorGuid,
OUT UINT32 *Attributes OPTIONAL,
IN OUT UINTN *DataSize,
OUT VOID *Data
)
{
EFI_STATUS Status;
UINT32 *Config;
//
// If we were asked for the size, just return it right away.
//
if (Data == NULL || *DataSize < sizeof (UINT32)) {
*DataSize = sizeof (UINT32);
return EFI_BUFFER_TOO_SMALL;
}
Config = (UINT32 *) Data;
//
// Otherwise call the original function.
//
Status = GetVariable (VariableName, VendorGuid, Attributes, DataSize, Data);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCABC: GetVariable csr-active-config - %r\n", Status));
*Config = 0;
Status = EFI_SUCCESS;
if (Attributes != NULL) {
*Attributes =
EFI_VARIABLE_BOOTSERVICE_ACCESS |
EFI_VARIABLE_RUNTIME_ACCESS |
EFI_VARIABLE_NON_VOLATILE;
}
}
//
// We must unrestrict NVRAM from SIP or slide=X will not be supported.
//
SlideSupport->CsrActiveConfig = *Config;
SlideSupport->HasCsrActiveConfig = TRUE;
*Config |= CSR_ALLOW_UNRESTRICTED_NVRAM;
return Status;
}
/**
UEFI GetVariable override specific to boot-args.
See caller for more details.
@param[in,out] SlideSupport Slide support state.
@param[in] GetVariable Original UEFI GetVariable service.
@param[in] VariableName GetVariable variable name argument.
@param[in] VendorGuid GetVariable vendor GUID argument.
@param[out] Attributes GetVariable attributes argument.
@param[in,out] DataSize GetVariable data size argument.
@param[out] Data GetVariable data argument.
@retval GetVariable status code.
**/
STATIC
EFI_STATUS
GetVariableBootArgs (
IN OUT SLIDE_SUPPORT_STATE *SlideSupport,
IN EFI_GET_VARIABLE GetVariable,
IN CHAR16 *VariableName,
IN EFI_GUID *VendorGuid,
OUT UINT32 *Attributes OPTIONAL,
IN OUT UINTN *DataSize,
OUT VOID *Data
)
{
EFI_STATUS Status;
UINTN StoredBootArgsSize;
UINT8 Slide;
CHAR8 SlideArgument[10];
UINTN SlideArgumentLength;
StoredBootArgsSize = BOOT_LINE_LENGTH;
SlideArgumentLength = ARRAY_SIZE (SlideArgument) - 1;
if (!SlideSupport->HasBootArgs) {
Slide = GenerateSlideValue (SlideSupport);
//
// boot-args normally arrives non-null terminated.
//
Status = GetVariable (
VariableName,
VendorGuid,
Attributes,
&StoredBootArgsSize,
SlideSupport->BootArgs
);
if (EFI_ERROR (Status)) {
SlideSupport->BootArgs[0] = '\0';
}
//
// Note, the point is to always pass 3 characters to avoid side attacks on value length.
// boot.efi always reads in decimal, so 008 and 8 are equivalent.
//
AsciiSPrint (SlideArgument, ARRAY_SIZE (SlideArgument), "slide=%-03d", Slide);
if (!OcAppendArgumentToCmd (NULL, SlideSupport->BootArgs, SlideArgument, SlideArgumentLength)) {
//
// Broken boot-args, try to overwrite.
//
AsciiStrnCpyS (
SlideSupport->BootArgs,
SlideArgumentLength + 1,
SlideArgument,
SlideArgumentLength + 1
);
}
SlideSupport->BootArgsSize = AsciiStrLen (SlideSupport->BootArgs);
SlideSupport->HasBootArgs = TRUE;
}
if (Attributes) {
*Attributes =
EFI_VARIABLE_BOOTSERVICE_ACCESS |
EFI_VARIABLE_RUNTIME_ACCESS |
EFI_VARIABLE_NON_VOLATILE;
}
if (*DataSize >= SlideSupport->BootArgsSize && Data != NULL) {
CopyMem (
Data,
SlideSupport->BootArgs,
SlideSupport->BootArgsSize
);
Status = EFI_SUCCESS;
} else {
Status = EFI_BUFFER_TOO_SMALL;
}
*DataSize = SlideSupport->BootArgsSize;
return Status;
}
/**
Erases customised slide value from everywhere accessible
for security purposes.
@param[in,out] SlideSupport Slide support state.
@param[in,out] BootArgs Apple kernel boot arguments.
**/
STATIC
VOID
HideSlideFromOs (
IN OUT SLIDE_SUPPORT_STATE *SlideSupport,
IN OUT OC_BOOT_ARGUMENTS *BootArgs
)
{
EFI_STATUS Status;
DTEntry Chosen;
CHAR8 *ArgsStr;
UINT32 ArgsSize;
//
// First, there is a BootArgs entry for XNU.
//
OcRemoveArgumentFromCmd (BootArgs->CommandLine, "slide=");
//
// Second, there is a DT entry.
//
DTInit ((VOID *)(UINTN) (*BootArgs->DeviceTreeP), BootArgs->DeviceTreeLength);
Status = DTLookupEntry (NULL, "/chosen", &Chosen);
if (!EFI_ERROR (Status)) {
Status = DTGetProperty (Chosen, "boot-args", (VOID **)&ArgsStr, &ArgsSize);
if (!EFI_ERROR (Status) && ArgsSize > 0) {
OcRemoveArgumentFromCmd (ArgsStr, "slide=");
}
}
//
// Third, clean the boot args just in case.
//
SlideSupport->ValidSlideCount = 0;
SlideSupport->BootArgsSize = 0;
SecureZeroMem (SlideSupport->ValidSlides, sizeof (SlideSupport->ValidSlides));
SecureZeroMem (SlideSupport->BootArgs, sizeof (SlideSupport->BootArgs));
}
VOID
AppleSlideUnlockForSafeMode (
IN OUT UINT8 *ImageBase,
IN UINTN ImageSize
)
{
//
// boot.efi performs the following check:
// if (State & (BOOT_MODE_SAFE | BOOT_MODE_ASLR)) == (BOOT_MODE_SAFE | BOOT_MODE_ASLR)) {
// * Disable KASLR *
// }
// We do not care about the asm it will use for it, but we could assume that the constants
// will be used twice and their location will be very close to each other.
//
// BOOT_MODE_SAFE | BOOT_MODE_ASLR constant is 0x4001 in hex.
// It has not changed since its appearance, so is most likely safe to look for.
// Furthermore, since boot.efi state mask uses higher bits, it is safe to assume that
// the comparison will be at least 32-bit.
//
//
// The new way patch is a workaround for 10.13.5 and newer, where the code got finally changed.
// if (State & BOOT_MODE_SAFE) {
// ReportFeature(FEATURE_BOOT_MODE_SAFE);
// if (State & BOOT_MODE_ASLR) {
// * Disable KASLR *
// }
// }
//
//
// This is a reasonable maximum distance to expect between the instructions.
//
STATIC CONST UINTN MaxDist = 0x10;
STATIC CONST UINT8 SearchSeqNew[] = {0xF6, 0xC4, 0x40, 0x75};
STATIC CONST UINT8 SearchSeqNew2[] = {0x0F, 0xBA, 0xE0, 0x0E, 0x72};
STATIC CONST UINT8 SearchSeq[] = {0x01, 0x40, 0x00, 0x00};
UINT8 *StartOff;
UINT8 *EndOff;
UINTN FirstOff;
UINTN SecondOff;
UINTN SearchSeqNewSize;
BOOLEAN NewWay;
StartOff = ImageBase;
EndOff = StartOff + ImageSize - sizeof (SearchSeq) - MaxDist;
FirstOff = 0;
SecondOff = 0;
NewWay = FALSE;
do {
while (StartOff + FirstOff <= EndOff) {
if (StartOff + FirstOff <= EndOff - 1
&& CompareMem (StartOff + FirstOff, SearchSeqNew2, sizeof (SearchSeqNew2)) == 0) {
SearchSeqNewSize = sizeof (SearchSeqNew2);
NewWay = TRUE;
break;
} else if (CompareMem (StartOff + FirstOff, SearchSeqNew, sizeof (SearchSeqNew)) == 0) {
SearchSeqNewSize = sizeof (SearchSeqNew);
NewWay = TRUE;
break;
} else if (CompareMem (StartOff + FirstOff, SearchSeq, sizeof (SearchSeq)) == 0) {
break;
}
FirstOff++;
}
DEBUG ((
DEBUG_VERBOSE,
"OCABC: Found first %d at off %X\n",
(UINT32) NewWay,
(UINT32) FirstOff
));
if (StartOff + FirstOff > EndOff) {
DEBUG ((
DEBUG_INFO,
"OCABC: Failed to find first BOOT_MODE_SAFE | BOOT_MODE_ASLR sequence\n"
));
break;
}
if (NewWay) {
//
// Here we just patch the comparison code and the check by straight nopping.
//
DEBUG ((DEBUG_VERBOSE, "OCABC: Patching new safe mode aslr check...\n"));
SetMem (StartOff + FirstOff, SearchSeqNewSize + 1, 0x90);
return;
}
SecondOff = FirstOff + sizeof (SearchSeq);
while (
StartOff + SecondOff <= EndOff && FirstOff + MaxDist >= SecondOff &&
CompareMem (StartOff + SecondOff, SearchSeq, sizeof (SearchSeq))) {
SecondOff++;
}
DEBUG ((DEBUG_VERBOSE, "OCABC: Found second at off %X\n", (UINT32) SecondOff));
if (FirstOff + MaxDist < SecondOff) {
DEBUG ((DEBUG_VERBOSE, "OCABC: Trying next match...\n"));
SecondOff = 0;
FirstOff += sizeof (SearchSeq);
}
} while (SecondOff == 0);
if (SecondOff != 0) {
//
// Here we use 0xFFFFFFFF constant as a replacement value.
// Since the state values are contradictive (e.g. safe & single at the same time)
// We are allowed to use this instead of to simulate if (false).
//
DEBUG ((DEBUG_VERBOSE, "OCABC: Patching safe mode aslr check...\n"));
SetMem (StartOff + FirstOff, sizeof (SearchSeq), 0xFF);
SetMem (StartOff + SecondOff, sizeof (SearchSeq), 0xFF);
}
}
EFI_STATUS
AppleSlideGetVariable (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN EFI_GET_VARIABLE GetVariable,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL,
IN OC_MEMORY_FILTER FilterMap OPTIONAL,
IN VOID *FilterMapContext OPTIONAL,
IN CHAR16 *VariableName,
IN EFI_GUID *VendorGuid,
OUT UINT32 *Attributes OPTIONAL,
IN OUT UINTN *DataSize,
OUT VOID *Data
)
{
BootCompat->SlideSupport.ProvideMaxSlide = BootCompat->Settings.ProvideMaxSlide;
if (VariableName != NULL && VendorGuid != NULL && DataSize != NULL
&& CompareGuid (VendorGuid, &gEfiAppleBootGuid)) {
if (StrCmp (VariableName, L"csr-active-config") == 0) {
//
// We override csr-active-config with CSR_ALLOW_UNRESTRICTED_NVRAM bit set
// to allow one to pass a custom slide value even when SIP is on.
// This original value of csr-active-config is returned to OS at XNU boot.
// This allows SIP to be fully enabled in the operating system.
//
return GetVariableCsrActiveConfig (
&BootCompat->SlideSupport,
GetVariable,
VariableName,
VendorGuid,
Attributes,
DataSize,
Data
);
} else if (StrCmp (VariableName, L"boot-args") == 0
&& !BootCompat->ServiceState.AppleCustomSlide
&& ShouldUseCustomSlideOffset (&BootCompat->SlideSupport, GetMemoryMap, FilterMap, FilterMapContext)) {
//
// When we cannot allow some KASLR values due to used address we generate
// a random slide value among the valid options, which we we pass via boot-args.
// See ShouldUseCustomSlideOffset for more details.
//
// We delay memory map analysis as much as we can, in case boot.efi or anything else allocates
// stuff with gBS->AllocatePool and it overlaps with the kernel area.
// Overriding AllocatePool with a custom allocator does not really improve the situation,
// because on older boards allocated memory above BASE_4GB causes instant reboots, and
// on the only (so far) problematic X99 and X299 we have no free region for our pool anyway.
// In any case, the current APTIOFIX_SPECULATED_KERNEL_SIZE value appears to work reliably.
//
return GetVariableBootArgs (
&BootCompat->SlideSupport,
GetVariable,
VariableName,
VendorGuid,
Attributes,
DataSize,
Data
);
}
}
return GetVariable (VariableName, VendorGuid, Attributes, DataSize, Data);
}
VOID
AppleSlideRestore (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN OUT OC_BOOT_ARGUMENTS *BootArgs
)
{
SLIDE_SUPPORT_STATE *SlideSupport;
SlideSupport = &BootCompat->SlideSupport;
//
// Restore csr-active-config to a value it was before our slide=X alteration.
//
if (BootArgs->CsrActiveConfig != NULL && SlideSupport->HasCsrActiveConfig) {
*BootArgs->CsrActiveConfig = SlideSupport->CsrActiveConfig;
}
//
// Having slide=X values visible in the operating system defeats the purpose of KASLR.
// Since our custom implementation works by passing random KASLR slide via boot-args,
// this is especially important.
//
HideSlideFromOs (SlideSupport, BootArgs);
}

View File

@ -0,0 +1,49 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 CONTEXT_SWITCH_H
#define CONTEXT_SWITCH_H
//
// Structure definitions shared with ASM code.
// Keep these definitions in sync with ContextSwitch.nasm!
//
#pragma pack(push, 1)
/**
Assembly support state.
This state is used as an intermediate structure to hold UEFI environment
context and kernel environment context for switching between 32-bit
and 64-bit modes during booting as normal XNU boot still happens in 32-bit.
**/
typedef PACKED struct ASM_SUPPORT_STATE_ {
VOID *KernelEntry;
} ASM_SUPPORT_STATE;
/**
Assembly kernel trampoline.
This structure contains encoded assembly to jump from kernel
code to UEFI code through AsmAppleMapPlatformPrepareKernelState
intermediate handler.
**/
typedef PACKED struct ASM_KERNEL_JUMP_ {
UINT8 MovInst;
UINT32 Addr;
UINT16 CallInst;
} ASM_KERNEL_JUMP;
#pragma pack(pop)
#endif // CONTEXT_SWITCH_H

View File

@ -0,0 +1,27 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "../BootCompatInternal.h"
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
VOID
AppleMapPlatformSaveState (
IN OUT ASM_SUPPORT_STATE *AsmState,
OUT ASM_KERNEL_JUMP *KernelJump
)
{
CpuDeadLoop ();
}

View File

@ -0,0 +1,753 @@
/** @file
Copyright (C) 2013, dmazar. All rights reserved.
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "BootCompatInternal.h"
#include <Guid/OcVariable.h>
#include <IndustryStandard/AppleHibernate.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/OcBootManagementLib.h>
#include <Library/DeviceTreeLib.h>
#include <Library/MachoLib.h>
#include <Library/OcMemoryLib.h>
#include <Library/OcMiscLib.h>
#include <Library/OcStringLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
/**
Protect RT data from boot.efi relocation by marking them MemMapIO.
See more details in the function definition.
@param[in,out] RtReloc Relocation entry list to store entry types.
@param[in] MemoryMapSize Memory map size.
@param[in] DescriptorSize Memory map descriptor size.
@param[in,out] MemoryMap MemoryMap to protect entries in.
@param[in] SysTableArea Special address that should not be protected.
**/
STATIC
VOID
ProtectRtMemoryFromRelocation (
IN OUT RT_RELOC_PROTECT_DATA *RtReloc,
IN UINTN MemoryMapSize,
IN UINTN DescriptorSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
IN EFI_PHYSICAL_ADDRESS SysTableArea,
IN UINTN SysTableAreaSize
)
{
//
// We protect RT data & code from relocation by marking them MemMapIO except EFI_SYSTEM_TABLE area.
//
// This fixes NVRAM issues on some boards where access to NVRAM after boot services is possible
// only in SMM mode. RT driver passes data to SMM handler through previously negotiated buffer
// and this buffer must not be relocated.
// Explained and examined in detail by CodeRush and night199uk:
// https://web.archive.org/web/20141025080709/http://www.projectosx.com/forum/lofiversion/index.php/t3298.html
//
// Starting with APTIO V for NVRAM to work not only RT data but RT code too can no longer be moved
// due to the use of commbuffers. This, however, creates a memory protection issue, because
// XNU maps RT data as RW and code as RX, and AMI appears use global variables in some RT drivers.
// For this reason we shim (most?) affected RT services via wrapers that unset the WP bit during
// the UEFI call and set it back on return in a separate driver.
// Explained in detail by Download-Fritz and vit9696:
// http://www.insanelymac.com/forum/topic/331381-aptiomemoryfix (first 2 links in particular).
//
// EFI_SYSTEM_TABLE is passed directly through kernel boot arguments, and thus goes through static
// mapping (ml_static_ptovirt) in efi_set_tables_64 call. This mapping works as PHYS | CONST = VIRT.
// To avoid kernel accessing unmapped virtual address we let boot.efi relocate the page with
// EFI_SYSTEM_TABLE area. While technically it is possible to let the original page to be relocated,
// we pick a safer root by using a private copy.
//
// The primary downside of this approach is that boot.efi will still reserve the contiguous memory
// for runtime services after the kernel: efiRuntimeServicesPageCount pages starting from
// efiRuntimeServicesPageStart within kaddr ~ ksize range. However, unlike Macs, which have reserved
// gaps only for ACPI NVS, MemMapIO and similar regions, with this approach almost no physical memory
// in efiRuntimeServicesPageStart area is used at all. This memory is never reclaimed by XNU, which
// marks it as allocated in i386_vm_init. Expirements show that at least 85 MBs (Z170) are used for
// this process. On server systems the issue is much worse due to many devices in place.
// Ideally boot.efi should only count RT code and RT data pages, but it is not easy to change.
//
UINTN NumEntries;
UINTN Index;
EFI_MEMORY_DESCRIPTOR *Desc;
RT_RELOC_PROTECT_INFO *RelocInfo;
Desc = MemoryMap;
RtReloc->NumEntries = 0;
RelocInfo = &RtReloc->RelocInfo[0];
NumEntries = MemoryMapSize / DescriptorSize;
for (Index = 0; Index < NumEntries; ++Index) {
if ((Desc->Attribute & EFI_MEMORY_RUNTIME) != 0
&& Desc->NumberOfPages > 0
&& (Desc->Type == EfiRuntimeServicesCode || Desc->Type == EfiRuntimeServicesData)
&& !AREA_WITHIN_DESCRIPTOR (Desc, SysTableArea, SysTableAreaSize)) {
if (RtReloc->NumEntries == ARRAY_SIZE (RtReloc->RelocInfo)) {
RUNTIME_DEBUG ((
DEBUG_ERROR,
"OCABC: Cannot save mem type for entry: %Lx (type 0x%x)\n",
(UINT64) Desc->PhysicalStart,
(UINT32) Desc->Type
));
return;
}
RelocInfo->PhysicalStart = Desc->PhysicalStart;
RelocInfo->PhysicalEnd = LAST_DESCRIPTOR_ADDR (Desc);
RelocInfo->Type = Desc->Type;
Desc->Type = EfiMemoryMappedIO;
++RelocInfo;
++RtReloc->NumEntries;
}
Desc = NEXT_MEMORY_DESCRIPTOR (Desc, DescriptorSize);
}
}
/**
Copy RT flagged areas to separate memmap, define virtual to physical address mapping,
and call SetVirtualAddressMap() only with that partial memmap.
@param[in,out] KernelState Kernel support state.
@param[in] MemoryMapSize Memory map size.
@param[in] DescriptorSize Memory map descriptor size.
@param[in] DescriptorVersion Memor map descriptor version.
@param[in,out] MemoryMap Complete memory map with all entries.
@retval EFI_SUCCESS on success.
**/
STATIC
EFI_STATUS
PerformRtMemoryVirtualMapping (
IN OUT KERNEL_SUPPORT_STATE *KernelState,
IN UINTN MemoryMapSize,
IN UINTN DescriptorSize,
IN UINT32 DescriptorVersion,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap
)
{
//
// About partial memmap:
// Some UEFIs are converting pointers to virtual addresses even if they do not
// point to regions with RT flag. This means that those UEFIs are using
// Desc->VirtualStart even for non-RT regions. Linux had issues with this:
// http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=7cb00b72876ea2451eb79d468da0e8fb9134aa8a
// They are doing it Windows way now - copying RT descriptors to separate
// mem map and passing that stripped map to SetVirtualAddressMap().
// We'll do the same, although it seems that just assigning
// VirtualStart = PhysicalStart for non-RT areas also does the job.
//
// About virtual to physical mappings:
// Also adds virtual to physical address mappings for RT areas. This is needed since
// SetVirtualAddressMap() does not work on my Aptio without that. Probably because some driver
// has a bug and is trying to access new virtual addresses during the change.
// Linux and Windows are doing the same thing and problem is
// not visible there.
//
UINTN NumEntries;
UINTN Index;
EFI_MEMORY_DESCRIPTOR *Desc;
EFI_MEMORY_DESCRIPTOR *VirtualDesc;
EFI_STATUS Status;
PAGE_MAP_AND_DIRECTORY_POINTER *PageTable;
Desc = MemoryMap;
NumEntries = MemoryMapSize / DescriptorSize;
VirtualDesc = KernelState->VmMap;
KernelState->VmMapSize = 0;
KernelState->VmMapDescSize = DescriptorSize;
//
// Get current VM page table.
//
PageTable = OcGetCurrentPageTable (NULL);
for (Index = 0; Index < NumEntries; ++Index) {
//
// Legacy note. Some UEFIs end up with "reserved" area with EFI_MEMORY_RUNTIME flag set when
// Intel HD3000 or HD4000 is used. For example, on GA-H81N-D2H there is a single 1 GB descriptor:
// 000000009F800000-00000000DF9FFFFF 0000000000040200 8000000000000000
//
// All known boot.efi starting from at least 10.5.8 properly handle this flag and do not assign
// virtual addresses to reserved descriptors. However, our legacy code had a bug, and did not
// check for EfiReservedMemoryType. Therefore it replaced such entries by EfiMemoryMappedIO
// to "prevent" boot.efi relocations.
//
// The relevant discussion and the original fix can be found here:
// http://web.archive.org/web/20141111124211/http://www.projectosx.com:80/forum/lofiversion/index.php/t2428-450.html
// https://sourceforge.net/p/cloverefiboot/code/605/
//
// The correct approach is to properly handle EfiReservedMemoryType with EFI_MEMORY_RUNTIME
// attribute set, and not mess with the memory map passed to boot.efi. As done here.
//
if (Desc->Type != EfiReservedMemoryType && (Desc->Attribute & EFI_MEMORY_RUNTIME) != 0) {
//
// Check if there is enough space in virtual map.
//
if (KernelState->VmMapSize + DescriptorSize > sizeof (KernelState->VmMap)) {
RUNTIME_DEBUG ((DEBUG_ERROR, "OCABC: Too many RT entries to memory map\n"));
return EFI_OUT_OF_RESOURCES;
}
//
// Copy region with EFI_MEMORY_RUNTIME flag to virtual map.
//
CopyMem (VirtualDesc, Desc, DescriptorSize);
//
// Define virtual to physical mapping.
//
Status = VmMapVirtualPages (
&KernelState->VmContext,
PageTable,
Desc->VirtualStart,
Desc->NumberOfPages,
Desc->PhysicalStart
);
if (EFI_ERROR (Status)) {
RUNTIME_DEBUG ((DEBUG_ERROR, "OCABC: RT mapping failure - %r\n", Status));
return EFI_OUT_OF_RESOURCES;
}
//
// Proceed to next virtual map slot.
//
VirtualDesc = NEXT_MEMORY_DESCRIPTOR (VirtualDesc, DescriptorSize);
KernelState->VmMapSize += DescriptorSize;
}
//
// Proceed to next original map slot.
//
Desc = NEXT_MEMORY_DESCRIPTOR (Desc, DescriptorSize);
}
VmFlushCaches ();
Status = gRT->SetVirtualAddressMap (
KernelState->VmMapSize,
DescriptorSize,
DescriptorVersion,
KernelState->VmMap
);
return Status;
}
/**
Revert RT data protected types to let XNU kernel kernel properly map data.
@param[in] RtReloc Relocated entry list with entry types.
@param[in] MemoryMapSize Memory map size.
@param[in] DescriptorSize Memory map descriptor size.
@param[in,out] MemoryMap MemoryMap to restore protected entries in.
**/
STATIC
VOID
RestoreProtectedRtMemoryTypes (
IN RT_RELOC_PROTECT_DATA *RtReloc,
IN UINTN MemoryMapSize,
IN UINTN DescriptorSize,
IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap
)
{
UINTN Index;
UINTN Index2;
UINTN NumEntriesLeft;
UINTN NumEntries;
EFI_PHYSICAL_ADDRESS PhysicalStart;
EFI_PHYSICAL_ADDRESS PhysicalEnd;
EFI_MEMORY_DESCRIPTOR *Desc;
NumEntriesLeft = RtReloc->NumEntries;
NumEntries = MemoryMapSize / DescriptorSize;
Desc = MemoryMap;
for (Index = 0; Index < NumEntries && NumEntriesLeft > 0; ++Index) {
PhysicalStart = Desc->PhysicalStart;
PhysicalEnd = LAST_DESCRIPTOR_ADDR (Desc);
for (Index2 = 0; Index2 < RtReloc->NumEntries; ++Index2) {
//
// PhysicalStart match is enough, but just in case.
// Select firmwares, like Lenovo ThinkPad X240, have insane reserved areas.
// For example 0000000000000000-FFFFFFFFFFFFFFFF 0000000000000000 0000000000000000.
// Any fuzzy matching is prone to errors, so just do exact comparison.
//
if (PhysicalStart == RtReloc->RelocInfo[Index2].PhysicalStart
&& PhysicalEnd == RtReloc->RelocInfo[Index2].PhysicalEnd) {
Desc->Type = RtReloc->RelocInfo[Index2].Type;
--NumEntriesLeft;
break;
}
}
Desc = NEXT_MEMORY_DESCRIPTOR (Desc, DescriptorSize);
}
if (NumEntriesLeft > 0) {
RUNTIME_DEBUG ((
DEBUG_ERROR,
"OCABC: Failed to restore %u entries out of %u\n",
(UINT32) NumEntriesLeft,
(UINT32) RtReloc->NumEntries
));
}
}
/**
Prepare environment for normal booting. Called when boot.efi jumps to kernel.
@param[in,out] BootCompat Boot compatibility context.
@param[in,out] BootArgs Apple kernel boot arguments.
**/
STATIC
VOID
AppleMapPrepareForBooting (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN OUT VOID *BootArgs
)
{
EFI_STATUS Status;
DTEntry Chosen;
CHAR8 *ArgsStr;
UINT32 ArgsSize;
OC_BOOT_ARGUMENTS BA;
UINTN MemoryMapSize;
EFI_MEMORY_DESCRIPTOR *MemoryMap;
UINTN DescriptorSize;
OcParseBootArgs (&BA, BootArgs);
if (BootCompat->Settings.ProvideCustomSlide) {
//
// Restore the variables we tampered with to support custom slides.
//
AppleSlideRestore (BootCompat, &BA);
}
if (BootCompat->Settings.DisableSingleUser) {
//
// First, there is a BootArgs entry for XNU.
//
OcRemoveArgumentFromCmd (BA.CommandLine, "-s");
//
// Second, there is a DT entry.
//
DTInit ((VOID *)(UINTN) *BA.DeviceTreeP, BA.DeviceTreeLength);
Status = DTLookupEntry (NULL, "/chosen", &Chosen);
if (!EFI_ERROR (Status)) {
Status = DTGetProperty (Chosen, "boot-args", (VOID **) &ArgsStr, &ArgsSize);
if (!EFI_ERROR (Status) && ArgsSize > 0) {
OcRemoveArgumentFromCmd (ArgsStr, "-s");
}
}
}
if (BootCompat->Settings.AvoidRuntimeDefrag) {
MemoryMapSize = *BA.MemoryMapSize;
MemoryMap = (EFI_MEMORY_DESCRIPTOR *)(UINTN) (*BA.MemoryMap);
DescriptorSize = *BA.MemoryMapDescriptorSize;
//
// We must restore EfiRuntimeServicesCode memory area types, because otherwise
// RuntimeServices won't be mapped.
//
RestoreProtectedRtMemoryTypes (
&BootCompat->RtReloc,
MemoryMapSize,
DescriptorSize,
MemoryMap
);
//
// On native Macs due to EfiBoot defragmentation it is guaranteed that
// VADDR % BASE_1GB == PADDR. macOS 11 started to rely on this in
// acpi_count_enabled_logical_processors, which needs to access MADT (APIC)
// ACPI table, and does that through ConfigurationTables.
//
// The simplest approach is to just copy the table, so that it is accessible
// at both actual mapping and 1:1 defragmented mapping. This should be safe,
// as the memory for 1:1 defragmented mapping is reserved by EfiBoot in the
// first place and is otherwise stolen anyway.
//
if (BootCompat->KernelState.ConfigurationTable != NULL) {
CopyMem (
(VOID*) ((UINTN) BA.SystemTable->ConfigurationTable & (BASE_1GB - 1)),
BootCompat->KernelState.ConfigurationTable,
sizeof (*BootCompat->KernelState.ConfigurationTable) * BA.SystemTable->NumberOfTableEntries
);
}
}
}
/**
Prepare environment for hibernate wake. Called when boot.efi jumps to kernel.
@param[in,out] BootCompat Boot compatibility context.
@param[in,out] ImageHeaderPage Apple hibernate image page number.
**/
STATIC
VOID
AppleMapPrepareForHibernateWake (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN UINTN ImageHeaderPage
)
{
IOHibernateImageHeader *ImageHeader;
IOHibernateHandoff *Handoff;
ImageHeader = (IOHibernateImageHeader *) EFI_PAGES_TO_SIZE (ImageHeaderPage);
//
// Legacy note. In legacy implementations systemTableOffset was unconditionally overwritten
// with a wrong address due to ImageHeader->runtimePages not being converted from pages to bytes.
// Fortunately systemTableOffset was unused when kIOHibernateHandoffTypeMemoryMap is unspecified.
// systemTableOffset is calculated properly by boot.efi itself starting from 10.6.8 at least,
// and thus this assignment was useless in the first place.
//
//
// At this step we have two routes.
//
// 1. Remove newly generated memory map from hibernate image to let XNU use the original mapping.
// This is known to work well on most systems primarily because Windows requires UEFI firmwares
// to preserve physical memory consistency at S4 wake. "On a UEFI platform, firmware runtime memory
// must be consistent across S4 sleep state transitions, in both size and location.", see:
// https://docs.microsoft.com/en-us/windows-hardware/design/device-experiences/oem-uefi#hibernation-state-s4-transition-requirements
// 2. Recover memory map just as we do for normal booting. This was causing issues on some firmwares,
// which provided very strange memory maps after S4 wake. In other cases this should not immediately
// break things. XNU will entirely remove efiRuntimeServicesPageStart/efiRuntimeServicesPageSize
// mapping, and our new memory map entries will unconditionally overwrite previous ones. In case
// no physical memory changes happened this should work fine.
//
Handoff = (IOHibernateHandoff *) EFI_PAGES_TO_SIZE ((UINTN) ImageHeader->handoffPages);
while (Handoff->type != kIOHibernateHandoffTypeEnd) {
if (Handoff->type == kIOHibernateHandoffTypeMemoryMap) {
if (BootCompat->Settings.DiscardHibernateMap) {
//
// Route 1. Discard the new memory map here, and let XNU use what it had.
// It is unknown whether there still are any firmwares that need this.
//
Handoff->type = kIOHibernateHandoffType;
} else {
//
// Route 2. Recovery memory protection types just as normal boot.
//
if (BootCompat->KernelState.VmMapDescSize == 0) {
RUNTIME_DEBUG ((DEBUG_ERROR, "OCABC: Saved descriptor size cannot be 0\n"));
return;
}
if (BootCompat->Settings.AvoidRuntimeDefrag) {
//
// I think we should not be there, but ideally all quirks are relatively independent.
//
RestoreProtectedRtMemoryTypes (
&BootCompat->RtReloc,
Handoff->bytecount,
BootCompat->KernelState.VmMapDescSize,
(EFI_MEMORY_DESCRIPTOR *)(UINTN) Handoff->data
);
}
}
break;
}
Handoff = (IOHibernateHandoff *) ((UINTN) Handoff + sizeof(Handoff) + Handoff->bytecount);
}
}
VOID
AppleMapPrepareMemoryPool (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat
)
{
EFI_STATUS Status;
if (!BootCompat->Settings.SetupVirtualMap
|| BootCompat->KernelState.VmContext.MemoryPool != NULL) {
return;
}
Status = VmAllocateMemoryPool (
&BootCompat->KernelState.VmContext,
OC_DEFAULT_VMEM_PAGE_COUNT,
BootCompat->ServicePtrs.GetMemoryMap
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "OCABC: Memory pool allocation failure - %r\n", Status));
}
}
VOID
AppleMapPrepareBooterState (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN OUT EFI_LOADED_IMAGE *LoadedImage,
IN EFI_GET_MEMORY_MAP GetMemoryMap OPTIONAL
)
{
EFI_STATUS Status;
//
// Allocate memory pool if needed.
//
AppleMapPrepareMemoryPool (
BootCompat
);
//
// This function may be called twice, do not redo in this case.
//
AppleMapPlatformSaveState (
&BootCompat->KernelState.AsmState,
&BootCompat->KernelState.KernelJump
);
if (BootCompat->Settings.AvoidRuntimeDefrag) {
if (BootCompat->KernelState.SysTableRtArea == 0) {
//
// Allocate RT data pages for copy of UEFI system table for kernel.
// This one also has to be 32-bit due to XNU BootArgs structure.
// The reason for this allocation to be required is because XNU uses static
// mapping for directly passed pointers (see ProtectRtMemoryFromRelocation).
//
BootCompat->KernelState.SysTableRtArea = BASE_4GB;
BootCompat->KernelState.SysTableRtAreaSize = gST->Hdr.HeaderSize;
Status = OcAllocatePagesFromTop (
EfiRuntimeServicesData,
EFI_SIZE_TO_PAGES (gST->Hdr.HeaderSize),
&BootCompat->KernelState.SysTableRtArea,
GetMemoryMap,
NULL
);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"OCABC: Failed to allocate system table memory - %r\n",
Status
));
BootCompat->KernelState.SysTableRtArea = 0;
return;
}
//
// Copy UEFI system table to the new location.
//
CopyMem (
(VOID *)(UINTN) BootCompat->KernelState.SysTableRtArea,
gST,
gST->Hdr.HeaderSize
);
//
// Remember physical configuration table location.
//
BootCompat->KernelState.ConfigurationTable = gST->ConfigurationTable;
}
//
// Assign loaded image with custom system table.
//
LoadedImage->SystemTable =
(EFI_SYSTEM_TABLE *)(UINTN) BootCompat->KernelState.SysTableRtArea;
}
}
VOID
AppleMapPrepareKernelJump (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN UINTN ImageAddress,
IN BOOLEAN AppleHibernateWake
)
{
UINT64 KernelEntryVaddr;
UINT32 KernelEntry;
IOHibernateImageHeader *ImageHeader;
//
// There is no reason to patch the kernel when we do not need it.
//
if (!BootCompat->Settings.AvoidRuntimeDefrag && !BootCompat->Settings.DiscardHibernateMap) {
return;
}
//
// Check whether we have image address and abort if not.
//
if (ImageAddress == 0) {
RUNTIME_DEBUG ((DEBUG_ERROR, "OCABC: Failed to find image address, hibernate %d\n", AppleHibernateWake));
return;
}
if (!AppleHibernateWake) {
//
// ImageAddress points to the first kernel segment, __HIB.
// Kernel image header is located in __TEXT, which follows __HIB.
//
ImageAddress += KERNEL_BASE_PADDR;
//
// Cut higher virtual address bits.
//
KernelEntryVaddr = MachoRuntimeGetEntryAddress (
(VOID*) ImageAddress
);
if (KernelEntryVaddr == 0) {
RUNTIME_DEBUG ((DEBUG_ERROR, "OCABC: Kernel entry point was not found!"));
return;
}
//
// Perform virtual to physical address conversion by subtracting __TEXT base
// and adding current physical kernel location.
//
KernelEntry = (UINT32) (KernelEntryVaddr - KERNEL_TEXT_VADDR + ImageAddress);
} else {
//
// Read kernel entry from hibernation image and patch it with jump.
// At this stage HIB section is not yet copied from sleep image to it's
// proper memory destination. so we'll patch entry point in sleep image.
// Note the virtual -> physical conversion through truncation.
//
ImageHeader = (IOHibernateImageHeader *) ImageAddress;
KernelEntry = ((UINT32)(UINTN) &ImageHeader->fileExtentMap[0])
+ ImageHeader->fileExtentMapSize + ImageHeader->restore1CodeOffset;
}
//
// Save original kernel entry code.
//
CopyMem (
&BootCompat->KernelState.KernelOrg[0],
(VOID *)(UINTN) KernelEntry,
sizeof (BootCompat->KernelState.KernelOrg)
);
//
// Copy kernel jump code to kernel entry address.
//
CopyMem (
(VOID *)(UINTN) KernelEntry,
&BootCompat->KernelState.KernelJump,
sizeof (BootCompat->KernelState.KernelJump)
);
}
EFI_STATUS
AppleMapPrepareMemState (
IN OUT BOOT_COMPAT_CONTEXT *BootCompat,
IN UINTN MemoryMapSize,
IN UINTN DescriptorSize,
IN UINT32 DescriptorVersion,
IN EFI_MEMORY_DESCRIPTOR *MemoryMap
)
{
EFI_STATUS Status;
//
// Protect RT areas from relocation by marking then MemMapIO.
//
if (BootCompat->Settings.AvoidRuntimeDefrag) {
ProtectRtMemoryFromRelocation (
&BootCompat->RtReloc,
MemoryMapSize,
DescriptorSize,
MemoryMap,
BootCompat->KernelState.SysTableRtArea,
BootCompat->KernelState.SysTableRtAreaSize
);
}
//
// Virtualize RT services with all needed fixes.
//
if (BootCompat->Settings.SetupVirtualMap) {
Status = PerformRtMemoryVirtualMapping (
&BootCompat->KernelState,
MemoryMapSize,
DescriptorSize,
DescriptorVersion,
MemoryMap
);
} else {
Status = gRT->SetVirtualAddressMap (
MemoryMapSize,
DescriptorSize,
DescriptorVersion,
MemoryMap
);
}
//
// Copy now virtualized UEFI system table for boot.efi to hand it to the kernel.
//
if (BootCompat->Settings.AvoidRuntimeDefrag) {
CopyMem (
(VOID *)(UINTN) BootCompat->KernelState.SysTableRtArea,
gST,
gST->Hdr.HeaderSize
);
}
return Status;
}
UINTN
EFIAPI
AppleMapPrepareKernelState (
IN UINTN Args,
IN BOOLEAN ModeX64
)
{
BOOT_COMPAT_CONTEXT *BootCompatContext;
BootCompatContext = GetBootCompatContext ();
if (BootCompatContext->ServiceState.AppleHibernateWake) {
AppleMapPrepareForHibernateWake (
BootCompatContext,
Args
);
} else {
AppleMapPrepareForBooting (
BootCompatContext,
(VOID *) Args
);
}
//
// Restore original kernel entry code.
//
CopyMem (
BootCompatContext->KernelState.AsmState.KernelEntry,
&BootCompatContext->KernelState.KernelOrg[0],
sizeof (BootCompatContext->KernelState.KernelOrg)
);
return Args;
}

View File

@ -0,0 +1,160 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/OcDebugLogLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAfterBootCompatLib.h>
#include <Library/OcDevicePathLib.h>
#include <Library/OcMiscLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Protocol/OcAfterBootCompat.h>
#include "BootCompatInternal.h"
/**
Apple Boot Compatibility protocol instance. Its GUID matches
with legacy AptioMemoryFix protocol, allowing us to avoid
conflicts between the two.
**/
STATIC OC_AFTER_BOOT_COMPAT_PROTOCOL mOcAfterBootCompatProtocol = {
OC_AFTER_BOOT_COMPAT_PROTOCOL_REVISION
};
/**
Apple Boot Compatibility context. This context is used throughout
the library. Must be accessed through GetBootCompatContext ().
**/
STATIC BOOT_COMPAT_CONTEXT mOcAfterBootCompatContext;
STATIC
EFI_STATUS
InstallAbcProtocol (
VOID
)
{
EFI_STATUS Status;
VOID *Interface;
EFI_HANDLE Handle;
Status = gBS->LocateProtocol (
&gOcAfterBootCompatProtocolGuid,
NULL,
&Interface
);
if (!EFI_ERROR (Status)) {
//
// Ensure we do not run with AptioMemoryFix.
// It also checks for attempts to install this protocol twice.
//
DEBUG ((DEBUG_WARN, "OCABC: Found legacy AptioMemoryFix driver!\n"));
return EFI_ALREADY_STARTED;
}
Handle = NULL;
Status = gBS->InstallMultipleProtocolInterfaces (
&Handle,
&gOcAfterBootCompatProtocolGuid,
&mOcAfterBootCompatProtocol,
NULL
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_WARN, "OCABC: protocol install failure - %r\n", Status));
return Status;
}
return EFI_SUCCESS;
}
BOOT_COMPAT_CONTEXT *
GetBootCompatContext (
VOID
)
{
return &mOcAfterBootCompatContext;
}
EFI_STATUS
OcAbcInitialize (
IN OC_ABC_SETTINGS *Settings
)
{
EFI_STATUS Status;
BOOT_COMPAT_CONTEXT *BootCompat;
UINTN LowMemory;
UINTN TotalMemory;
Status = InstallAbcProtocol ();
if (EFI_ERROR (Status)) {
return Status;
}
DEBUG ((
DEBUG_INFO,
"OCABC: RTDFRG %d DEVMMIO %d NOSU %d NOVRWR %d NOSB %d NOHBMAP %d SMSLIDE %d WRUNPROT %d\n",
Settings->AvoidRuntimeDefrag,
Settings->DevirtualiseMmio,
Settings->DisableSingleUser,
Settings->DisableVariableWrite,
Settings->ProtectSecureBoot,
Settings->DiscardHibernateMap,
Settings->EnableSafeModeSlide,
Settings->EnableWriteUnprotector
));
DEBUG ((
DEBUG_INFO,
"OCABC: FEXITBS %d PRMRG %d CSLIDE %d MSLIDE %d PRSRV %d RBMAP %d VMAP %d APPLOS %d RTPERMS %d\n",
Settings->ForceExitBootServices,
Settings->ProtectMemoryRegions,
Settings->ProvideCustomSlide,
Settings->ProvideMaxSlide,
Settings->ProtectUefiServices,
Settings->RebuildAppleMemoryMap,
Settings->SetupVirtualMap,
Settings->SignalAppleOS,
Settings->SyncRuntimePermissions
));
DEBUG_CODE_BEGIN ();
TotalMemory = OcCountFreePages (&LowMemory);
DEBUG ((
DEBUG_INFO,
"OCABC: Firmware has %Lu free pages (%Lu in lower 4 GB)\n",
(UINT64) TotalMemory,
(UINT64) LowMemory
));
DEBUG_CODE_END ();
BootCompat = GetBootCompatContext ();
CopyMem (
&BootCompat->Settings,
Settings,
sizeof (BootCompat->Settings)
);
InstallServiceOverrides (BootCompat);
return EFI_SUCCESS;
}

View File

@ -0,0 +1,78 @@
## @file
#
# Component description file for the library producing the Apple Device property protocol.
#
# Copyright (C) 2019, vit9696. All rights reserved.<BR>
#
# All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# 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 = OcAfterBootCompatLib
FILE_GUID = A393F7CF-3966-4C7E-8763-3DD991681C9B
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = OcAfterBootCompatLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_SMM_DRIVER
#
# The following information is for reference only and not required by the build tools.
#
# VALID_ARCHITECTURES = IA32 X64 IPF EBC
#
[Sources]
BootCompatInternal.h
CustomSlide.c
KernelSupport.c
OcAfterBootCompatLib.c
ServiceOverrides.c
# All headers should go to [Sources], this sounds like a bug in EDK II Build System.
Ia32/ContextSwitch.h
X64/ContextSwitch.h
[Sources.Ia32]
Ia32/ContextSwitchSupport.c
[Sources.X64]
X64/ContextSwitch.nasm
X64/ContextSwitchSupport.c
[Packages]
CloverPkg.dec
MdePkg/MdePkg.dec
# OpenCorePkg/OpenCorePkg.dec
CloverEFI/UefiCpuPkg/UefiCpuPkg.dec
[Guids]
gEfiAppleBootGuid ## SOMETIMES_CONSUMES
[Protocols]
gOcAfterBootCompatProtocolGuid ## PRODUCES
gOcFirmwareRuntimeProtocolGuid ## SOMETIMES_CONSUMES
[LibraryClasses]
BaseLib
BaseMemoryLib
DebugLib
DevicePathLib
MemoryAllocationLib
PrintLib
UefiBootServicesTableLib
UefiRuntimeServicesTableLib
OcCpuLib
OcCryptoLib
DeviceTreeLib
OcGuardLib
OcMemoryLib
OcOSInfoLib
OcRngLib

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,95 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 CONTEXT_SWITCH_H
#define CONTEXT_SWITCH_H
//
// Structure definitions shared with ASM code.
// Keep these definitions in sync with ContextSwitch.nasm!
//
#pragma pack(push, 1)
/**
Assembly support state.
This state is used as an intermediate structure to hold UEFI environment
context and kernel environment context for switching between 32-bit
and 64-bit modes during booting as normal XNU boot still happens in 32-bit.
**/
typedef PACKED struct ASM_SUPPORT_STATE_ {
UINT64 SavedGDTR;
UINT16 SavedGDTRLimit;
UINT64 SavedIDTR;
UINT16 SavedIDTRLimit;
UINT64 SavedCR3;
UINT16 SavedCS;
UINT16 SavedDS;
UINT16 SavedES;
UINT16 SavedFS;
UINT16 SavedGS;
UINT64 SavedGDTR32;
UINT16 SavedGDTR32Limit;
UINT64 SavedIDTR32;
UINT16 SavedIDTR32Limit;
UINT16 SavedCS32;
UINT16 SavedDS32;
UINT16 SavedES32;
UINT16 SavedFS32;
UINT16 SavedGS32;
VOID *KernelEntry;
} ASM_SUPPORT_STATE;
/**
Assembly kernel trampoline.
This structure contains encoded assembly to jump from kernel
code to UEFI code through AsmAppleMapPlatformPrepareKernelState
intermediate handler.
**/
typedef PACKED struct ASM_KERNEL_JUMP_ {
UINT8 MovInst;
UINT32 Addr;
UINT16 CallInst;
} ASM_KERNEL_JUMP;
#pragma pack(pop)
/**
Assembly interface to save UEFI environment state in specific way.
@param[in,out] AsmState Assembly state to update, can be preserved.
**/
VOID
EFIAPI
AsmAppleMapPlatformSaveState (
IN OUT ASM_SUPPORT_STATE *AsmState
);
/**
Assembly interface for backjump from kernel code.
Takes kernel arguments through RAX or EAX register.
**/
VOID
AsmAppleMapPlatformPrepareKernelState (
);
/**
Assembly global variable containing ASM_SUPPORT_STATE address.
Must fit into lower 32-bit bytes due to 32-bit .
**/
extern UINT32 gOcAbcAsmStateAddr32;
#endif // CONTEXT_SWITCH_H

View File

@ -0,0 +1,391 @@
;------------------------------------------------------------------------------
; @file
; Copyright (C) 2013, dmazar. All rights reserved.
; Copyright (C) 2019, vit9696. All rights reserved.
;
; All rights reserved.
;
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;------------------------------------------------------------------------------
BITS 64
DEFAULT REL
;------------------------------------------------------------------------------
; Structure definitions shared with C code.
; Keep these definitions in sync with ContextSwitch.h!
;------------------------------------------------------------------------------
struc ASM_SUPPORT_STATE
;------------------------------------------------------------------------------
; 64-bit state
;------------------------------------------------------------------------------
.SavedGDTR resq 1
.SavedGDTRLimit resw 1
.SavedIDTR resq 1
.SavedIDTRLimit resw 1
.SavedCR3 resq 1
.SavedCS resw 1
.SavedDS resw 1
.SavedES resw 1
.SavedFS resw 1
.SavedGS resw 1
;------------------------------------------------------------------------------
; 32-bit state
;------------------------------------------------------------------------------
.SavedGDTR32 resq 1
.SavedGDTR32Limit resw 1
.SavedIDTR32 resq 1
.SavedIDTR32Limit resw 1
.SavedCS32 resw 1
.SavedDS32 resw 1
.SavedES32 resw 1
.SavedFS32 resw 1
.SavedGS32 resw 1
;------------------------------------------------------------------------------
; Kernel entry address.
;------------------------------------------------------------------------------
.KernelEntry resq 1
.Size:
endstruc
struc ASM_KERNEL_JUMP
.MovInst resb 1
.Addr resd 1
.CallInst resw 1
.Size:
endstruc
;------------------------------------------------------------------------------
; C callback method called on jump to kernel after boot.efi finishes.
;------------------------------------------------------------------------------
extern ASM_PFX(AppleMapPrepareKernelState)
SECTION .text
;------------------------------------------------------------------------------
; VOID
; EFIAPI
; AsmAppleMapPlatformSaveState (
; OUT ASM_SUPPORT_STATE *AsmState
; );
;------------------------------------------------------------------------------
align 8
global ASM_PFX(AsmAppleMapPlatformSaveState)
ASM_PFX(AsmAppleMapPlatformSaveState):
BITS 64
sgdt [rcx + ASM_SUPPORT_STATE.SavedGDTR]
sidt [rcx + ASM_SUPPORT_STATE.SavedIDTR]
mov rax, cr3
mov [rcx + ASM_SUPPORT_STATE.SavedCR3], rax
mov word [rcx + ASM_SUPPORT_STATE.SavedCS], cs
mov word [rcx + ASM_SUPPORT_STATE.SavedDS], ds
mov word [rcx + ASM_SUPPORT_STATE.SavedES], es
mov word [rcx + ASM_SUPPORT_STATE.SavedFS], fs
mov word [rcx + ASM_SUPPORT_STATE.SavedGS], gs
ret
;------------------------------------------------------------------------------
; Apple kernel starts through call gate, an assembly structure allocated in
; 32-bit high memory, that transitions to 32-bit mode and then calls the kernel
; with 32-bit GDT and UEFI stack.
;
; KernelCallGate:
; lea rax, StartKernelIn32Bit
; mov cs:gKernelBooter32, eax
; lea rax, gKernelGdtTable
; mov cs:gKernelGdtBase, rax
; lgdt fword ptr cs:gKernelGdtLimit
; mov ax, 10h
; mov ds, ax
; mov es, ax
; mov gs, ax
; mov fs, ax
; lea rax, gKernelBooter32
; jmp fword ptr [rax]
;
; StartKernelIn32Bit:
; mov rax, cr0
; btr eax, 1Fh
; mov cr0, rax
; mov ebx, ecx ; ebx = boot-args
; mov edi, edx
; ; Disable long mode
; mov ecx, 0C0000080h ; EFER MSR number.
; rdmsr
; btr eax, 8 ; Set LME=0.
; wrmsr
; jmp short SwitchTo32Bit
;
; SwitchTo32Bit:
; mov eax, ebx
; jmp rdi ; Jump to kernel
; hlt
; ret
;
; gKernelBooter32:
; dd 0
; dw 8 ; New CS value
; gKernelGdtLimit: ; IA32_DESCRIPTOR
; dw 18h
; gKernelGdtBase:
; dq 0
; gKernelGdtTable: ; Array of IA32_GDT.
; dw 0 ; [0] = LimitLow
; dw 0 ; [0] = BaseLow
; db 0 ; [0] = BaseMid
; dw 0 ; [0] = Flags
; db 0 ; [0] = BaseHigh
; dw 0FFFFh ; [1] = LimitLow
; dw 0 ; [1] = BaseLow
; db 0 ; [1] = BaseMid
; dw 0CF9Eh ; [1] - Flags
; db 0 ; [1] = BaseHigh
; dw 0FFFFh ; [2] = LimitLow
; dw 0 ; [2] = BaseLow
; db 0 ; [2] = BaseMid
; dw 0CF92h ; [2] = Flags
; db 0 ; [2] = BaseHigh
;------------------------------------------------------------------------------
;------------------------------------------------------------------------------
; Long (far) return.
; retfq (lretq) - 64-bit encoding 48 CB
; retf (lret) - 32-bit encoding CB
;------------------------------------------------------------------------------
LONG_RET64:
db 048h
LONG_RET32:
db 0CBh
;------------------------------------------------------------------------------
; AsmAppleMapPlatformPrepareKernelState
;
; Callback from boot.efi - this is where we jump when boot.efi jumps to kernel.
; eax register contains boot arguments for the kernel.
;
; - test if we are in 32 bit or in 64 bit
; - if 64 bit, then jump to AsmJumpFromKernel64
; - else just continue with AsmJumpFromKernel32
;------------------------------------------------------------------------------
global ASM_PFX(AsmAppleMapPlatformPrepareKernelState)
ASM_PFX(AsmAppleMapPlatformPrepareKernelState):
BITS 32
push eax ; save bootArgs pointer to stack
mov dword ecx, 0C0000080h ; EFER MSR number.
rdmsr ; Read EFER.
bt eax, 8 ; Check if LME==1 -> CF=1.
pop eax
jc AsmJumpFromKernel64 ; LME==1 -> jump to 64 bit code
; otherwise, continue with AsmJumpFromKernel32
; Above 32-bit code must give the opcodes equivalent to following in 64-bit.
;BITS 64
; push rax ; save bootArgs pointer to stack
; mov ecx, C0000080h ; EFER MSR number.
; rdmsr ; Read EFER.
; bt eax, 8 ; Check if LME==1 -> CF=1.
; pop rax
; jc AsmJumpFromKernel64 ; LME==1 -> jump to 64 bit code
;------------------------------------------------------------------------------
; AsmJumpFromKernel32
;
; Callback from boot.efi in 32 bit mode.
;------------------------------------------------------------------------------
AsmJumpFromKernel32:
BITS 32
; Save bootArgs pointer to edi.
mov edi, eax
; Load ebx with AsmState - we'll access our saved data with it.
db 0BBh ; mov ebx, OFFSET DataBase
;------------------------------------------------------------------------------
; 32-bit pointer to AsmState used to reduce global variable access.
; Defined here becuase 32-bit mode does not support relative addressing.
; As both jumps can happen from 64-bit kernel, the address must fit in 4 bytes.
;------------------------------------------------------------------------------
global ASM_PFX(gOcAbcAsmStateAddr32)
ASM_PFX(gOcAbcAsmStateAddr32):
dd 0
; Store kernel entery point prior to hunk code.
pop ecx
sub ecx, ASM_KERNEL_JUMP.Size
mov dword [ebx + ASM_SUPPORT_STATE.KernelEntry], ecx
; Store 32-bit state to be able to recover it later.
sgdt [ebx + ASM_SUPPORT_STATE.SavedGDTR32]
sidt [ebx + ASM_SUPPORT_STATE.SavedIDTR32]
mov word [ebx + ASM_SUPPORT_STATE.SavedCS32], cs
mov word [ebx + ASM_SUPPORT_STATE.SavedDS32], ds
mov word [ebx + ASM_SUPPORT_STATE.SavedES32], es
mov word [ebx + ASM_SUPPORT_STATE.SavedFS32], fs
mov word [ebx + ASM_SUPPORT_STATE.SavedGS32], gs
;
; Transition to 64-bit mode...
; boot.efi disables interrupts for us, so we are safe.
;
; Load saved UEFI GDT and IDT.
; They will become active after code segment is changed in long jump.
lgdt [ebx + ASM_SUPPORT_STATE.SavedGDTR]
lidt [ebx + ASM_SUPPORT_STATE.SavedIDTR]
; Enable the 64-bit page-translation-table entries by setting CR4.PAE=1.
mov eax, cr4
bts eax, 5
mov cr4, eax
; Set the long-mode page tables by reusing saved UEFI tables.
mov eax, dword [ebx + ASM_SUPPORT_STATE.SavedCR3]
mov cr3, eax
; Enable long mode (set EFER.LME=1).
mov ecx, 0C0000080h ; EFER MSR number.
rdmsr ; Read EFER.
bts eax, 8 ; Set LME=1.
wrmsr ; Write EFER.
; Enable paging to activate long mode (set CR0.PG=1).
mov eax, cr0 ; Read CR0.
bts eax, 31 ; Set PG=1.
mov cr0, eax ; Write CR0.
; Jump to the 64-bit code segment.
mov ax, word [ebx + ASM_SUPPORT_STATE.SavedCS]
push eax
call LONG_RET32
BITS 64
;
; Done transitioning to 64-bit code.
;
; Set other segment selectors. In most firmwares all segment registers but cs
; point to the same selector, but we must not rely on it.
mov ax, word [rbx + ASM_SUPPORT_STATE.SavedDS]
mov ds, ax
mov ax, word [rbx + ASM_SUPPORT_STATE.SavedES]
mov es, ax
mov ax, word [rbx + ASM_SUPPORT_STATE.SavedFS]
mov fs, ax
mov ax, word [rbx + ASM_SUPPORT_STATE.SavedGS]
mov gs, ax
; boot.efi preserves ss selector from UEFI GDT to just use UEFI stack (and memory) as is.
; For this reason just assume the stack is useable but align it for definite 64-bit compat.
and rsp, 0FFFFFFFFFFFFFFF0h
; Call AppleMapPrepareKernelState (rcx = rax = bootArgs, rdx = 0 = 32 bit kernel jump).
mov rcx, rdi
xor edx, edx
push rdx
push rdx
push rdx
push rcx
call ASM_PFX(AppleMapPrepareKernelState)
; Return value in rax is bootArgs pointer again.
mov rdi, rax
;
; Transition back to 32-bit.
;
; Load saved 32-bit GDT.
lgdt [rbx + ASM_SUPPORT_STATE.SavedGDTR32]
; Jump to the 32-bit code segment.
mov ax, word [rbx + ASM_SUPPORT_STATE.SavedCS32]
push rax
call LONG_RET64
BITS 32
;
; Done transitioning to 32-bit code.
;
; Disable paging (set CR0.PG=0).
mov eax, cr0 ; Read CR0.
btr eax, 31 ; Set PG=0.
mov cr0, eax ; Write CR0.
; Disable long mode (set EFER.LME=0).
mov ecx, 0C0000080h ; EFER MSR number.
rdmsr ; Read EFER.
btr eax, 8 ; Set LME=0.
wrmsr ; Write EFER.
jmp AsmJumpFromKernel32Compatibility
AsmJumpFromKernel32Compatibility:
;
; We are in 32-bit protected mode, no paging.
;
; Reload saved 32 bit state data.
; Since boot.efi relies on segment registers shadow part and preserves ss value,
; which contains previously read GDT data, we are not allowed to later update it.
lidt [ebx + ASM_SUPPORT_STATE.SavedIDTR32]
mov ax, word [ebx + ASM_SUPPORT_STATE.SavedDS32]
mov ds, ax
mov ax, word [ebx + ASM_SUPPORT_STATE.SavedES32]
mov es, ax
mov ax, word [ebx + ASM_SUPPORT_STATE.SavedFS32]
mov fs, ax
mov ax, word [ebx + ASM_SUPPORT_STATE.SavedGS32]
mov gs, ax
; Jump back to the kernel passing boot arguments in eax.
mov eax, edi
mov edx, dword [ebx + ASM_SUPPORT_STATE.KernelEntry]
jmp edx
;------------------------------------------------------------------------------
; AsmJumpFromKernel64
;
; Callback from boot.efi in 64 bit mode.
; State is prepared for kernel: 64 bit, pointer to bootArgs in rax.
;------------------------------------------------------------------------------
AsmJumpFromKernel64:
BITS 64
; Load rbx with AsmState - we'll access our saved data with it.
mov ebx, dword [ASM_PFX(gOcAbcAsmStateAddr32)]
; Store kernel entery point prior to hunk code.
pop rcx
sub rcx, ASM_KERNEL_JUMP.Size
mov qword [rbx + ASM_SUPPORT_STATE.KernelEntry], rcx
; Call AppleMapPrepareKernelState (rcx = rax = bootArgs, rdx = 1 = 64-bit kernel jump).
mov rcx, rax
xor edx, edx
push rdx
push rdx
push rdx
push rcx
inc edx
call ASM_PFX(AppleMapPrepareKernelState)
; Jump back to the kernel passing boot arguments in rax.
mov rdx, [rbx + ASM_SUPPORT_STATE.KernelEntry]
jmp rdx

View File

@ -0,0 +1,48 @@
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "../BootCompatInternal.h"
#include <Library/DebugLib.h>
VOID
AppleMapPlatformSaveState (
IN OUT ASM_SUPPORT_STATE *AsmState,
OUT ASM_KERNEL_JUMP *KernelJump
)
{
//
// Save current 64-bit state - will be used later in callback from kernel jump
// to be able to transition to 64-bit in case 32-bit kernel startup code is used.
//
AsmAppleMapPlatformSaveState (AsmState);
//
// Assembly state must fit into 32-bit address as we may jumo from 32-bit kernel
// startup code. This is used instead of GetBootCompatContext.
//
ASSERT ((UINT32)(UINTN) AsmState == (UINTN) AsmState);
gOcAbcAsmStateAddr32 = (UINT32)(UINTN) AsmState;
//
// Kernel trampoline for jumping to kernel.
//
ASSERT (
(UINT32)(UINTN) AsmAppleMapPlatformPrepareKernelState
== (UINTN) AsmAppleMapPlatformPrepareKernelState
);
KernelJump->MovInst = 0xB9;
KernelJump->Addr = (UINT32)(UINTN) AsmAppleMapPlatformPrepareKernelState;
KernelJump->CallInst = 0xD1FF;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,63 @@
## @file
#
# Component description file for the library producing the Apple Device property protocol.
#
# Copyright (C) 2019, vit9696. All rights reserved.<BR>
#
# All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# 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 = OcAppleBootPolicyLib
FILE_GUID = 330E9083-C008-4030-AA86-ECF1FBAE824D
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = OcAppleBootPolicyLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_SMM_DRIVER
#
# The following information is for reference only and not required by the build tools.
#
# VALID_ARCHITECTURES = IA32 X64 IPF EBC
#
[Sources]
OcAppleBootPolicyLib.c
[Packages]
CloverPkg.dec
# OpenCorePkg/OpenCorePkg.dec
MdePkg/MdePkg.dec
[Guids]
gAppleApfsContainerInfoGuid ## SOMETIMES_CONSUMES
gAppleApfsVolumeInfoGuid ## SOMETIMES_CONSUMES
gAppleBlessedSystemFileInfoGuid ## SOMETIMES_CONSUMES
gAppleBlessedSystemFolderInfoGuid ## SOMETIMES_CONSUMES
gAppleBlessedOsxFolderInfoGuid ## SOMETIMES_CONSUMES
gEfiFileInfoGuid ## SOMETIMES_CONSUMES
[Protocols]
gAppleBootPolicyProtocolGuid ## PRODUCES
gEfiSimpleFileSystemProtocolGuid ## SOMETIMES_CONSUMES
[LibraryClasses]
BaseLib
BaseMemoryLib
DebugLib
DevicePathLib
MemoryAllocationLib
PrintLib
UefiBootServicesTableLib
OcGuardLib
OcFileLib
OcXmlLib

View File

@ -0,0 +1,194 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleChunklistLib.h>
#include <Library/OcAppleRamDiskLib.h>
#include <Library/OcCryptoLib.h>
#include <Library/OcGuardLib.h>
BOOLEAN
OcAppleChunklistInitializeContext (
OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN OUT VOID *Buffer,
IN UINT32 BufferSize
)
{
APPLE_CHUNKLIST_HEADER *ChunklistHeader;
UINTN DataEnd;
UINT8 *Signature;
UINT32 SigLength;
UINT32 Index;
UINT8 SwapValue;
ASSERT (Buffer != NULL);
ASSERT (BufferSize > 0);
ASSERT (Context != NULL);
ChunklistHeader = (APPLE_CHUNKLIST_HEADER *) Buffer;
if (BufferSize < sizeof (APPLE_CHUNKLIST_HEADER)) {
return FALSE;
}
//
// Ensure the header is compatible.
//
if (ChunklistHeader->Magic != APPLE_CHUNKLIST_MAGIC
|| ChunklistHeader->Length != sizeof (APPLE_CHUNKLIST_HEADER)
|| ChunklistHeader->FileVersion != APPLE_CHUNKLIST_FILE_VERSION_10
|| ChunklistHeader->ChunkMethod != APPLE_CHUNKLIST_CHUNK_METHOD_10
|| ChunklistHeader->SigMethod != APPLE_CHUNKLIST_SIG_METHOD_10) {
return FALSE;
}
//
// Ensure that chunk and signature addresses are valid in the first place.
//
if (OcOverflowAddUN ((UINTN) Buffer, (UINTN) ChunklistHeader->ChunkOffset, (UINTN *) &Context->Chunks)
|| OcOverflowAddUN ((UINTN) Buffer, (UINTN) ChunklistHeader->SigOffset, (UINTN *) &Context->Signature)) {
return FALSE;
}
//
// Ensure that chunks and signature reside within Buffer.
//
if (ChunklistHeader->ChunkCount > MAX_UINTN) {
return FALSE;
}
Context->ChunkCount = (UINTN)ChunklistHeader->ChunkCount;
if (OcOverflowMulAddUN (sizeof (APPLE_CHUNKLIST_CHUNK), Context->ChunkCount, (UINTN) Context->Chunks, &DataEnd)
|| DataEnd > (UINTN) Buffer + BufferSize
|| OcOverflowAddUN (sizeof (APPLE_CHUNKLIST_SIG), (UINTN) Context->Signature, &DataEnd)
|| DataEnd != (UINTN) Buffer + BufferSize) {
return FALSE;
}
//
// Prepare signature verification data.
//
Sha256 (Context->Hash, (UINT8 *)ChunklistHeader, (UINTN)ChunklistHeader->SigOffset);
Signature = Context->Signature->Signature;
SigLength = sizeof (Context->Signature->Signature);
for (Index = 0; Index < (SigLength / 2); ++Index) {
SwapValue = Signature[Index];
Signature[Index] = Signature[SigLength - Index - 1];
Signature[SigLength - Index - 1] = SwapValue;
}
return TRUE;
}
BOOLEAN
OcAppleChunklistVerifySignature (
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN CONST OC_RSA_PUBLIC_KEY *PublicKey
)
{
BOOLEAN Result;
ASSERT (Context != NULL);
ASSERT (Context->Signature != NULL);
Result = RsaVerifySigHashFromKey (
PublicKey,
Context->Signature->Signature,
sizeof (Context->Signature->Signature),
Context->Hash,
sizeof (Context->Hash),
OcSigHashTypeSha256
);
DEBUG_CODE (
if (Result) {
Context->Signature = NULL;
}
);
return Result;
}
BOOLEAN
OcAppleChunklistVerifyData (
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *Context,
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable
)
{
BOOLEAN Result;
UINTN Index;
UINT8 ChunkHash[SHA256_DIGEST_SIZE];
CONST APPLE_CHUNKLIST_CHUNK *CurrentChunk;
UINTN CurrentOffset;
UINT32 ChunkDataSize;
VOID *ChunkData;
ASSERT (Context != NULL);
ASSERT (Context->Chunks != NULL);
ASSERT (ExtentTable != NULL);
DEBUG_CODE (
ASSERT (Context->Signature == NULL);
);
ChunkDataSize = 0;
for (Index = 0; Index < Context->ChunkCount; ++Index) {
CurrentChunk = &Context->Chunks[Index];
if (ChunkDataSize < CurrentChunk->Length) {
ChunkDataSize = CurrentChunk->Length;
}
}
ChunkData = AllocatePool (ChunkDataSize);
if (ChunkData == NULL) {
return FALSE;
}
CurrentOffset = 0;
for (Index = 0; Index < Context->ChunkCount; Index++) {
CurrentChunk = &Context->Chunks[Index];
Result = OcAppleRamDiskRead (
ExtentTable,
CurrentOffset,
CurrentChunk->Length,
ChunkData
);
if (!Result) {
FreePool (ChunkData);
return FALSE;
}
//
// Calculate checksum of data and ensure they match.
//
DEBUG ((DEBUG_VERBOSE, "OCCL: Validating chunk %lu of %lu\n",
(UINT64)Index + 1, (UINT64)Context->ChunkCount));
Sha256 (ChunkHash, ChunkData, CurrentChunk->Length);
if (CompareMem (ChunkHash, CurrentChunk->Checksum, SHA256_DIGEST_SIZE) != 0) {
FreePool (ChunkData);
return FALSE;
}
CurrentOffset += CurrentChunk->Length;
}
FreePool (ChunkData);
return TRUE;
}

View File

@ -0,0 +1,35 @@
## @file
# Copyright (C) 2019, Goldfish64. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# 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 = OcAppleChunklistLib
FILE_GUID = D891DF81-0C83-47FF-ABAD-546050E1A07F
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = OcAppleChunklistLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_SMM_DRIVER
[Packages]
CloverPkg.dec
MdePkg/MdePkg.dec
# OpenCorePkg/OpenCorePkg.dec
[LibraryClasses]
BaseMemoryLib
DebugLib
OcAppleRamDiskLib
OcCryptoLib
UefiLib
[Sources]
OcAppleChunklistLib.c

View File

@ -0,0 +1,367 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <Protocol/AppleDiskImage.h>
#include <Protocol/AppleRamDisk.h>
#include <Protocol/BlockIo.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleDiskImageLib.h>
#include <Library/OcStringLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include "OcAppleDiskImageLibInternal.h"
#define DMG_FILE_PATH_LEN (L_STR_LEN (L"DMG_.dmg") + 16 + 1)
#pragma pack(push, 1)
typedef PACKED struct {
VENDOR_DEFINED_DEVICE_PATH Vendor;
UINT64 Length;
} DMG_SIZE_DEVICE_PATH;
typedef PACKED struct {
EFI_DEVICE_PATH_PROTOCOL Header;
///
/// A NULL-terminated Path string including directory and file names.
///
CHAR16 PathName[DMG_FILE_PATH_LEN];
} DMG_FILEPATH_DEVICE_PATH;
typedef PACKED struct {
APPLE_RAM_DISK_DP_HEADER RamDisk;
DMG_FILEPATH_DEVICE_PATH FilePath;
DMG_SIZE_DEVICE_PATH Size;
EFI_DEVICE_PATH_PROTOCOL End;
} DMG_DEVICE_PATH;
#pragma pack(pop)
#define OC_APPLE_DISK_IMAGE_MOUNTED_DATA_SIGNATURE \
SIGNATURE_32('D','m','g','I')
#define OC_APPLE_DISK_IMAGE_MOUNTED_DATA_FROM_THIS(This) \
BASE_CR ( \
(This), \
OC_APPLE_DISK_IMAGE_MOUNTED_DATA, \
BlockIo \
)
typedef struct {
UINT32 Signature;
EFI_BLOCK_IO_PROTOCOL BlockIo;
EFI_BLOCK_IO_MEDIA BlockIoMedia;
DMG_DEVICE_PATH DevicePath;
OC_APPLE_DISK_IMAGE_CONTEXT *ImageContext;
} OC_APPLE_DISK_IMAGE_MOUNTED_DATA;
STATIC
EFI_STATUS
EFIAPI
DiskImageBlockIoReset (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
)
{
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
DiskImageBlockIoReadBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
)
{
OC_APPLE_DISK_IMAGE_MOUNTED_DATA *DiskImageData;
BOOLEAN Result;
if ((This == NULL) || (Buffer == NULL)) {
return EFI_INVALID_PARAMETER;
}
if ((BufferSize % APPLE_DISK_IMAGE_SECTOR_SIZE) != 0) {
return EFI_BAD_BUFFER_SIZE;
}
DiskImageData = OC_APPLE_DISK_IMAGE_MOUNTED_DATA_FROM_THIS (This);
if (DiskImageData->Signature == 0) {
return EFI_UNSUPPORTED;
}
ASSERT (DiskImageData->Signature == OC_APPLE_DISK_IMAGE_MOUNTED_DATA_SIGNATURE);
if (Lba >= DiskImageData->ImageContext->SectorCount) {
return EFI_INVALID_PARAMETER;
}
Result = OcAppleDiskImageRead (
DiskImageData->ImageContext,
(UINTN)Lba,
BufferSize,
Buffer
);
if (!Result) {
return EFI_DEVICE_ERROR;
}
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
DiskImageBlockIoWriteBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
IN VOID *Buffer
)
{
return EFI_WRITE_PROTECTED;
}
STATIC
EFI_STATUS
EFIAPI
DiskImageBlockIoFlushBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This
)
{
return EFI_SUCCESS;
}
STATIC UINT32 mDmgCounter; ///< FIXME: This should exist on a protocol basis!
STATIC
VOID
InternalConstructDmgDevicePath (
IN OUT OC_APPLE_DISK_IMAGE_MOUNTED_DATA *DiskImageData,
IN UINTN FileSize
)
{
UINT64 RamDmgAddress;
DMG_DEVICE_PATH *DevPath;
CHAR16 *UnicodeDevPath;
ASSERT (DiskImageData != NULL);
ASSERT (DiskImageData->ImageContext);
RamDmgAddress = (UINTN)DiskImageData->ImageContext->ExtentTable;
DevPath = &DiskImageData->DevicePath;
DevPath->RamDisk.Vendor.Vendor.Header.Type = HARDWARE_DEVICE_PATH;
DevPath->RamDisk.Vendor.Vendor.Header.SubType = HW_VENDOR_DP;
CopyGuid (
&DevPath->RamDisk.Vendor.Vendor.Guid,
&gAppleRamDiskProtocolGuid
);
DevPath->RamDisk.Vendor.Counter = mDmgCounter++;
SetDevicePathNodeLength (
&DevPath->RamDisk.Vendor,
sizeof (DevPath->RamDisk.Vendor)
);
DevPath->RamDisk.MemMap.Header.Type = HARDWARE_DEVICE_PATH;
DevPath->RamDisk.MemMap.Header.SubType = HW_MEMMAP_DP;
DevPath->RamDisk.MemMap.MemoryType = EfiACPIMemoryNVS;
DevPath->RamDisk.MemMap.StartingAddress = RamDmgAddress;
DevPath->RamDisk.MemMap.EndingAddress = RamDmgAddress + sizeof (APPLE_RAM_DISK_EXTENT_TABLE);
SetDevicePathNodeLength (&DevPath->RamDisk.MemMap, sizeof (DevPath->RamDisk.MemMap));
DevPath->FilePath.Header.Type = MEDIA_DEVICE_PATH;
DevPath->FilePath.Header.SubType = MEDIA_FILEPATH_DP;
SetDevicePathNodeLength (&DevPath->FilePath, sizeof (DevPath->FilePath));
UnicodeSPrint (
DevPath->FilePath.PathName,
sizeof (DevPath->FilePath.PathName),
L"DMG_%16X.dmg",
FileSize
);
DevPath->Size.Vendor.Header.Type = MESSAGING_DEVICE_PATH;
DevPath->Size.Vendor.Header.SubType = MSG_VENDOR_DP;
DevPath->Size.Length = FileSize;
SetDevicePathNodeLength (&DevPath->Size, sizeof (DevPath->Size));
CopyGuid (
(VOID *)&DevPath->Size.Vendor.Guid,
&gAppleDiskImageProtocolGuid
);
SetDevicePathEndNode (&DevPath->End);
DEBUG_CODE_BEGIN ();
ASSERT (
IsDevicePathValid ((EFI_DEVICE_PATH_PROTOCOL *) DevPath, sizeof (*DevPath))
);
UnicodeDevPath = ConvertDevicePathToText ((EFI_DEVICE_PATH_PROTOCOL *)DevPath, FALSE, FALSE);
DEBUG ((DEBUG_INFO, "OCDI: Built DMG DP: %s\n", UnicodeDevPath != NULL ? UnicodeDevPath : L"<NULL>"));
if (UnicodeDevPath != NULL) {
FreePool (UnicodeDevPath);
}
DEBUG_CODE_END ();
}
STATIC CONST EFI_BLOCK_IO_PROTOCOL mDiskImageBlockIo = {
EFI_BLOCK_IO_PROTOCOL_REVISION,
NULL,
DiskImageBlockIoReset,
DiskImageBlockIoReadBlocks,
DiskImageBlockIoWriteBlocks,
DiskImageBlockIoFlushBlocks
};
EFI_HANDLE
OcAppleDiskImageInstallBlockIo (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN FileSize,
OUT CONST EFI_DEVICE_PATH_PROTOCOL **DevicePath OPTIONAL,
OUT UINTN *DevicePathSize OPTIONAL
)
{
EFI_HANDLE BlockIoHandle;
EFI_STATUS Status;
OC_APPLE_DISK_IMAGE_MOUNTED_DATA *DiskImageData;
ASSERT (Context != NULL);
ASSERT (FileSize > 0);
DiskImageData = AllocateZeroPool (sizeof (*DiskImageData));
if (DiskImageData == NULL) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to allocate DMG mount context\n"));
return NULL;
}
DiskImageData->Signature = OC_APPLE_DISK_IMAGE_MOUNTED_DATA_SIGNATURE;
DiskImageData->ImageContext = Context;
CopyMem (
&DiskImageData->BlockIo,
&mDiskImageBlockIo,
sizeof (DiskImageData->BlockIo)
);
DiskImageData->BlockIo.Media = &DiskImageData->BlockIoMedia;
DiskImageData->BlockIoMedia.MediaPresent = TRUE;
DiskImageData->BlockIoMedia.ReadOnly = TRUE;
DiskImageData->BlockIoMedia.BlockSize = APPLE_DISK_IMAGE_SECTOR_SIZE;
DiskImageData->BlockIoMedia.LastBlock = (Context->SectorCount - 1);
InternalConstructDmgDevicePath (DiskImageData, FileSize);
BlockIoHandle = NULL;
Status = gBS->InstallMultipleProtocolInterfaces (
&BlockIoHandle,
&gEfiDevicePathProtocolGuid,
&DiskImageData->DevicePath,
&gEfiBlockIoProtocolGuid,
&DiskImageData->BlockIo,
NULL
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to install protocols %r\n", Status));
FreePool (DiskImageData);
return NULL;
}
Status = gBS->ConnectController (BlockIoHandle, NULL, NULL, TRUE);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to connect DMG handle %r\n", Status));
Status = gBS->UninstallMultipleProtocolInterfaces (
BlockIoHandle,
&gEfiDevicePathProtocolGuid,
&DiskImageData->DevicePath,
&gEfiBlockIoProtocolGuid,
&DiskImageData->BlockIo,
NULL
);
if (!EFI_ERROR (Status)) {
FreePool (DiskImageData);
} else {
DEBUG ((DEBUG_INFO, "OCDI: Failed to uninstall protocols %r\n", Status));
DiskImageData->Signature = 0;
}
return NULL;
}
if (DevicePath != NULL) {
*DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)&DiskImageData->DevicePath;
if (DevicePathSize != NULL) {
*DevicePathSize = sizeof (DiskImageData->DevicePath);
}
}
return BlockIoHandle;
}
VOID
OcAppleDiskImageUninstallBlockIo (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN VOID *BlockIoHandle
)
{
EFI_STATUS Status;
EFI_BLOCK_IO_PROTOCOL *BlockIo;
OC_APPLE_DISK_IMAGE_MOUNTED_DATA *DiskImageData;
ASSERT (Context != NULL);
ASSERT (BlockIoHandle != NULL);
Status = gBS->HandleProtocol (
BlockIoHandle,
&gEfiBlockIoProtocolGuid,
(VOID **)&BlockIo
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDI: Invalid handle for Block I/O uninstall\n"));
return;
}
DiskImageData = OC_APPLE_DISK_IMAGE_MOUNTED_DATA_FROM_THIS (BlockIo);
Status = gBS->DisconnectController (BlockIoHandle, NULL, NULL);
Status |= gBS->UninstallMultipleProtocolInterfaces (
BlockIoHandle,
&gEfiBlockIoProtocolGuid,
&DiskImageData->BlockIo,
&gEfiDevicePathProtocolGuid,
&DiskImageData->DevicePath,
NULL
);
if (!EFI_ERROR (Status)) {
FreePool (DiskImageData);
} else {
DEBUG ((
DEBUG_INFO,
"OCDI: Failed to disconnect DMG controller or uninstal protocols\n"
));
DiskImageData->Signature = 0;
}
}

View File

@ -0,0 +1,422 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <Protocol/SimpleFileSystem.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleChunklistLib.h>
#include <Library/OcAppleDiskImageLib.h>
#include <Library/OcCompressionLib.h>
#include <Library/OcFileLib.h>
#include <Library/OcGuardLib.h>
#include "OcAppleDiskImageLibInternal.h"
BOOLEAN
OcAppleDiskImageInitializeContext (
OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable,
IN UINTN FileSize
)
{
BOOLEAN Result;
UINTN TrailerOffset;
APPLE_DISK_IMAGE_TRAILER Trailer;
UINT32 DmgBlockCount;
APPLE_DISK_IMAGE_BLOCK_DATA **DmgBlocks;
UINT32 SwappedSig;
UINT64 OffsetTop;
UINT32 HeaderSize;
UINT64 DataForkOffset;
UINT64 DataForkLength;
UINT32 SegmentCount;
APPLE_DISK_IMAGE_CHECKSUM DataForkChecksum;
UINT64 XmlOffset;
UINT64 XmlLength;
UINT64 SectorCount;
CHAR8 *PlistData;
ASSERT (Context != NULL);
ASSERT (ExtentTable != NULL);
ASSERT (FileSize > 0);
if (FileSize <= sizeof (Trailer)) {
DEBUG ((
DEBUG_INFO,
"OCDI: DMG file size error: %u/%u\n",
FileSize,
(UINT32) sizeof (Trailer)
));
return FALSE;
}
SwappedSig = SwapBytes32 (APPLE_DISK_IMAGE_MAGIC);
TrailerOffset = (FileSize - sizeof (Trailer));
Result = OcAppleRamDiskRead (
ExtentTable,
TrailerOffset,
sizeof (Trailer),
&Trailer
);
if (!Result || (Trailer.Signature != SwappedSig)) {
DEBUG ((
DEBUG_INFO,
"OCDI: DMG trailer error: %d - %Lx/%Lx - %X/%X\n",
Result,
(UINT64) TrailerOffset,
(UINT64) FileSize,
SwappedSig,
Trailer.Signature
));
return FALSE;
}
HeaderSize = SwapBytes32 (Trailer.HeaderSize);
DataForkOffset = SwapBytes64 (Trailer.DataForkOffset);
DataForkLength = SwapBytes64 (Trailer.DataForkLength);
SegmentCount = SwapBytes32 (Trailer.SegmentCount);
XmlOffset = SwapBytes64 (Trailer.XmlOffset);
XmlLength = SwapBytes64 (Trailer.XmlLength);
SectorCount = SwapBytes64 (Trailer.SectorCount);
DataForkChecksum.Size = SwapBytes32 (Trailer.DataForkChecksum.Size);
if ((HeaderSize != sizeof (Trailer))
|| (XmlLength == 0)
|| (XmlLength > MAX_UINT32)
|| (DataForkChecksum.Size > (sizeof (DataForkChecksum.Data) * 8))
|| (SectorCount == 0)) {
DEBUG ((
DEBUG_INFO,
"OCDI: DMG context error: %u/%Lu/%Lu/%u/%u\n",
HeaderSize,
XmlLength,
SectorCount,
DataForkChecksum.Size
));
return FALSE;
}
if ((SegmentCount != 0) && (SegmentCount != 1)) {
DEBUG ((DEBUG_ERROR, "OCDI: Multiple segments are unsupported\n"));
return FALSE;
}
Result = OcOverflowMulU64 (
SectorCount,
APPLE_DISK_IMAGE_SECTOR_SIZE,
&OffsetTop
);
if (Result || (OffsetTop > MAX_UINTN)) {
DEBUG ((DEBUG_INFO, "OCDI: DMG sector error: %Lu %Lu\n", SectorCount, OffsetTop));
return FALSE;
}
Result = OcOverflowAddU64 (
XmlOffset,
XmlLength,
&OffsetTop
);
if (Result || (OffsetTop > TrailerOffset)) {
DEBUG ((DEBUG_INFO, "OCDI: DMG xml error: %Lu %Lu %Lu %Lu\n", XmlOffset, XmlLength, OffsetTop, TrailerOffset));
return FALSE;
}
Result = OcOverflowAddU64 (
DataForkOffset,
DataForkLength,
&OffsetTop
);
if (Result || (OffsetTop > TrailerOffset)) {
DEBUG ((DEBUG_INFO, "OCDI: DMG data error: %Lu %Lu %Lu %Lu\n", DataForkOffset, DataForkLength, OffsetTop, TrailerOffset));
return FALSE;
}
PlistData = AllocatePool ((UINT32)XmlLength);
if (PlistData == NULL) {
DEBUG ((DEBUG_INFO, "OCDI: DMG plist alloc error: %Lu\n", XmlLength));
return FALSE;
}
Result = OcAppleRamDiskRead (
ExtentTable,
(UINTN)XmlOffset,
(UINTN)XmlLength,
PlistData
);
if (!Result) {
DEBUG ((DEBUG_INFO, "OCDI: DMG plist read error: %Lu %Lu\n", XmlOffset, XmlLength));
FreePool (PlistData);
return FALSE;
}
Result = InternalParsePlist (
PlistData,
(UINT32)XmlLength,
(UINTN)SectorCount,
(UINTN)DataForkOffset,
(UINTN)DataForkLength,
&DmgBlockCount,
&DmgBlocks
);
FreePool (PlistData);
if (!Result) {
DEBUG ((DEBUG_INFO, "OCDI: DMG plist parse error: %Lu %Lu\n", XmlOffset, XmlLength));
return FALSE;
}
Context->ExtentTable = ExtentTable;
Context->BlockCount = DmgBlockCount;
Context->Blocks = DmgBlocks;
Context->SectorCount = (UINTN)SectorCount;
return TRUE;
}
BOOLEAN
OcAppleDiskImageInitializeFromFile (
OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN EFI_FILE_PROTOCOL *File
)
{
EFI_STATUS Status;
BOOLEAN Result;
UINT32 FileSize;
CONST APPLE_RAM_DISK_EXTENT_TABLE *ExtentTable;
ASSERT (Context != NULL);
ASSERT (File != NULL);
Status = GetFileSize (File, &FileSize);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to retrieve DMG file size\n"));
return FALSE;
}
ExtentTable = OcAppleRamDiskAllocate (FileSize, EfiACPIMemoryNVS);
if (ExtentTable == NULL) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to allocate DMG data\n"));
return FALSE;
}
Result = OcAppleRamDiskLoadFile (ExtentTable, File, FileSize);
if (!Result) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to load DMG file\n"));
OcAppleRamDiskFree (ExtentTable);
return FALSE;
}
Result = OcAppleDiskImageInitializeContext (Context, ExtentTable, FileSize);
if (!Result) {
DEBUG ((DEBUG_INFO, "OCDI: Failed to initialise DMG context\n"));
OcAppleRamDiskFree (ExtentTable);
return FALSE;
}
return TRUE;
}
BOOLEAN
OcAppleDiskImageVerifyData (
IN OUT OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN OUT OC_APPLE_CHUNKLIST_CONTEXT *ChunklistContext
)
{
ASSERT (Context != NULL);
ASSERT (ChunklistContext != NULL);
return OcAppleChunklistVerifyData (
ChunklistContext,
Context->ExtentTable
);
}
VOID
OcAppleDiskImageFreeContext (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context
)
{
UINT32 Index;
ASSERT (Context != NULL);
for (Index = 0; Index < Context->BlockCount; ++Index) {
FreePool (Context->Blocks[Index]);
}
FreePool (Context->Blocks);
}
VOID
OcAppleDiskImageFreeFile (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context
)
{
OcAppleRamDiskFree (Context->ExtentTable);
OcAppleDiskImageFreeContext (Context);
}
BOOLEAN
OcAppleDiskImageRead (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
)
{
BOOLEAN Result;
APPLE_DISK_IMAGE_BLOCK_DATA *BlockData;
APPLE_DISK_IMAGE_CHUNK *Chunk;
UINT64 ChunkTotalLength;
UINT64 ChunkLength;
UINT64 ChunkOffset;
UINT8 *ChunkData;
UINT8 *ChunkDataCompressed;
UINTN LbaCurrent;
UINTN LbaOffset;
UINTN LbaLength;
UINTN RemainingBufferSize;
UINTN BufferChunkSize;
UINT8 *BufferCurrent;
UINTN OutSize;
ASSERT (Context != NULL);
ASSERT (Buffer != NULL);
ASSERT (Lba < Context->SectorCount);
LbaCurrent = Lba;
RemainingBufferSize = BufferSize;
BufferCurrent = Buffer;
while (RemainingBufferSize > 0) {
Result = InternalGetBlockChunk (Context, LbaCurrent, &BlockData, &Chunk);
if (!Result) {
return FALSE;
}
LbaOffset = (LbaCurrent - (UINTN)DMG_SECTOR_START_ABS (BlockData, Chunk));
LbaLength = ((UINTN)Chunk->SectorCount - LbaOffset);
Result = OcOverflowMulU64 (
LbaOffset,
APPLE_DISK_IMAGE_SECTOR_SIZE,
&ChunkOffset
);
if (Result) {
return FALSE;
}
Result = OcOverflowMulU64 (
Chunk->SectorCount,
APPLE_DISK_IMAGE_SECTOR_SIZE,
&ChunkTotalLength
);
if (Result) {
return FALSE;
}
ChunkLength = (ChunkTotalLength - ChunkOffset);
BufferChunkSize = (UINTN)MIN (RemainingBufferSize, ChunkLength);
switch (Chunk->Type) {
case APPLE_DISK_IMAGE_CHUNK_TYPE_ZERO:
case APPLE_DISK_IMAGE_CHUNK_TYPE_IGNORE:
{
ZeroMem (BufferCurrent, BufferChunkSize);
break;
}
case APPLE_DISK_IMAGE_CHUNK_TYPE_RAW:
{
Result = OcAppleRamDiskRead (
Context->ExtentTable,
(UINTN)(Chunk->CompressedOffset + ChunkOffset),
BufferChunkSize,
BufferCurrent
);
if (!Result) {
return FALSE;
}
break;
}
case APPLE_DISK_IMAGE_CHUNK_TYPE_ZLIB:
{
ChunkData = AllocatePool ((UINTN)(ChunkTotalLength + Chunk->CompressedLength));
if (ChunkData == NULL) {
return FALSE;
}
ChunkDataCompressed = (ChunkData + (UINTN)ChunkTotalLength);
Result = OcAppleRamDiskRead (
Context->ExtentTable,
(UINTN)Chunk->CompressedOffset,
(UINTN)Chunk->CompressedLength,
ChunkDataCompressed
);
if (!Result) {
FreePool (ChunkData);
return FALSE;
}
OutSize = DecompressZLIB (
ChunkData,
(UINTN)ChunkTotalLength,
ChunkDataCompressed,
(UINTN)Chunk->CompressedLength
);
if (OutSize != (UINTN)ChunkTotalLength) {
FreePool (ChunkData);
return FALSE;
}
CopyMem (BufferCurrent, (ChunkData + ChunkOffset), BufferChunkSize);
FreePool (ChunkData);
break;
}
default:
{
DEBUG ((
DEBUG_ERROR,
"OCDI: Compression type %x unsupported\n",
Chunk->Type
));
return FALSE;
}
}
RemainingBufferSize -= BufferChunkSize;
BufferCurrent += BufferChunkSize;
LbaCurrent += LbaLength;
}
return TRUE;
}

View File

@ -0,0 +1,49 @@
## @file
# Copyright (C) 2019, Goldfish64. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# 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 = OcAppleDiskImageLib
FILE_GUID = F8E071ED-3EAB-46C6-9C50-B99B6B3915FF
MODULE_TYPE = BASE
VERSION_STRING = 1.0
LIBRARY_CLASS = OcAppleDiskImageLib|PEIM DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_SMM_DRIVER
[Packages]
CloverPkg.dec
MdePkg/MdePkg.dec
# OpenCorePkg/OpenCorePkg.dec
[LibraryClasses]
BaseMemoryLib
DebugLib
DevicePathLib
MemoryAllocationLib
OcAppleRamDiskLib
OcCompressionLib
OcDevicePathLib
OcGuardLib
OcXmlLib
PrintLib
[Protocols]
gEfiDevicePathProtocolGuid # PRODUCES
gEfiBlockIoProtocolGuid # PRODUCES
gAppleRamDiskProtocolGuid # CONSUMES
gAppleDiskImageProtocolGuid # CONSUMES
[Sources]
OcAppleDiskImageBlockIo.c
OcAppleDiskImageLib.c
OcAppleDiskImageLibInternal.c
OcAppleDiskImageLibInternal.h

View File

@ -0,0 +1,355 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleDiskImageLib.h>
#include <Library/OcGuardLib.h>
#include <Library/OcXmlLib.h>
#include "OcAppleDiskImageLibInternal.h"
STATIC
BOOLEAN
InternalFindPlistDictChild (
IN XML_NODE *Node,
IN CHAR8 *KeyName,
OUT XML_NODE **Key,
OUT XML_NODE **Value
)
{
UINT32 ChildCount;
XML_NODE *ChildValue;
XML_NODE *ChildKey;
CONST CHAR8 *ChildKeyName;
UINT32 Index;
ASSERT (Node != NULL);
ASSERT (KeyName != NULL);
ASSERT (Key != NULL);
ASSERT (Value != NULL);
ChildCount = PlistDictChildren (Node);
for (Index = 0; Index < ChildCount; ++Index) {
ChildKey = PlistDictChild (Node, Index, &ChildValue);
if (ChildKey == NULL) {
break;
}
ChildKeyName = PlistKeyValue (ChildKey);
if (ChildKeyName == NULL) {
break;
}
if (AsciiStrCmp (ChildKeyName, KeyName) == 0) {
*Key = ChildKey;
*Value = ChildValue;
return TRUE;
}
}
return FALSE;
}
STATIC
BOOLEAN
InternalSwapBlockData (
IN OUT APPLE_DISK_IMAGE_BLOCK_DATA *BlockData,
IN UINT32 MaxSize,
IN UINTN SectorCount,
IN UINTN DataForkOffset,
IN UINTN DataForkSize
)
{
UINT32 ChunksSize;
UINTN MaxOffset;
BOOLEAN Result;
APPLE_DISK_IMAGE_CHUNK *Chunk;
UINT32 Index;
UINT64 BlockSectorTop;
UINT64 ChunkSectorTop;
UINT64 OffsetTop;
ASSERT (MaxSize >= sizeof (*BlockData));
BlockData->ChunkCount = SwapBytes32 (BlockData->ChunkCount);
Result = OcOverflowMulU32 (
BlockData->ChunkCount,
sizeof (*BlockData->Chunks),
&ChunksSize
);
if (Result || (ChunksSize > (MaxSize - sizeof (*BlockData)))) {
return FALSE;
}
MaxOffset = (DataForkOffset + DataForkSize);
BlockData->Version = SwapBytes32 (BlockData->Version);
BlockData->SectorNumber = SwapBytes64 (BlockData->SectorNumber);
BlockData->SectorCount = SwapBytes64 (BlockData->SectorCount);
BlockData->DataOffset = SwapBytes64 (BlockData->DataOffset);
BlockData->BuffersNeeded = SwapBytes32 (BlockData->BuffersNeeded);
BlockData->BlockDescriptors = SwapBytes32 (BlockData->BlockDescriptors);
BlockData->Checksum.Type = SwapBytes32 (BlockData->Checksum.Type);
BlockData->Checksum.Size = SwapBytes32 (BlockData->Checksum.Size);
if (BlockData->DataOffset > DataForkOffset
|| (BlockData->Checksum.Size > (sizeof (BlockData->Checksum.Data) * 8))
|| (BlockData->DataOffset > MaxOffset)) {
return FALSE;
}
Result = OcOverflowAddU64 (
BlockData->SectorNumber,
BlockData->SectorCount,
&BlockSectorTop
);
if (Result || BlockSectorTop > SectorCount) {
DEBUG ((DEBUG_ERROR, "OCDI: Block sectors exceed DMG sectors %lu %lu\n", BlockSectorTop, SectorCount));
return FALSE;
}
for (Index = 0; Index < APPLE_DISK_IMAGE_CHECKSUM_SIZE; ++Index) {
BlockData->Checksum.Data[Index] = SwapBytes32 (
BlockData->Checksum.Data[Index]
);
}
for (Index = 0; Index < BlockData->ChunkCount; ++Index) {
Chunk = &BlockData->Chunks[Index];
Chunk->Type = SwapBytes32 (Chunk->Type);
Chunk->Comment = SwapBytes32 (Chunk->Comment);
Chunk->SectorNumber = SwapBytes64 (Chunk->SectorNumber);
Chunk->SectorCount = SwapBytes64 (Chunk->SectorCount);
Chunk->CompressedOffset = SwapBytes64 (Chunk->CompressedOffset);
Chunk->CompressedLength = SwapBytes64 (Chunk->CompressedLength);
Result = OcOverflowAddU64 (
Chunk->SectorNumber,
Chunk->SectorCount,
&ChunkSectorTop
);
if (Result || (ChunkSectorTop > BlockSectorTop)) {
return FALSE;
}
Result = OcOverflowAddU64 (
Chunk->CompressedOffset,
Chunk->CompressedLength,
&OffsetTop
);
if (Result || (OffsetTop > MaxOffset)) {
return FALSE;
}
}
return TRUE;
}
BOOLEAN
InternalParsePlist (
IN CHAR8 *Plist,
IN UINT32 PlistSize,
IN UINTN SectorCount,
IN UINTN DataForkOffset,
IN UINTN DataForkSize,
OUT UINT32 *BlockCount,
OUT APPLE_DISK_IMAGE_BLOCK_DATA ***Blocks
)
{
BOOLEAN Result;
XML_DOCUMENT *XmlPlistDoc;
XML_NODE *NodeRoot;
XML_NODE *NodeResourceForkKey;
XML_NODE *NodeResourceForkValue;
XML_NODE *NodeBlockListKey;
XML_NODE *NodeBlockListValue;
XML_NODE *NodeBlockDict;
XML_NODE *BlockDictChildKey;
XML_NODE *BlockDictChildValue;
UINT32 BlockDictChildDataSize;
UINT32 NumDmgBlocks;
UINT32 DmgBlocksSize;
APPLE_DISK_IMAGE_BLOCK_DATA **DmgBlocks;
APPLE_DISK_IMAGE_BLOCK_DATA *Block;
UINT32 Index;
ASSERT (Plist != NULL);
ASSERT (PlistSize > 0);
ASSERT (BlockCount != NULL);
ASSERT (Blocks != NULL);
DmgBlocks = NULL;
XmlPlistDoc = NULL;
XmlPlistDoc = XmlDocumentParse (Plist, PlistSize, FALSE);
if (XmlPlistDoc == NULL) {
Result = FALSE;
goto DONE_ERROR;
}
NodeRoot = PlistDocumentRoot (XmlPlistDoc);
if (NodeRoot == NULL) {
Result = FALSE;
goto DONE_ERROR;
}
Result = InternalFindPlistDictChild (
NodeRoot,
DMG_PLIST_RESOURCE_FORK_KEY,
&NodeResourceForkKey,
&NodeResourceForkValue
);
if (!Result) {
goto DONE_ERROR;
}
Result = InternalFindPlistDictChild (
NodeResourceForkValue,
DMG_PLIST_BLOCK_LIST_KEY,
&NodeBlockListKey,
&NodeBlockListValue
);
if (!Result) {
goto DONE_ERROR;
}
NumDmgBlocks = XmlNodeChildren (NodeBlockListValue);
if (NumDmgBlocks == 0) {
Result = FALSE;
goto DONE_ERROR;
}
Result = !OcOverflowMulU32 (NumDmgBlocks, sizeof (*DmgBlocks), &DmgBlocksSize);
if (!Result) { ///< Result must be FALSE on error, it's checked at DONE_ERROR
goto DONE_ERROR;
}
DmgBlocks = AllocatePool (DmgBlocksSize);
if (DmgBlocks == NULL) {
Result = FALSE;
goto DONE_ERROR;
}
for (Index = 0; Index < NumDmgBlocks; ++Index) {
NodeBlockDict = XmlNodeChild (NodeBlockListValue, Index);
Result = InternalFindPlistDictChild (
NodeBlockDict,
DMG_PLIST_DATA,
&BlockDictChildKey,
&BlockDictChildValue
);
if (!Result) {
goto DONE_ERROR;
}
Result = PlistDataSize (BlockDictChildValue, &BlockDictChildDataSize);
if (!Result || (BlockDictChildDataSize < sizeof (*Block))) {
Result = FALSE;
goto DONE_ERROR;
}
Block = AllocatePool (BlockDictChildDataSize);
if (Block == NULL) {
Result = FALSE;
goto DONE_ERROR;
}
DmgBlocks[Index] = Block;
Result = PlistDataValue (
BlockDictChildValue,
(UINT8 *)Block,
&BlockDictChildDataSize
);
if (!Result) {
FreePool (Block);
goto DONE_ERROR;
}
Result = InternalSwapBlockData (
Block,
BlockDictChildDataSize,
SectorCount,
DataForkOffset,
DataForkSize
);
if (!Result) {
FreePool (Block);
goto DONE_ERROR;
}
}
*BlockCount = NumDmgBlocks;
*Blocks = DmgBlocks;
Result = TRUE;
DONE_ERROR:
if (!Result && (DmgBlocks != NULL)) {
while ((Index--) != 0) {
FreePool (DmgBlocks[Index]);
}
FreePool (DmgBlocks);
}
if (XmlPlistDoc != NULL) {
XmlDocumentFree (XmlPlistDoc);
}
return Result;
}
BOOLEAN
InternalGetBlockChunk (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN Lba,
OUT APPLE_DISK_IMAGE_BLOCK_DATA **Data,
OUT APPLE_DISK_IMAGE_CHUNK **Chunk
)
{
UINT32 BlockIndex;
UINT32 ChunkIndex;
APPLE_DISK_IMAGE_BLOCK_DATA *BlockData;
APPLE_DISK_IMAGE_CHUNK *BlockChunk;
for (BlockIndex = 0; BlockIndex < Context->BlockCount; ++BlockIndex) {
BlockData = Context->Blocks[BlockIndex];
if ((Lba >= BlockData->SectorNumber)
&& (Lba < (BlockData->SectorNumber + BlockData->SectorCount))) {
for (ChunkIndex = 0; ChunkIndex < BlockData->ChunkCount; ++ChunkIndex) {
BlockChunk = &BlockData->Chunks[ChunkIndex];
if ((Lba >= DMG_SECTOR_START_ABS (BlockData, BlockChunk))
&& (Lba < (DMG_SECTOR_START_ABS (BlockData, BlockChunk) + BlockChunk->SectorCount))) {
*Data = BlockData;
*Chunk = BlockChunk;
return TRUE;
}
}
}
}
return FALSE;
}

View File

@ -0,0 +1,48 @@
/** @file
Copyright (C) 2019, Goldfish64. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
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 APPLE_DISK_IMAGE_LIB_INTERNAL_H
#define APPLE_DISK_IMAGE_LIB_INTERNAL_H
#define BASE_256B 0x0100U
#define SIZE_512B 0x0200U
#define DMG_SECTOR_START_ABS(b, c) (((b)->SectorNumber) + ((c)->SectorNumber))
#define DMG_PLIST_RESOURCE_FORK_KEY "resource-fork"
#define DMG_PLIST_BLOCK_LIST_KEY "blkx"
#define DMG_PLIST_ATTRIBUTES "Attributes"
#define DMG_PLIST_CFNAME "CFName"
#define DMG_PLIST_DATA "Data"
#define DMG_PLIST_ID "ID"
#define DMG_PLIST_NAME "Name"
BOOLEAN
InternalParsePlist (
IN CHAR8 *Plist,
IN UINT32 PlistSize,
IN UINTN SectorCount,
IN UINTN DataForkOffset,
IN UINTN DataForkSize,
OUT UINT32 *BlockCount,
OUT APPLE_DISK_IMAGE_BLOCK_DATA ***Blocks
);
BOOLEAN
InternalGetBlockChunk (
IN OC_APPLE_DISK_IMAGE_CONTEXT *Context,
IN UINTN Lba,
OUT APPLE_DISK_IMAGE_BLOCK_DATA **Data,
OUT APPLE_DISK_IMAGE_CHUNK **Chunk
);
#endif // APPLE_DISK_IMAGE_LIB_INTERNAL_H

Some files were not shown because too many files have changed in this diff Show More