summaryrefslogtreecommitdiff
path: root/Core/IntelFrameworkModulePkg/Universal
diff options
context:
space:
mode:
Diffstat (limited to 'Core/IntelFrameworkModulePkg/Universal')
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c204
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.h59
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.inf81
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.uni22
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c222
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.c91
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.h166
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportAcpiSupportProtocol.c1918
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.inf81
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.uni24
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxeExtra.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Bds.h237
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.inf229
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.uni33
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c736
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.c254
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.h82
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bm.vfr365
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BmLib.c411
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bmstring.uni263
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.c1690
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.h1679
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c1823
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/ConsoleOption.c1198
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Data.c332
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FE.vfr127
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FileExplorer.c469
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FormGuid.h243
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/UpdatePage.c1413
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Variable.c1380
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.c399
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.h103
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerStrings.uni33
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerVfr.Vfr50
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Capsules.c233
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.c2605
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.h523
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerStrings.uni96
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.Vfr93
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.h56
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DriverHealthVfr.Vfr38
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.c1487
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.h254
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageStrings.uni70
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageVfr.Vfr137
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.c597
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.h67
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.c48
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.h32
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.c499
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.h51
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/MemoryTest.c436
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.c59
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.h65
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/BdsDxe/Strings.uni55
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/ComponentName.c167
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.c1288
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.h484
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.inf64
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.uni22
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.c588
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.h226
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.inf51
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxeExtra.uni19
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.c587
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.h129
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.inf81
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.uni39
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxeExtra.uni19
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErr.c151
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.inf57
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxeExtra.uni19
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/Ffs.c608
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwPadFile.c1228
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVol.c798
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolAttrib.c220
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDriver.h761
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.inf74
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.uni23
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolRead.c632
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolWrite.c1586
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/FlashUpdate.c1218
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/ParseUpdateProfile.c1133
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDispatcher.c846
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriver.h213
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.inf76
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.uni24
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateStrings.uni25
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegion.c170
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.inf55
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.uni26
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtraction.c1456
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.inf57
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.uni24
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxeExtra.uni20
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DataHubStatusCodeWorker.c376
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.c88
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.h91
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.inf72
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxeExtra.uni19
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/MemoryStausCodeWorker.c118
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/SerialStatusCodeWorker.c162
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.c146
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.h147
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf78
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePeiExtra.uni19
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/DataHubStatusCodeWorker.c390
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/RtMemoryStatusCodeWorker.c104
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/SerialStatusCodeWorker.c160
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.c301
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.h231
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.inf88
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.uni21
-rw-r--r--Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxeExtra.uni19
124 files changed, 42037 insertions, 0 deletions
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c
new file mode 100644
index 0000000000..e03101cab8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c
@@ -0,0 +1,204 @@
+/** @file
+ This is an implementation of the ACPI S3 Save protocol. This is defined in
+ S3 boot path specification 0.9.
+
+Copyright (c) 2006 - 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.
+
+**/
+
+#include <PiDxe.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+#include <Protocol/AcpiS3Save.h>
+
+#include "AcpiS3Save.h"
+
+/**
+ Hook point for AcpiVariableThunkPlatform for InstallAcpiS3Save.
+**/
+VOID
+InstallAcpiS3SaveThunk (
+ VOID
+ );
+
+/**
+ Hook point for AcpiVariableThunkPlatform for S3Ready.
+
+**/
+VOID
+S3ReadyThunkPlatform (
+ VOID
+ );
+
+UINTN mLegacyRegionSize;
+
+EFI_ACPI_S3_SAVE_PROTOCOL mS3Save = {
+ LegacyGetS3MemorySize,
+ S3Ready,
+};
+
+/**
+ Allocate memory below 4G memory address.
+
+ This function allocates memory below 4G memory address.
+
+ @param MemoryType Memory type of memory to allocate.
+ @param Size Size of memory to allocate.
+
+ @return Allocated address for output.
+
+**/
+VOID*
+AllocateMemoryBelow4G (
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Size
+ )
+{
+ UINTN Pages;
+ EFI_PHYSICAL_ADDRESS Address;
+ EFI_STATUS Status;
+ VOID* Buffer;
+
+ Pages = EFI_SIZE_TO_PAGES (Size);
+ Address = 0xffffffff;
+
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ MemoryType,
+ Pages,
+ &Address
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ Buffer = (VOID *) (UINTN) Address;
+ ZeroMem (Buffer, Size);
+
+ return Buffer;
+}
+
+/**
+ Gets the buffer of legacy memory below 1 MB
+ This function is to get the buffer in legacy memory below 1MB that is required during S3 resume.
+
+ @param This A pointer to the EFI_ACPI_S3_SAVE_PROTOCOL instance.
+ @param Size The returned size of legacy memory below 1 MB.
+
+ @retval EFI_SUCCESS Size is successfully returned.
+ @retval EFI_INVALID_PARAMETER The pointer Size is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyGetS3MemorySize (
+ IN EFI_ACPI_S3_SAVE_PROTOCOL *This,
+ OUT UINTN *Size
+ )
+{
+ if (Size == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *Size = mLegacyRegionSize;
+ return EFI_SUCCESS;
+}
+
+/**
+ Prepares all information that is needed in the S3 resume boot path.
+
+ Allocate the resources or prepare informations and save in ACPI variable set for S3 resume boot path
+
+ @param This A pointer to the EFI_ACPI_S3_SAVE_PROTOCOL instance.
+ @param LegacyMemoryAddress The base address of legacy memory.
+
+ @retval EFI_NOT_FOUND Some necessary information cannot be found.
+ @retval EFI_SUCCESS All information was saved successfully.
+ @retval EFI_OUT_OF_RESOURCES Resources were insufficient to save all the information.
+ @retval EFI_INVALID_PARAMETER The memory range is not located below 1 MB.
+
+**/
+EFI_STATUS
+EFIAPI
+S3Ready (
+ IN EFI_ACPI_S3_SAVE_PROTOCOL *This,
+ IN VOID *LegacyMemoryAddress
+ )
+{
+ STATIC BOOLEAN AlreadyEntered;
+
+ DEBUG ((EFI_D_INFO, "S3Ready!\n"));
+
+ //
+ // Platform may invoke AcpiS3Save->S3Save() before ExitPmAuth, because we need save S3 information there, while BDS ReadyToBoot may invoke it again.
+ // So if 2nd S3Save() is triggered later, we need ignore it.
+ //
+ if (AlreadyEntered) {
+ return EFI_SUCCESS;
+ }
+ AlreadyEntered = TRUE;
+
+ if (FeaturePcdGet(PcdFrameworkCompatibilitySupport)) {
+ S3ReadyThunkPlatform ();
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The Driver Entry Point.
+
+ The function is the driver Entry point which will produce AcpiS3SaveProtocol.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_SUCCESS Driver initialized successfully
+ @retval EFI_UNSUPPORTED Do not support ACPI S3
+ @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources
+
+**/
+EFI_STATUS
+EFIAPI
+InstallAcpiS3Save (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ if (!PcdGetBool (PcdAcpiS3Enable)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ if (!FeaturePcdGet(PcdPlatformCsmSupport)) {
+ //
+ // More memory for no CSM tip, because GDT need relocation
+ //
+ mLegacyRegionSize = 0x250;
+ } else {
+ mLegacyRegionSize = 0x100;
+ }
+
+ if (FeaturePcdGet(PcdFrameworkCompatibilitySupport)) {
+ InstallAcpiS3SaveThunk ();
+ }
+
+ Status = gBS->InstallProtocolInterface (
+ &ImageHandle,
+ &gEfiAcpiS3SaveProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &mS3Save
+ );
+ ASSERT_EFI_ERROR (Status);
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.h b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.h
new file mode 100644
index 0000000000..65974a3402
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.h
@@ -0,0 +1,59 @@
+/** @file
+ This is an implementation of the ACPI S3 Save protocol. This is defined in
+ S3 boot path specification 0.9.
+
+Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+
+This program and the accompanying materials
+are licensed and made available under the terms and conditions
+of the BSD License which accompanies this distribution. The
+full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+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 _ACPI_S3_SAVE_H_
+#define _ACPI_S3_SAVE_H_
+
+/**
+ Gets the buffer of legacy memory below 1 MB
+ This function is to get the buffer in legacy memory below 1MB that is required during S3 resume.
+
+ @param This A pointer to the EFI_ACPI_S3_SAVE_PROTOCOL instance.
+ @param Size The returned size of legacy memory below 1 MB.
+
+ @retval EFI_SUCCESS Size is successfully returned.
+ @retval EFI_INVALID_PARAMETER The pointer Size is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyGetS3MemorySize (
+ IN EFI_ACPI_S3_SAVE_PROTOCOL * This,
+ OUT UINTN * Size
+ );
+
+/**
+ Prepares all information that is needed in the S3 resume boot path.
+
+ Allocate the resources or prepare informations and save in ACPI variable set for S3 resume boot path
+
+ @param This A pointer to the EFI_ACPI_S3_SAVE_PROTOCOL instance.
+ @param LegacyMemoryAddress The base address of legacy memory.
+
+ @retval EFI_NOT_FOUND Some necessary information cannot be found.
+ @retval EFI_SUCCESS All information was saved successfully.
+ @retval EFI_OUT_OF_RESOURCES Resources were insufficient to save all the information.
+ @retval EFI_INVALID_PARAMETER The memory range is not located below 1 MB.
+
+**/
+EFI_STATUS
+EFIAPI
+S3Ready (
+ IN EFI_ACPI_S3_SAVE_PROTOCOL *This,
+ IN VOID *LegacyMemoryAddress
+ );
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.inf b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.inf
new file mode 100644
index 0000000000..179aa82d8d
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.inf
@@ -0,0 +1,81 @@
+## @file
+# AcpiS3Save module installs ACPI S3 Save protocol to prepare S3 boot data.
+#
+# Copyright (c) 2006 - 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.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = AcpiS3SaveDxe
+ MODULE_UNI_FILE = AcpiS3SaveDxe.uni
+ FILE_GUID = 2BDED685-F733-455f-A840-43A22B791FB3
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = InstallAcpiS3Save
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ AcpiS3Save.h
+ AcpiS3Save.c
+ AcpiVariableThunkPlatform.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ PcdLib
+ UefiRuntimeServicesTableLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ BaseMemoryLib
+ HobLib
+ UefiLib
+ DebugLib
+
+[Guids]
+ ## SOMETIMES_CONSUMES ## Variable:L"AcpiGlobalVariable"
+ ## SOMETIMES_PRODUCES ## Variable:L"AcpiGlobalVariable"
+ gEfiAcpiVariableCompatiblityGuid
+
+[Protocols]
+ gEfiAcpiS3SaveProtocolGuid ## PRODUCES
+ gFrameworkEfiMpServiceProtocolGuid ## SOMETIMES_CONSUMES
+ ## NOTIFY
+ ## SOMETIMES_CONSUMES
+ gEdkiiVariableLockProtocolGuid
+
+[FeaturePcd]
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdPlatformCsmSupport ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFrameworkCompatibilitySupport ## CONSUMES
+
+[Pcd]
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdS3AcpiReservedMemorySize ## SOMETIMES_CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable ## CONSUMES
+
+[Depex]
+ #
+ # Note: the extra dependency of gEfiMpServiceProtocolGuid is to ensure that ACPI variable is set by MpDxe driver before
+ # AcpiS3SaveDxe module is executed.
+ #
+ gEfiVariableArchProtocolGuid AND gEfiVariableWriteArchProtocolGuid AND gEfiMpServiceProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ AcpiS3SaveDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.uni b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.uni
new file mode 100644
index 0000000000..7d4eed80a8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxe.uni
@@ -0,0 +1,22 @@
+// /** @file
+// AcpiS3Save module installs ACPI S3 Save protocol to prepare S3 boot data.
+//
+// AcpiS3Save module installs ACPI S3 Save protocol to prepare S3 boot data.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Installs ACPI S3 Save protocol to prepare S3 boot data"
+
+#string STR_MODULE_DESCRIPTION #language en-US "AcpiS3Save module installs ACPI S3 Save protocol to prepare S3 boot data."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxeExtra.uni
new file mode 100644
index 0000000000..0596a9dcf2
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3SaveDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// AcpiS3SaveDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"ACPI S3 Save State DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c
new file mode 100644
index 0000000000..105b142b28
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c
@@ -0,0 +1,222 @@
+/** @file
+ This is an implementation of the AcpiVariable platform field for ECP platform.
+
+Copyright (c) 2006 - 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.
+
+==
+
+typedef struct {
+ EFI_PHYSICAL_ADDRESS AcpiReservedMemoryBase; <<===
+ UINT32 AcpiReservedMemorySize; <<===
+ EFI_PHYSICAL_ADDRESS S3ReservedLowMemoryBase;
+ EFI_PHYSICAL_ADDRESS AcpiBootScriptTable;
+ EFI_PHYSICAL_ADDRESS RuntimeScriptTableBase;
+ EFI_PHYSICAL_ADDRESS AcpiFacsTable;
+ UINT64 SystemMemoryLength; <<===
+ ACPI_CPU_DATA_COMPATIBILITY AcpiCpuData;
+ EFI_PHYSICAL_ADDRESS VideoOpromAddress;
+ UINT32 VideoOpromSize;
+ EFI_PHYSICAL_ADDRESS S3DebugBufferAddress;
+ EFI_PHYSICAL_ADDRESS S3ResumeNvsEntryPoint;
+} ACPI_VARIABLE_SET_COMPATIBILITY;
+
+**/
+
+#include <FrameworkDxe.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/HobLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiLib.h>
+#include <Protocol/FrameworkMpService.h>
+#include <Protocol/VariableLock.h>
+#include <Guid/AcpiVariableCompatibility.h>
+
+GLOBAL_REMOVE_IF_UNREFERENCED
+ACPI_VARIABLE_SET_COMPATIBILITY *mAcpiVariableSetCompatibility = NULL;
+
+/**
+ Allocate memory below 4G memory address.
+
+ This function allocates memory below 4G memory address.
+
+ @param MemoryType Memory type of memory to allocate.
+ @param Size Size of memory to allocate.
+
+ @return Allocated address for output.
+
+**/
+VOID*
+AllocateMemoryBelow4G (
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Size
+ );
+
+/**
+ Hook point for AcpiVariableThunkPlatform for S3Ready.
+
+**/
+VOID
+S3ReadyThunkPlatform (
+ VOID
+ )
+{
+ EFI_PHYSICAL_ADDRESS AcpiMemoryBase;
+ UINT32 AcpiMemorySize;
+ EFI_PEI_HOB_POINTERS Hob;
+ UINT64 MemoryLength;
+
+ DEBUG ((EFI_D_INFO, "S3ReadyThunkPlatform\n"));
+
+ if (mAcpiVariableSetCompatibility == NULL) {
+ return;
+ }
+
+ //
+ // Allocate ACPI reserved memory under 4G
+ //
+ AcpiMemoryBase = (EFI_PHYSICAL_ADDRESS)(UINTN)AllocateMemoryBelow4G (EfiReservedMemoryType, PcdGet32 (PcdS3AcpiReservedMemorySize));
+ ASSERT (AcpiMemoryBase != 0);
+ AcpiMemorySize = PcdGet32 (PcdS3AcpiReservedMemorySize);
+
+ //
+ // Calculate the system memory length by memory hobs
+ //
+ MemoryLength = 0x100000;
+ Hob.Raw = GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR);
+ ASSERT (Hob.Raw != NULL);
+ while ((Hob.Raw != NULL) && (!END_OF_HOB_LIST (Hob))) {
+ if (Hob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) {
+ //
+ // Skip the memory region below 1MB
+ //
+ if (Hob.ResourceDescriptor->PhysicalStart >= 0x100000) {
+ MemoryLength += Hob.ResourceDescriptor->ResourceLength;
+ }
+ }
+ Hob.Raw = GET_NEXT_HOB (Hob);
+ Hob.Raw = GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, Hob.Raw);
+ }
+
+ mAcpiVariableSetCompatibility->AcpiReservedMemoryBase = AcpiMemoryBase;
+ mAcpiVariableSetCompatibility->AcpiReservedMemorySize = AcpiMemorySize;
+ mAcpiVariableSetCompatibility->SystemMemoryLength = MemoryLength;
+
+ DEBUG((EFI_D_INFO, "AcpiVariableThunkPlatform: AcpiMemoryBase is 0x%8x\n", mAcpiVariableSetCompatibility->AcpiReservedMemoryBase));
+ DEBUG((EFI_D_INFO, "AcpiVariableThunkPlatform: AcpiMemorySize is 0x%8x\n", mAcpiVariableSetCompatibility->AcpiReservedMemorySize));
+ DEBUG((EFI_D_INFO, "AcpiVariableThunkPlatform: SystemMemoryLength is 0x%8x\n", mAcpiVariableSetCompatibility->SystemMemoryLength));
+
+ return ;
+}
+
+/**
+ Register callback function upon VariableLockProtocol
+ to lock ACPI_GLOBAL_VARIABLE variable to avoid malicious code to update it.
+
+ @param[in] Event Event whose notification function is being invoked.
+ @param[in] Context Pointer to the notification function's context.
+**/
+VOID
+EFIAPI
+VariableLockAcpiGlobalVariable (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+ EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
+ //
+ // Mark ACPI_GLOBAL_VARIABLE variable to read-only if the Variable Lock protocol exists
+ //
+ Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
+ if (!EFI_ERROR (Status)) {
+ Status = VariableLock->RequestToLock (VariableLock, ACPI_GLOBAL_VARIABLE, &gEfiAcpiVariableCompatiblityGuid);
+ ASSERT_EFI_ERROR (Status);
+ }
+}
+
+/**
+ Hook point for AcpiVariableThunkPlatform for InstallAcpiS3Save.
+**/
+VOID
+InstallAcpiS3SaveThunk (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ FRAMEWORK_EFI_MP_SERVICES_PROTOCOL *FrameworkMpService;
+ UINTN VarSize;
+ VOID *Registration;
+
+ Status = gBS->LocateProtocol (
+ &gFrameworkEfiMpServiceProtocolGuid,
+ NULL,
+ (VOID**) &FrameworkMpService
+ );
+ if (!EFI_ERROR (Status)) {
+ //
+ // On ECP platform, if framework CPU drivers are in use, The compatible version of ACPI variable set
+ // should be produced by CPU driver.
+ //
+ VarSize = sizeof (mAcpiVariableSetCompatibility);
+ Status = gRT->GetVariable (
+ ACPI_GLOBAL_VARIABLE,
+ &gEfiAcpiVariableCompatiblityGuid,
+ NULL,
+ &VarSize,
+ &mAcpiVariableSetCompatibility
+ );
+ if (EFI_ERROR (Status) || (VarSize != sizeof (mAcpiVariableSetCompatibility))) {
+ DEBUG ((EFI_D_ERROR, "FATAL ERROR: AcpiVariableSetCompatibility was not saved by CPU driver correctly. OS S3 may fail!\n"));
+ mAcpiVariableSetCompatibility = NULL;
+ }
+ } else {
+ //
+ // Allocate/initialize the compatible version of Acpi Variable Set since Framework chipset/platform
+ // driver need this variable. ACPI_GLOBAL_VARIABLE variable is not used in runtime phase,
+ // so RT attribute is not needed for it.
+ //
+ mAcpiVariableSetCompatibility = AllocateMemoryBelow4G (EfiACPIMemoryNVS, sizeof(ACPI_VARIABLE_SET_COMPATIBILITY));
+ Status = gRT->SetVariable (
+ ACPI_GLOBAL_VARIABLE,
+ &gEfiAcpiVariableCompatiblityGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof(mAcpiVariableSetCompatibility),
+ &mAcpiVariableSetCompatibility
+ );
+ if (!EFI_ERROR (Status)) {
+ //
+ // Register callback function upon VariableLockProtocol
+ // to lock ACPI_GLOBAL_VARIABLE variable to avoid malicious code to update it.
+ //
+ EfiCreateProtocolNotifyEvent (
+ &gEdkiiVariableLockProtocolGuid,
+ TPL_CALLBACK,
+ VariableLockAcpiGlobalVariable,
+ NULL,
+ &Registration
+ );
+ } else {
+ DEBUG ((EFI_D_ERROR, "FATAL ERROR: AcpiVariableSetCompatibility cannot be saved: %r. OS S3 may fail!\n", Status));
+ gBS->FreePages (
+ (EFI_PHYSICAL_ADDRESS) (UINTN) mAcpiVariableSetCompatibility,
+ EFI_SIZE_TO_PAGES (sizeof (ACPI_VARIABLE_SET_COMPATIBILITY))
+ );
+ mAcpiVariableSetCompatibility = NULL;
+ }
+ }
+
+ DEBUG((EFI_D_INFO, "AcpiVariableSetCompatibility is 0x%8x\n", mAcpiVariableSetCompatibility));
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.c b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.c
new file mode 100644
index 0000000000..a8b1f06117
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.c
@@ -0,0 +1,91 @@
+/** @file
+ This is an implementation of the ACPI Support protocol. This is defined in
+ the Tiano ACPI External Product Specification, revision 0.3.6.
+
+Copyright (c) 2006 - 2010, 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.
+
+**/
+
+//
+// Includes
+//
+#include "AcpiSupport.h"
+
+//
+// Handle to install ACPI Table Protocol (and ACPI Suppport protocol).
+//
+EFI_HANDLE mHandle = NULL;
+
+/**
+ Entry point of the ACPI support driver. This function creates and initializes an instance of the ACPI Support
+ Protocol and installs it on a new handle.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_SUCCESS Driver initialized successfully
+ @retval EFI_LOAD_ERROR Failed to Initialize or has been loaded
+ @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources
+**/
+EFI_STATUS
+EFIAPI
+InstallAcpiSupport (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+
+{
+ EFI_STATUS Status;
+ EFI_ACPI_SUPPORT_INSTANCE *PrivateData;
+
+ //
+ // Initialize our protocol
+ //
+ PrivateData = AllocateZeroPool (sizeof (EFI_ACPI_SUPPORT_INSTANCE));
+ ASSERT (PrivateData);
+ PrivateData->Signature = EFI_ACPI_SUPPORT_SIGNATURE;
+
+ //
+ // Call all constructors per produced protocols
+ //
+ Status = AcpiSupportAcpiSupportConstructor (PrivateData);
+ if (EFI_ERROR (Status)) {
+ gBS->FreePool (PrivateData);
+ return EFI_LOAD_ERROR;
+ }
+
+ //
+ // Install ACPI Table protocol and optional ACPI support protocol based on
+ // feature flag: PcdInstallAcpiSupportProtocol.
+ //
+ if (FeaturePcdGet (PcdInstallAcpiSupportProtocol)) {
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &mHandle,
+ &gEfiAcpiTableProtocolGuid,
+ &PrivateData->AcpiTableProtocol,
+ &gEfiAcpiSupportProtocolGuid,
+ &PrivateData->AcpiSupport,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+ } else {
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &mHandle,
+ &gEfiAcpiTableProtocolGuid,
+ &PrivateData->AcpiTableProtocol,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.h b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.h
new file mode 100644
index 0000000000..1bcf1e6ee5
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupport.h
@@ -0,0 +1,166 @@
+/** @file
+ This is an implementation of the ACPI Support protocol.
+ It is in compliance with the 0.9 definition of the protocol.
+
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
+
+This program and the accompanying materials
+are licensed and made available under the terms and conditions
+of the BSD License which accompanies this distribution. The
+full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+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 _ACPI_SUPPORT_H_
+#define _ACPI_SUPPORT_H_
+
+
+#include <PiDxe.h>
+
+#include <Protocol/AcpiTable.h>
+#include <Guid/Acpi.h>
+#include <Protocol/AcpiSupport.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/PcdLib.h>
+
+//
+// Statements that include other files
+//
+#include <IndustryStandard/Acpi.h>
+
+
+//
+// Private Driver Data
+//
+//
+// ACPI Table Linked List Signature.
+//
+#define EFI_ACPI_TABLE_LIST_SIGNATURE SIGNATURE_32 ('E', 'A', 'T', 'L')
+
+//
+// ACPI Table Linked List Entry definition.
+//
+// Signature must be set to EFI_ACPI_TABLE_LIST_SIGNATURE
+// Link is the linked list data.
+// Version is the versions of the ACPI tables that this table belongs in.
+// Table is a pointer to the table.
+// PageAddress is the address of the pages allocated for the table.
+// NumberOfPages is the number of pages allocated at PageAddress.
+// Handle is used to identify a particular table.
+//
+typedef struct {
+ UINT32 Signature;
+ LIST_ENTRY Link;
+ EFI_ACPI_TABLE_VERSION Version;
+ EFI_ACPI_COMMON_HEADER *Table;
+ EFI_PHYSICAL_ADDRESS PageAddress;
+ UINTN NumberOfPages;
+ UINTN Handle;
+} EFI_ACPI_TABLE_LIST;
+
+//
+// Containment record for linked list.
+//
+#define EFI_ACPI_TABLE_LIST_FROM_LINK(_link) CR (_link, EFI_ACPI_TABLE_LIST, Link, EFI_ACPI_TABLE_LIST_SIGNATURE)
+
+//
+// The maximum number of tables this driver supports
+//
+#define EFI_ACPI_MAX_NUM_TABLES 20
+
+//
+// Protocol private structure definition
+//
+//
+// ACPI support protocol instance signature definition.
+//
+#define EFI_ACPI_SUPPORT_SIGNATURE SIGNATURE_32 ('S', 'S', 'A', 'E')
+
+//
+// ACPI support protocol instance data structure
+//
+typedef struct {
+ UINTN Signature;
+ EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER *Rsdp1; // Pointer to RSD_PTR structure
+ EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER *Rsdp3; // Pointer to RSD_PTR structure
+ EFI_ACPI_DESCRIPTION_HEADER *Rsdt1; // Pointer to RSDT table header
+ EFI_ACPI_DESCRIPTION_HEADER *Rsdt3; // Pointer to RSDT table header
+ EFI_ACPI_DESCRIPTION_HEADER *Xsdt; // Pointer to XSDT table header
+ EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE *Fadt1; // Pointer to FADT table header
+ EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *Fadt3; // Pointer to FADT table header
+ EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs1; // Pointer to FACS table header
+ EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs3; // Pointer to FACS table header
+ EFI_ACPI_DESCRIPTION_HEADER *Dsdt1; // Pointer to DSDT table header
+ EFI_ACPI_DESCRIPTION_HEADER *Dsdt3; // Pointer to DSDT table header
+ LIST_ENTRY TableList;
+ UINTN NumberOfTableEntries1; // Number of ACPI 1.0 tables
+ UINTN NumberOfTableEntries3; // Number of ACPI 3.0 tables
+ UINTN CurrentHandle;
+ BOOLEAN TablesInstalled1; // ACPI 1.0 tables published
+ BOOLEAN TablesInstalled3; // ACPI 3.0 tables published
+ EFI_ACPI_SUPPORT_PROTOCOL AcpiSupport;
+ EFI_ACPI_TABLE_PROTOCOL AcpiTableProtocol;
+} EFI_ACPI_SUPPORT_INSTANCE;
+
+//
+// ACPI support protocol instance containing record macro
+//
+#define EFI_ACPI_SUPPORT_INSTANCE_FROM_ACPI_SUPPORT_THIS(a) \
+ CR (a, \
+ EFI_ACPI_SUPPORT_INSTANCE, \
+ AcpiSupport, \
+ EFI_ACPI_SUPPORT_SIGNATURE \
+ )
+//
+// ACPI table protocol instance containing record macro
+//
+#define EFI_ACPI_TABLE_INSTANCE_FROM_ACPI_SUPPORT_THIS(a) \
+ CR (a, \
+ EFI_ACPI_SUPPORT_INSTANCE, \
+ AcpiTableProtocol, \
+ EFI_ACPI_SUPPORT_SIGNATURE \
+ )
+
+/**
+ Constructor for the ACPI support protocol.
+
+ Constructor for the ACPI support protocol to initializes instance data.
+
+ @param AcpiSupportInstance Instance to construct
+
+ @retval EFI_SUCCESS Instance initialized.
+ @retval EFI_OUT_OF_RESOURCES Unable to allocate required resources.
+**/
+EFI_STATUS
+AcpiSupportAcpiSupportConstructor (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance
+ );
+/**
+ Entry point of the ACPI support driver. This function creates and initializes an instance of the ACPI Support
+ Protocol and installs it on a new handle.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_SUCCESS Driver initialized successfully
+ @retval EFI_LOAD_ERROR Failed to Initialize or has been loaded
+ @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources
+**/
+EFI_STATUS
+EFIAPI
+InstallAcpiSupport (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ );
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportAcpiSupportProtocol.c b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportAcpiSupportProtocol.c
new file mode 100644
index 0000000000..6443c3acd0
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportAcpiSupportProtocol.c
@@ -0,0 +1,1918 @@
+/** @file
+ ACPI Support Protocol implementation
+
+Copyright (c) 2006 - 2014, 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.
+
+**/
+
+//
+// Includes
+//
+#include "AcpiSupport.h"
+//
+// The maximum number of tables that pre-allocated.
+//
+UINTN mEfiAcpiMaxNumTables = EFI_ACPI_MAX_NUM_TABLES;
+/**
+ This function adds an ACPI table to the table list. It will detect FACS and
+ allocate the correct type of memory and properly align the table.
+
+ @param AcpiSupportInstance Instance of the protocol.
+ @param Table Table to add.
+ @param Checksum Does the table require checksumming.
+ @param Version The version of the list to add the table to.
+ @param Handle Pointer for returning the handle.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_OUT_OF_RESOURCES Could not allocate a required resource.
+ @return EFI_ABORTED The table is a duplicate of a table that is required
+ to be unique.
+**/
+EFI_STATUS
+AddTableToList (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance,
+ IN VOID *Table,
+ IN BOOLEAN Checksum,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ OUT UINTN *Handle
+ );
+/**
+ This function finds and removes the table specified by the handle.
+
+ @param AcpiSupportInstance Instance of the protocol.
+ @param Version Bitmask of which versions to remove.
+ @param Handle Table to remove.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_ABORTED An error occurred.
+ @return EFI_NOT_FOUND Handle not found in table list.
+**/
+EFI_STATUS
+RemoveTableFromList (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ IN UINTN Handle
+ );
+/**
+ This function calculates and updates an UINT8 checksum.
+
+ @param Buffer Pointer to buffer to checksum
+ @param Size Number of bytes to checksum
+ @param ChecksumOffset Offset to place the checksum result in
+
+ @return EFI_SUCCESS The function completed successfully.
+**/
+EFI_STATUS
+AcpiPlatformChecksum (
+ IN VOID *Buffer,
+ IN UINTN Size,
+ IN UINTN ChecksumOffset
+ );
+/**
+ Checksum all versions of the common tables, RSDP, RSDT, XSDT.
+
+ @param AcpiSupportInstance Protocol instance private data.
+
+ @return EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+ChecksumCommonTables (
+ IN OUT EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance
+ );
+
+/**
+ This function returns a table specified by an index if it exists.
+
+ The function returns a buffer containing the table that the caller must free.
+ The function also returns a handle used to identify the table for update or
+ deletion using the SetAcpiTable function.
+
+ @param This Instance of the protocol.
+ @param Index Zero-based index of the table to retrieve.
+ @param Table Returned pointer to the table.
+ @param Version Versions that the table is currently used in.
+ @param Handle Handle of the table, used in updating tables.
+
+ @retval EFI_SUCCESS The function completed successfully.
+ @retval EFI_NOT_FOUND The requested table does not exist.
+
+**/
+EFI_STATUS
+EFIAPI
+GetAcpiTable (
+ IN EFI_ACPI_SUPPORT_PROTOCOL *This,
+ IN INTN Index,
+ OUT VOID **Table,
+ OUT EFI_ACPI_TABLE_VERSION *Version,
+ OUT UINTN *Handle
+ )
+
+{
+ EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance;
+ INTN TempIndex;
+ LIST_ENTRY *CurrentLink;
+ LIST_ENTRY *StartLink;
+ EFI_ACPI_TABLE_LIST *CurrentTable;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (This);
+ ASSERT (Table);
+ ASSERT (Handle);
+
+ //
+ // Get the instance of the protocol
+ //
+ AcpiSupportInstance = EFI_ACPI_SUPPORT_INSTANCE_FROM_ACPI_SUPPORT_THIS (This);
+
+ //
+ // Find the table
+ //
+ CurrentLink = AcpiSupportInstance->TableList.ForwardLink;
+ StartLink = &AcpiSupportInstance->TableList;
+ for (TempIndex = 0; (TempIndex < Index) && (CurrentLink != StartLink) && (CurrentLink != NULL); TempIndex++) {
+ CurrentLink = CurrentLink->ForwardLink;
+ }
+
+ if (TempIndex != Index || CurrentLink == StartLink) {
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Get handle and version
+ //
+ CurrentTable = EFI_ACPI_TABLE_LIST_FROM_LINK (CurrentLink);
+ *Handle = CurrentTable->Handle;
+ *Version = CurrentTable->Version;
+
+ //
+ // Copy the table
+ //
+ *Table = AllocateCopyPool (CurrentTable->Table->Length, CurrentTable->Table);
+ ASSERT (*Table);
+
+ return EFI_SUCCESS;
+}
+/**
+ This function adds, removes, or updates ACPI tables. If the address is not
+ null and the handle value is null, the table is added. If both the address and
+ handle are not null, the table at handle is updated with the table at address.
+ If the address is null and the handle is not, the table at handle is deleted.
+
+ @param This Pointer of the protocol.
+ @param Table Pointer to a table.
+ @param Checksum Boolean indicating if the checksum should be calculated.
+ @param Version Version(s) to set.
+ @param Handle Handle of the table.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_INVALID_PARAMETER Both the Table and *Handle were NULL.
+ @return EFI_ABORTED Could not complete the desired request.
+
+**/
+EFI_STATUS
+EFIAPI
+SetAcpiTable (
+ IN EFI_ACPI_SUPPORT_PROTOCOL *This,
+ IN VOID *Table OPTIONAL,
+ IN BOOLEAN Checksum,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ IN OUT UINTN *Handle
+ )
+{
+ EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance;
+ UINTN SavedHandle;
+ EFI_STATUS Status;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (This);
+ ASSERT (Handle != NULL);
+
+ //
+ // Get the instance of the protocol
+ //
+ AcpiSupportInstance = EFI_ACPI_SUPPORT_INSTANCE_FROM_ACPI_SUPPORT_THIS (This);
+
+ //
+ // Initialize locals
+ //
+ //
+ // Determine desired action
+ //
+ if (*Handle == 0) {
+ if (Table == NULL) {
+ //
+ // Invalid parameter combination
+ //
+ return EFI_INVALID_PARAMETER;
+ } else {
+ //
+ // Add table
+ //
+ Status = AddTableToList (AcpiSupportInstance, Table, Checksum, Version, Handle);
+ }
+ } else {
+ if (Table != NULL) {
+ //
+ // Update table
+ //
+ //
+ // Delete the table list entry
+ //
+ Status = RemoveTableFromList (AcpiSupportInstance, Version, *Handle);
+ if (EFI_ERROR (Status)) {
+ //
+ // Should not get an error here ever, but abort if we do.
+ //
+ return EFI_ABORTED;
+ }
+ //
+ // Set the handle to replace the table at the same handle
+ //
+ SavedHandle = AcpiSupportInstance->CurrentHandle;
+ AcpiSupportInstance->CurrentHandle = *Handle;
+
+ //
+ // Add the table
+ //
+ Status = AddTableToList (AcpiSupportInstance, Table, Checksum, Version, Handle);
+
+ //
+ // Restore the saved current handle
+ //
+ AcpiSupportInstance->CurrentHandle = SavedHandle;
+ } else {
+ //
+ // Delete table
+ //
+ Status = RemoveTableFromList (AcpiSupportInstance, Version, *Handle);
+ }
+ }
+
+ if (EFI_ERROR (Status)) {
+ //
+ // Should not get an error here ever, but abort if we do.
+ //
+ return EFI_ABORTED;
+ }
+ //
+ // Done
+ //
+ return EFI_SUCCESS;
+}
+/**
+ This function publishes the specified versions of the ACPI tables by
+ installing EFI configuration table entries for them. Any combination of
+ table versions can be published.
+
+ @param This Pointer of the protocol.
+ @param Version Version(s) to publish.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_ABORTED The function could not complete successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+PublishTables (
+ IN EFI_ACPI_SUPPORT_PROTOCOL *This,
+ IN EFI_ACPI_TABLE_VERSION Version
+ )
+{
+ EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance;
+ EFI_STATUS Status;
+ UINT32 *CurrentRsdtEntry;
+ VOID *CurrentXsdtEntry;
+ UINT64 Buffer64;
+
+ //
+ // Get the instance of the protocol
+ //
+ AcpiSupportInstance = EFI_ACPI_SUPPORT_INSTANCE_FROM_ACPI_SUPPORT_THIS (This);
+
+ //
+ // Reorder tables as some operating systems don't seem to find the
+ // FADT correctly if it is not in the first few entries
+ //
+
+ //
+ // Add FADT as the first entry
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ CurrentRsdtEntry = (UINT32 *) ((UINT8 *) AcpiSupportInstance->Rsdt1 + sizeof (EFI_ACPI_DESCRIPTION_HEADER));
+ *CurrentRsdtEntry = (UINT32) (UINTN) AcpiSupportInstance->Fadt1;
+ }
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 || (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ CurrentRsdtEntry = (UINT32 *) ((UINT8 *) AcpiSupportInstance->Rsdt3 + sizeof (EFI_ACPI_DESCRIPTION_HEADER));
+ *CurrentRsdtEntry = (UINT32) (UINTN) AcpiSupportInstance->Fadt3;
+ CurrentXsdtEntry = (VOID *) ((UINT8 *) AcpiSupportInstance->Xsdt + sizeof (EFI_ACPI_DESCRIPTION_HEADER));
+ //
+ // Add entry to XSDT, XSDT expects 64 bit pointers, but
+ // the table pointers in XSDT are not aligned on 8 byte boundary.
+ //
+ Buffer64 = (UINT64) (UINTN) AcpiSupportInstance->Fadt3;
+ CopyMem (
+ CurrentXsdtEntry,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+ }
+
+ //
+ // Do checksum again because Dsdt/Xsdt is updated.
+ //
+ ChecksumCommonTables (AcpiSupportInstance);
+
+ //
+ // Add the RSD_PTR to the system table and store that we have installed the
+ // tables.
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0 && !AcpiSupportInstance->TablesInstalled1) {
+ Status = gBS->InstallConfigurationTable (&gEfiAcpi10TableGuid, AcpiSupportInstance->Rsdp1);
+ if (EFI_ERROR (Status)) {
+ return EFI_ABORTED;
+ }
+
+ AcpiSupportInstance->TablesInstalled1 = TRUE;
+ }
+
+ if (((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 || (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) &&
+ !AcpiSupportInstance->TablesInstalled3) {
+ Status = gBS->InstallConfigurationTable (&gEfiAcpiTableGuid, AcpiSupportInstance->Rsdp3);
+ if (EFI_ERROR (Status)) {
+ return EFI_ABORTED;
+ }
+
+ AcpiSupportInstance->TablesInstalled3= TRUE;
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Installs an ACPI table into the RSDT/XSDT.
+ Note that the ACPI table should be checksumed before installing it.
+ Otherwise it will assert.
+
+ @param This Protocol instance pointer.
+ @param AcpiTableBuffer A pointer to a buffer containing the ACPI table to be installed.
+ @param AcpiTableBufferSize Specifies the size, in bytes, of the AcpiTableBuffer buffer.
+ @param TableKey Reurns a key to refer to the ACPI table.
+
+ @return EFI_SUCCESS The table was successfully inserted.
+ @return EFI_INVALID_PARAMETER Either AcpiTableBuffer is NULL, TableKey is NULL, or AcpiTableBufferSize
+ and the size field embedded in the ACPI table pointed to by AcpiTableBuffer
+ are not in sync.
+ @return EFI_OUT_OF_RESOURCES Insufficient resources exist to complete the request.
+ @retval EFI_ACCESS_DENIED The table signature matches a table already
+ present in the system and platform policy
+ does not allow duplicate tables of this type.
+
+**/
+EFI_STATUS
+EFIAPI
+InstallAcpiTable (
+ IN EFI_ACPI_TABLE_PROTOCOL *This,
+ IN VOID *AcpiTableBuffer,
+ IN UINTN AcpiTableBufferSize,
+ OUT UINTN *TableKey
+ )
+{
+ EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance;
+ EFI_ACPI_SUPPORT_PROTOCOL *AcpiSupport;
+ EFI_STATUS Status;
+ VOID *AcpiTableBufferConst;
+
+ //
+ // Check for invalid input parameters
+ //
+ if ((AcpiTableBuffer == NULL) || (TableKey == NULL)
+ || (((EFI_ACPI_DESCRIPTION_HEADER *) AcpiTableBuffer)->Length != AcpiTableBufferSize)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Get the instance of the ACPI support protocol
+ //
+ AcpiSupportInstance = EFI_ACPI_TABLE_INSTANCE_FROM_ACPI_SUPPORT_THIS (This);
+ AcpiSupport = &AcpiSupportInstance->AcpiSupport;
+
+ //
+ // Install the ACPI table by using ACPI support protocol
+ //
+ AcpiTableBufferConst = AllocateCopyPool (AcpiTableBufferSize, AcpiTableBuffer);
+ *TableKey = 0;
+ Status = AddTableToList (
+ AcpiSupportInstance,
+ AcpiTableBufferConst,
+ TRUE,
+ EFI_ACPI_TABLE_VERSION_1_0B | EFI_ACPI_TABLE_VERSION_2_0 | EFI_ACPI_TABLE_VERSION_3_0,
+ TableKey
+ );
+ if (!EFI_ERROR (Status)) {
+ Status = AcpiSupport->PublishTables (
+ AcpiSupport,
+ EFI_ACPI_TABLE_VERSION_1_0B | EFI_ACPI_TABLE_VERSION_2_0 | EFI_ACPI_TABLE_VERSION_3_0
+ );
+ }
+ FreePool (AcpiTableBufferConst);
+
+ return Status;
+}
+/**
+ Removes an ACPI table from the RSDT/XSDT.
+
+ @param This Protocol instance pointer.
+ @param TableKey Specifies the table to uninstall. The key was returned from InstallAcpiTable().
+
+ @return EFI_SUCCESS The table was successfully uninstalled.
+ @return EFI_NOT_FOUND TableKey does not refer to a valid key for a table entry.
+
+**/
+EFI_STATUS
+EFIAPI
+UninstallAcpiTable (
+ IN EFI_ACPI_TABLE_PROTOCOL *This,
+ IN UINTN TableKey
+ )
+{
+ EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance;
+ EFI_ACPI_SUPPORT_PROTOCOL *AcpiSupport;
+ EFI_STATUS Status;
+
+ //
+ // Get the instance of the ACPI support protocol
+ //
+ AcpiSupportInstance = EFI_ACPI_TABLE_INSTANCE_FROM_ACPI_SUPPORT_THIS (This);
+ AcpiSupport = &AcpiSupportInstance->AcpiSupport;
+
+ //
+ // Uninstall the ACPI table by using ACPI support protocol
+ //
+ Status = RemoveTableFromList (
+ AcpiSupportInstance,
+ EFI_ACPI_TABLE_VERSION_1_0B | EFI_ACPI_TABLE_VERSION_2_0 | EFI_ACPI_TABLE_VERSION_3_0,
+ TableKey
+ );
+ if (!EFI_ERROR (Status)) {
+ Status = AcpiSupport->PublishTables (
+ AcpiSupport,
+ EFI_ACPI_TABLE_VERSION_1_0B | EFI_ACPI_TABLE_VERSION_2_0 | EFI_ACPI_TABLE_VERSION_3_0
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ } else {
+ return EFI_SUCCESS;
+ }
+}
+/**
+ If the number of APCI tables exceeds the preallocated max table number, enlarge the table buffer.
+
+ @param AcpiSupportInstance ACPI support protocol instance data structure
+
+ @return EFI_SUCCESS reallocate the table beffer successfully.
+ @return EFI_OUT_OF_RESOURCES Unable to allocate required resources.
+
+**/
+EFI_STATUS
+ReallocateAcpiTableBuffer (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance
+ )
+{
+ UINTN NewMaxTableNumber;
+ UINTN TotalSize;
+ UINT8 *Pointer;
+ EFI_PHYSICAL_ADDRESS PageAddress;
+ EFI_ACPI_SUPPORT_INSTANCE TempPrivateData;
+ EFI_STATUS Status;
+ UINT64 CurrentData;
+
+ CopyMem (&TempPrivateData, AcpiSupportInstance, sizeof (EFI_ACPI_SUPPORT_INSTANCE));
+ //
+ // Enlarge the max table number from mEfiAcpiMaxNumTables to mEfiAcpiMaxNumTables + EFI_ACPI_MAX_NUM_TABLES
+ //
+ NewMaxTableNumber = mEfiAcpiMaxNumTables + EFI_ACPI_MAX_NUM_TABLES;
+ //
+ // Create RSDT, XSDT structures and allocate buffers.
+ //
+ TotalSize = sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 1.0 RSDT
+ NewMaxTableNumber * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 RSDT
+ NewMaxTableNumber * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 XSDT
+ NewMaxTableNumber * sizeof (UINT64);
+
+ //
+ // Allocate memory in the lower 32 bit of address range for
+ // compatibility with ACPI 1.0 OS.
+ //
+ // This is done because ACPI 1.0 pointers are 32 bit values.
+ // ACPI 2.0 OS and all 64 bit OS must use the 64 bit ACPI table addresses.
+ // There is no architectural reason these should be below 4GB, it is purely
+ // for convenience of implementation that we force memory below 4GB.
+ //
+ PageAddress = 0xFFFFFFFF;
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiACPIReclaimMemory,
+ EFI_SIZE_TO_PAGES (TotalSize),
+ &PageAddress
+ );
+
+ if (EFI_ERROR (Status)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Pointer = (UINT8 *) (UINTN) PageAddress;
+ ZeroMem (Pointer, TotalSize);
+
+ AcpiSupportInstance->Rsdt1 = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+ Pointer += (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + NewMaxTableNumber * sizeof (UINT32));
+ AcpiSupportInstance->Rsdt3 = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+ Pointer += (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + NewMaxTableNumber * sizeof (UINT32));
+ AcpiSupportInstance->Xsdt = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+
+ //
+ // Update RSDP to point to the new Rsdt and Xsdt address.
+ //
+ AcpiSupportInstance->Rsdp1->RsdtAddress = (UINT32) (UINTN) AcpiSupportInstance->Rsdt1;
+ AcpiSupportInstance->Rsdp3->RsdtAddress = (UINT32) (UINTN) AcpiSupportInstance->Rsdt3;
+ CurrentData = (UINT64) (UINTN) AcpiSupportInstance->Xsdt;
+ CopyMem (&AcpiSupportInstance->Rsdp3->XsdtAddress, &CurrentData, sizeof (UINT64));
+
+ //
+ // copy the original Rsdt1, Rsdt3 and Xsdt structure to new buffer
+ //
+ CopyMem (AcpiSupportInstance->Rsdt1, TempPrivateData.Rsdt1, (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + mEfiAcpiMaxNumTables * sizeof (UINT32)));
+ CopyMem (AcpiSupportInstance->Rsdt3, TempPrivateData.Rsdt3, (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + mEfiAcpiMaxNumTables * sizeof (UINT32)));
+ CopyMem (AcpiSupportInstance->Xsdt, TempPrivateData.Xsdt, (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + mEfiAcpiMaxNumTables * sizeof (UINT64)));
+
+ //
+ // Calculate orignal ACPI table buffer size
+ //
+ TotalSize = sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 1.0 RSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 RSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 XSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT64);
+ gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)TempPrivateData.Rsdt1, EFI_SIZE_TO_PAGES (TotalSize));
+
+ //
+ // Update the Max ACPI table number
+ //
+ mEfiAcpiMaxNumTables = NewMaxTableNumber;
+ return EFI_SUCCESS;
+}
+/**
+ This function adds an ACPI table to the table list. It will detect FACS and
+ allocate the correct type of memory and properly align the table.
+
+ @param AcpiSupportInstance Instance of the protocol.
+ @param Table Table to add.
+ @param Checksum Does the table require checksumming.
+ @param Version The version of the list to add the table to.
+ @param Handle Pointer for returning the handle.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_OUT_OF_RESOURCES Could not allocate a required resource.
+ @retval EFI_ACCESS_DENIED The table signature matches a table already
+ present in the system and platform policy
+ does not allow duplicate tables of this type.
+**/
+EFI_STATUS
+AddTableToList (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance,
+ IN VOID *Table,
+ IN BOOLEAN Checksum,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ OUT UINTN *Handle
+ )
+{
+ EFI_STATUS Status;
+ EFI_ACPI_TABLE_LIST *CurrentTableList;
+ UINT32 CurrentTableSignature;
+ UINT32 CurrentTableSize;
+ UINT32 *CurrentRsdtEntry;
+ VOID *CurrentXsdtEntry;
+ UINT64 Buffer64;
+ BOOLEAN AddToRsdt;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (AcpiSupportInstance);
+ ASSERT (Table);
+ ASSERT (Handle);
+
+ //
+ // Init locals
+ //
+ AddToRsdt = TRUE;
+
+ //
+ // Create a new list entry
+ //
+ CurrentTableList = AllocatePool (sizeof (EFI_ACPI_TABLE_LIST));
+ ASSERT (CurrentTableList);
+
+ //
+ // Determine table type and size
+ //
+ CurrentTableSignature = ((EFI_ACPI_COMMON_HEADER *) Table)->Signature;
+ CurrentTableSize = ((EFI_ACPI_COMMON_HEADER *) Table)->Length;
+
+ //
+ // Allocate a buffer for the table. All tables are allocated in the lower 32 bits of address space
+ // for backwards compatibility with ACPI 1.0 OS.
+ //
+ // This is done because ACPI 1.0 pointers are 32 bit values.
+ // ACPI 2.0 OS and all 64 bit OS must use the 64 bit ACPI table addresses.
+ // There is no architectural reason these should be below 4GB, it is purely
+ // for convenience of implementation that we force memory below 4GB.
+ //
+ CurrentTableList->PageAddress = 0xFFFFFFFF;
+ CurrentTableList->NumberOfPages = EFI_SIZE_TO_PAGES (CurrentTableSize);
+
+ //
+ // Allocation memory type depends on the type of the table
+ //
+ if ((CurrentTableSignature == EFI_ACPI_2_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) ||
+ (CurrentTableSignature == EFI_ACPI_4_0_UEFI_ACPI_DATA_TABLE_SIGNATURE)) {
+ //
+ // Allocate memory for the FACS. This structure must be aligned
+ // on a 64 byte boundary and must be ACPI NVS memory.
+ // Using AllocatePages should ensure that it is always aligned.
+ // Do not change signature for new ACPI version because they are same.
+ //
+ // UEFI table also need to be in ACPI NVS memory, because some data field
+ // could be updated by OS present agent. For example, BufferPtrAddress in
+ // SMM communication ACPI table.
+ //
+ ASSERT ((EFI_PAGE_SIZE % 64) == 0);
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiACPIMemoryNVS,
+ CurrentTableList->NumberOfPages,
+ &CurrentTableList->PageAddress
+ );
+ } else {
+ //
+ // All other tables are ACPI reclaim memory, no alignment requirements.
+ //
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiACPIReclaimMemory,
+ CurrentTableList->NumberOfPages,
+ &CurrentTableList->PageAddress
+ );
+ }
+ //
+ // Check return value from memory alloc.
+ //
+ if (EFI_ERROR (Status)) {
+ gBS->FreePool (CurrentTableList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Update the table pointer with the allocated memory start
+ //
+ CurrentTableList->Table = (EFI_ACPI_COMMON_HEADER *) (UINTN) CurrentTableList->PageAddress;
+
+ //
+ // Initialize the table contents
+ //
+ CurrentTableList->Signature = EFI_ACPI_TABLE_LIST_SIGNATURE;
+ CopyMem (CurrentTableList->Table, Table, CurrentTableSize);
+ CurrentTableList->Handle = AcpiSupportInstance->CurrentHandle++;
+ *Handle = CurrentTableList->Handle;
+ CurrentTableList->Version = Version;
+
+ //
+ // Update internal pointers if this is a required table. If it is a required
+ // table and a table of that type already exists, return an error.
+ //
+ // Calculate the checksum if the table is not FACS.
+ //
+ switch (CurrentTableSignature) {
+
+ case EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE:
+ //
+ // We don't add the FADT in the standard way because some
+ // OS expect the FADT to be early in the table list.
+ // So we always add it as the first element in the list.
+ //
+ AddToRsdt = FALSE;
+
+ //
+ // Check that the table has not been previously added.
+ //
+ if (((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0 && AcpiSupportInstance->Fadt1 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 && AcpiSupportInstance->Fadt3 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_3_0) != 0 && AcpiSupportInstance->Fadt3 != NULL)
+ ) {
+ gBS->FreePages (CurrentTableList->PageAddress, CurrentTableList->NumberOfPages);
+ gBS->FreePool (CurrentTableList);
+ return EFI_ACCESS_DENIED;
+ }
+ //
+ // Add the table to the appropriate table version
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Fadt1 = (EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE *) CurrentTableList->Table;
+
+ //
+ // Update pointers in FADT. If tables don't exist this will put NULL pointers there.
+ //
+ AcpiSupportInstance->Fadt1->FirmwareCtrl = (UINT32) (UINTN) AcpiSupportInstance->Facs1;
+ AcpiSupportInstance->Fadt1->Dsdt = (UINT32) (UINTN) AcpiSupportInstance->Dsdt1;
+
+ //
+ // RSDP OEM information is updated to match the FADT OEM information
+ //
+ CopyMem (
+ &AcpiSupportInstance->Rsdp1->OemId,
+ &AcpiSupportInstance->Fadt1->Header.OemId,
+ 6
+ );
+
+ //
+ // RSDT OEM information is updated to match the FADT OEM information.
+ //
+ CopyMem (
+ &AcpiSupportInstance->Rsdt1->OemId,
+ &AcpiSupportInstance->Fadt1->Header.OemId,
+ 6
+ );
+
+ CopyMem (
+ &AcpiSupportInstance->Rsdt1->OemTableId,
+ &AcpiSupportInstance->Fadt1->Header.OemTableId,
+ sizeof (UINT64)
+ );
+ AcpiSupportInstance->Rsdt1->OemRevision = AcpiSupportInstance->Fadt1->Header.OemRevision;
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Fadt3 = (EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *) CurrentTableList->Table;
+
+ //
+ // Update pointers in FADT. If tables don't exist this will put NULL pointers there.
+ // Note: If the FIRMWARE_CTRL is non-zero, then X_FIRMWARE_CTRL must be zero, and
+ // vice-versa.
+ //
+ if ((UINT64)(UINTN)AcpiSupportInstance->Facs3 < BASE_4GB) {
+ AcpiSupportInstance->Fadt3->FirmwareCtrl = (UINT32) (UINTN) AcpiSupportInstance->Facs3;
+ ZeroMem (
+ &AcpiSupportInstance->Fadt3->XFirmwareCtrl,
+ sizeof (UINT64)
+ );
+ } else {
+ AcpiSupportInstance->Fadt3->FirmwareCtrl = 0;
+ Buffer64 = (UINT64) (UINTN) AcpiSupportInstance->Facs3;
+ CopyMem (
+ &AcpiSupportInstance->Fadt3->XFirmwareCtrl,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+ }
+ AcpiSupportInstance->Fadt3->Dsdt = (UINT32) (UINTN) AcpiSupportInstance->Dsdt3;
+ Buffer64 = (UINT64) (UINTN) AcpiSupportInstance->Dsdt3;
+ CopyMem (
+ &AcpiSupportInstance->Fadt3->XDsdt,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+
+ //
+ // RSDP OEM information is updated to match the FADT OEM information
+ //
+ CopyMem (
+ &AcpiSupportInstance->Rsdp3->OemId,
+ &AcpiSupportInstance->Fadt3->Header.OemId,
+ 6
+ );
+
+ //
+ // RSDT OEM information is updated to match FADT OEM information.
+ //
+ CopyMem (
+ &AcpiSupportInstance->Rsdt3->OemId,
+ &AcpiSupportInstance->Fadt3->Header.OemId,
+ 6
+ );
+ CopyMem (
+ &AcpiSupportInstance->Rsdt3->OemTableId,
+ &AcpiSupportInstance->Fadt3->Header.OemTableId,
+ sizeof (UINT64)
+ );
+ AcpiSupportInstance->Rsdt3->OemRevision = AcpiSupportInstance->Fadt3->Header.OemRevision;
+
+ //
+ // XSDT OEM information is updated to match FADT OEM information.
+ //
+ CopyMem (
+ &AcpiSupportInstance->Xsdt->OemId,
+ &AcpiSupportInstance->Fadt3->Header.OemId,
+ 6
+ );
+ CopyMem (
+ &AcpiSupportInstance->Xsdt->OemTableId,
+ &AcpiSupportInstance->Fadt3->Header.OemTableId,
+ sizeof (UINT64)
+ );
+ AcpiSupportInstance->Xsdt->OemRevision = AcpiSupportInstance->Fadt3->Header.OemRevision;
+ }
+
+ //
+ // Checksum the table
+ //
+ if (Checksum) {
+ AcpiPlatformChecksum (
+ CurrentTableList->Table,
+ CurrentTableList->Table->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ break;
+
+ case EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE:
+ //
+ // Check that the table has not been previously added.
+ //
+ if (((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0 && AcpiSupportInstance->Facs1 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 && AcpiSupportInstance->Facs3 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_3_0) != 0 && AcpiSupportInstance->Facs3 != NULL)
+ ) {
+ gBS->FreePages (CurrentTableList->PageAddress, CurrentTableList->NumberOfPages);
+ gBS->FreePool (CurrentTableList);
+ return EFI_ACCESS_DENIED;
+ }
+ //
+ // FACS is referenced by FADT and is not part of RSDT
+ //
+ AddToRsdt = FALSE;
+
+ //
+ // Add the table to the appropriate table version
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Facs1 = (EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *) CurrentTableList->Table;
+
+ //
+ // If FADT already exists, update table pointers.
+ //
+ if (AcpiSupportInstance->Fadt1 != NULL) {
+ AcpiSupportInstance->Fadt1->FirmwareCtrl = (UINT32) (UINTN) AcpiSupportInstance->Facs1;
+
+ //
+ // Checksum FADT table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt1,
+ AcpiSupportInstance->Fadt1->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Facs3 = (EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *) CurrentTableList->Table;
+
+ //
+ // If FADT already exists, update table pointers.
+ //
+ if (AcpiSupportInstance->Fadt3 != NULL) {
+ //
+ // Note: If the FIRMWARE_CTRL is non-zero, then X_FIRMWARE_CTRL must be zero, and
+ // vice-versa.
+ //
+ if ((UINT64)(UINTN)AcpiSupportInstance->Facs3 < BASE_4GB) {
+ AcpiSupportInstance->Fadt3->FirmwareCtrl = (UINT32) (UINTN) AcpiSupportInstance->Facs3;
+ } else {
+ Buffer64 = (UINT64) (UINTN) AcpiSupportInstance->Facs3;
+ CopyMem (
+ &AcpiSupportInstance->Fadt3->XFirmwareCtrl,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+ }
+
+ //
+ // Checksum FADT table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt3,
+ AcpiSupportInstance->Fadt3->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+
+ break;
+
+ case EFI_ACPI_1_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE:
+ //
+ // Check that the table has not been previously added.
+ //
+ if (((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0 && AcpiSupportInstance->Dsdt1 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 && AcpiSupportInstance->Dsdt3 != NULL) ||
+ ((Version & EFI_ACPI_TABLE_VERSION_3_0) != 0 && AcpiSupportInstance->Dsdt3 != NULL)
+ ) {
+ gBS->FreePages (CurrentTableList->PageAddress, CurrentTableList->NumberOfPages);
+ gBS->FreePool (CurrentTableList);
+ return EFI_ACCESS_DENIED;
+ }
+ //
+ // DSDT is referenced by FADT and is not part of RSDT
+ //
+ AddToRsdt = FALSE;
+
+ //
+ // Add the table to the appropriate table version
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Dsdt1 = (EFI_ACPI_DESCRIPTION_HEADER *) CurrentTableList->Table;
+
+ //
+ // If FADT already exists, update table pointers.
+ //
+ if (AcpiSupportInstance->Fadt1 != NULL) {
+ AcpiSupportInstance->Fadt1->Dsdt = (UINT32) (UINTN) AcpiSupportInstance->Dsdt1;
+
+ //
+ // Checksum FADT table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt1,
+ AcpiSupportInstance->Fadt1->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ //
+ // Save a pointer to the table
+ //
+ AcpiSupportInstance->Dsdt3 = (EFI_ACPI_DESCRIPTION_HEADER *) CurrentTableList->Table;
+
+ //
+ // If FADT already exists, update table pointers.
+ //
+ if (AcpiSupportInstance->Fadt3 != NULL) {
+ AcpiSupportInstance->Fadt3->Dsdt = (UINT32) (UINTN) AcpiSupportInstance->Dsdt3;
+ Buffer64 = (UINT64) (UINTN) AcpiSupportInstance->Dsdt3;
+ CopyMem (
+ &AcpiSupportInstance->Fadt3->XDsdt,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+
+ //
+ // Checksum FADT table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt3,
+ AcpiSupportInstance->Fadt3->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+ //
+ // Checksum the table
+ //
+ if (Checksum) {
+ AcpiPlatformChecksum (
+ CurrentTableList->Table,
+ CurrentTableList->Table->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ break;
+
+ default:
+ //
+ // Checksum the table
+ //
+ if (Checksum) {
+ AcpiPlatformChecksum (
+ CurrentTableList->Table,
+ CurrentTableList->Table->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ break;
+ }
+ //
+ // Add the table to the current list of tables
+ //
+ InsertTailList (&AcpiSupportInstance->TableList, &CurrentTableList->Link);
+
+ //
+ // Add the table to RSDT and/or XSDT table entry lists.
+ //
+ //
+ // Add to ACPI 1.0b table tree
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ if (AddToRsdt) {
+ //
+ // If the table number exceed the gEfiAcpiMaxNumTables, enlarge the table buffer
+ //
+ if (AcpiSupportInstance->NumberOfTableEntries1 >= mEfiAcpiMaxNumTables) {
+ Status = ReallocateAcpiTableBuffer (AcpiSupportInstance);
+ ASSERT_EFI_ERROR (Status);
+ }
+ CurrentRsdtEntry = (UINT32 *)
+ (
+ (UINT8 *) AcpiSupportInstance->Rsdt1 +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) +
+ AcpiSupportInstance->NumberOfTableEntries1 *
+ sizeof (UINT32)
+ );
+
+ //
+ // Add entry to the RSDT unless its the FACS or DSDT
+ //
+ *CurrentRsdtEntry = (UINT32) (UINTN) CurrentTableList->Table;
+
+ //
+ // Update RSDT length
+ //
+ AcpiSupportInstance->Rsdt1->Length = AcpiSupportInstance->Rsdt1->Length + sizeof (UINT32);
+
+ AcpiSupportInstance->NumberOfTableEntries1++;
+ }
+ }
+ //
+ // Add to ACPI 2.0/3.0 table tree
+ //
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 || (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ if (AddToRsdt) {
+ //
+ // If the table number exceed the gEfiAcpiMaxNumTables, enlarge the table buffer
+ //
+ if (AcpiSupportInstance->NumberOfTableEntries3 >= mEfiAcpiMaxNumTables) {
+ Status = ReallocateAcpiTableBuffer (AcpiSupportInstance);
+ ASSERT_EFI_ERROR (Status);
+ }
+ //
+ // At this time, it is assumed that RSDT and XSDT maintain parallel lists of tables.
+ // If it becomes necessary to maintain separate table lists, changes will be required.
+ //
+ CurrentRsdtEntry = (UINT32 *)
+ (
+ (UINT8 *) AcpiSupportInstance->Rsdt3 +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) +
+ AcpiSupportInstance->NumberOfTableEntries3 *
+ sizeof (UINT32)
+ );
+
+ //
+ // This pointer must not be directly dereferenced as the XSDT entries may not
+ // be 64 bit aligned resulting in a possible fault. Use CopyMem to update.
+ //
+ CurrentXsdtEntry = (VOID *)
+ (
+ (UINT8 *) AcpiSupportInstance->Xsdt +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) +
+ AcpiSupportInstance->NumberOfTableEntries3 *
+ sizeof (UINT64)
+ );
+
+ //
+ // Add entry to the RSDT
+ //
+ *CurrentRsdtEntry = (UINT32) (UINTN) CurrentTableList->Table;
+
+ //
+ // Update RSDT length
+ //
+ AcpiSupportInstance->Rsdt3->Length = AcpiSupportInstance->Rsdt3->Length + sizeof (UINT32);
+
+ //
+ // Add entry to XSDT, XSDT expects 64 bit pointers, but
+ // the table pointers in XSDT are not aligned on 8 byte boundary.
+ //
+ Buffer64 = (UINT64) (UINTN) CurrentTableList->Table;
+ CopyMem (
+ CurrentXsdtEntry,
+ &Buffer64,
+ sizeof (UINT64)
+ );
+
+ //
+ // Update length
+ //
+ AcpiSupportInstance->Xsdt->Length = AcpiSupportInstance->Xsdt->Length + sizeof (UINT64);
+
+ AcpiSupportInstance->NumberOfTableEntries3++;
+ }
+ }
+
+ ChecksumCommonTables (AcpiSupportInstance);
+ return EFI_SUCCESS;
+}
+/**
+ This function finds the table specified by the handle and returns a pointer to it.
+ If the handle is not found, EFI_NOT_FOUND is returned and the contents of Table are
+ undefined.
+
+ @param Handle Table to find.
+ @param TableList Table list to search
+ @param Table Pointer to table found.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_NOT_FOUND No table found matching the handle specified.
+
+**/
+EFI_STATUS
+FindTableByHandle (
+ IN UINTN Handle,
+ IN LIST_ENTRY *TableList,
+ OUT EFI_ACPI_TABLE_LIST **Table
+ )
+{
+ LIST_ENTRY *CurrentLink;
+ EFI_ACPI_TABLE_LIST *CurrentTable;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (Table);
+
+ //
+ // Find the table
+ //
+ CurrentLink = TableList->ForwardLink;
+
+ while (CurrentLink != TableList) {
+ CurrentTable = EFI_ACPI_TABLE_LIST_FROM_LINK (CurrentLink);
+ if (CurrentTable->Handle == Handle) {
+ //
+ // Found handle, so return this table.
+ //
+ *Table = CurrentTable;
+ return EFI_SUCCESS;
+ }
+
+ CurrentLink = CurrentLink->ForwardLink;
+ }
+ //
+ // Table not found
+ //
+ return EFI_NOT_FOUND;
+}
+/**
+ This function removes a basic table from the RSDT and/or XSDT.
+ For Acpi 1.0 tables, pass in the Rsdt.
+ For Acpi 2.0 tables, pass in both Rsdt and Xsdt.
+
+ @param Table Pointer to table found.
+ @param NumberOfTableEntries Current number of table entries in the RSDT/XSDT
+ @param Rsdt Pointer to the RSDT to remove from
+ @param Xsdt Pointer to the Xsdt to remove from
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_INVALID_PARAMETER The table was not found in both Rsdt and Xsdt.
+
+**/
+EFI_STATUS
+RemoveTableFromRsdt (
+ IN OUT EFI_ACPI_TABLE_LIST * Table,
+ IN OUT UINTN *NumberOfTableEntries,
+ IN OUT EFI_ACPI_DESCRIPTION_HEADER * Rsdt,
+ IN OUT EFI_ACPI_DESCRIPTION_HEADER * Xsdt OPTIONAL
+ )
+{
+ UINT32 *CurrentRsdtEntry;
+ VOID *CurrentXsdtEntry;
+ UINT64 CurrentTablePointer64;
+ UINTN TempIndex;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (Table);
+ ASSERT (NumberOfTableEntries);
+ ASSERT (Rsdt);
+
+ //
+ // Find the table entry in the RSDT and XSDT
+ //
+ for (TempIndex = 0; TempIndex < *NumberOfTableEntries; TempIndex++) {
+ //
+ // At this time, it is assumed that RSDT and XSDT maintain parallel lists of tables.
+ // If it becomes necessary to maintain separate table lists, changes will be required.
+ //
+ CurrentRsdtEntry = (UINT32 *) ((UINT8 *) Rsdt + sizeof (EFI_ACPI_DESCRIPTION_HEADER) + TempIndex * sizeof (UINT32));
+ if (Xsdt != NULL) {
+ //
+ // This pointer must not be directly dereferenced as the XSDT entries may not
+ // be 64 bit aligned resulting in a possible fault. Use CopyMem to update.
+ //
+ CurrentXsdtEntry = (VOID *) ((UINT8 *) Xsdt + sizeof (EFI_ACPI_DESCRIPTION_HEADER) + TempIndex * sizeof (UINT64));
+
+ //
+ // Read the entry value out of the XSDT
+ //
+ CopyMem (&CurrentTablePointer64, CurrentXsdtEntry, sizeof (UINT64));
+ } else {
+ //
+ // Initialize to NULL
+ //
+ CurrentXsdtEntry = 0;
+ CurrentTablePointer64 = 0;
+ }
+ //
+ // Check if we have found the corresponding entry in both RSDT and XSDT
+ //
+ if (*CurrentRsdtEntry == (UINT32) (UINTN) Table->Table &&
+ ((Xsdt == NULL) || CurrentTablePointer64 == (UINT64) (UINTN) Table->Table)
+ ) {
+ //
+ // Found entry, so copy all following entries and shrink table
+ // We actually copy all + 1 to copy the initialized value of memory over
+ // the last entry.
+ //
+ CopyMem (CurrentRsdtEntry, CurrentRsdtEntry + 1, (*NumberOfTableEntries - TempIndex) * sizeof (UINT32));
+ Rsdt->Length = Rsdt->Length - sizeof (UINT32);
+ if (Xsdt != NULL) {
+ CopyMem (CurrentXsdtEntry, ((UINT64 *) CurrentXsdtEntry) + 1, (*NumberOfTableEntries - TempIndex) * sizeof (UINT64));
+ Xsdt->Length = Xsdt->Length - sizeof (UINT64);
+ }
+ break;
+ } else if (TempIndex + 1 == *NumberOfTableEntries) {
+ //
+ // At the last entry, and table not found
+ //
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ //
+ // Checksum the tables
+ //
+ AcpiPlatformChecksum (
+ Rsdt,
+ Rsdt->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+
+ if (Xsdt != NULL) {
+ AcpiPlatformChecksum (
+ Xsdt,
+ Xsdt->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ //
+ // Decrement the number of tables
+ //
+ (*NumberOfTableEntries)--;
+
+ return EFI_SUCCESS;
+}
+/**
+ This function removes a table and frees any associated memory.
+
+ @param AcpiSupportInstance Instance of the protocol.
+ @param Version Version(s) to delete.
+ @param Table Pointer to table found.
+
+ @return EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+DeleteTable (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ IN OUT EFI_ACPI_TABLE_LIST *Table
+ )
+{
+ UINT32 CurrentTableSignature;
+ BOOLEAN RemoveFromRsdt;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (AcpiSupportInstance);
+ ASSERT (Table);
+
+ //
+ // Init locals
+ //
+ RemoveFromRsdt = TRUE;
+
+ if (Table->Table != NULL) {
+ CurrentTableSignature = ((EFI_ACPI_COMMON_HEADER *) Table->Table)->Signature;
+
+ //
+ // Basic tasks to accomplish delete are:
+ // Determine removal requirements (in RSDT/XSDT or not)
+ // Remove entry from RSDT/XSDT
+ // Remove any table references to the table
+ // If no one is using the table
+ // Free the table (removing pointers from private data and tables)
+ // Remove from list
+ // Free list structure
+ //
+ //
+ // Determine if this table is in the RSDT or XSDT
+ //
+ if ((CurrentTableSignature == EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) ||
+ (CurrentTableSignature == EFI_ACPI_2_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE) ||
+ (CurrentTableSignature == EFI_ACPI_3_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE)
+ ) {
+ RemoveFromRsdt = FALSE;
+ }
+ //
+ // We don't remove the FADT in the standard way because some
+ // OS expect the FADT to be early in the table list.
+ // So we always put it as the first element in the list.
+ //
+ if (CurrentTableSignature == EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
+ RemoveFromRsdt = FALSE;
+ }
+
+ //
+ // Remove the table from RSDT and XSDT
+ //
+
+ //
+ // This is a basic table, remove it from any lists and the Rsdt and/or Xsdt
+ //
+ if (Version & EFI_ACPI_TABLE_VERSION_NONE & Table->Version) {
+ //
+ // Remove this version from the table
+ //
+ Table->Version = Table->Version &~EFI_ACPI_TABLE_VERSION_NONE;
+ }
+
+ if (Version & EFI_ACPI_TABLE_VERSION_1_0B & Table->Version) {
+ //
+ // Remove this version from the table
+ //
+ Table->Version = Table->Version &~EFI_ACPI_TABLE_VERSION_1_0B;
+
+ //
+ // Remove from Rsdt. We don't care about the return value because it is
+ // acceptable for the table to not exist in Rsdt.
+ // We didn't add some tables so we don't remove them.
+ //
+ if (RemoveFromRsdt) {
+ RemoveTableFromRsdt (
+ Table,
+ &AcpiSupportInstance->NumberOfTableEntries1,
+ AcpiSupportInstance->Rsdt1,
+ NULL
+ );
+ }
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0 & Table->Version) ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0 & Table->Version)) {
+ //
+ // Remove this version from the table
+ //
+ if (Version & EFI_ACPI_TABLE_VERSION_2_0 & Table->Version) {
+ Table->Version = Table->Version &~EFI_ACPI_TABLE_VERSION_2_0;
+ }
+ if (Version & EFI_ACPI_TABLE_VERSION_3_0 & Table->Version) {
+ Table->Version = Table->Version &~EFI_ACPI_TABLE_VERSION_3_0;
+ }
+
+ //
+ // Remove from Rsdt and Xsdt. We don't care about the return value
+ // because it is acceptable for the table to not exist in Rsdt/Xsdt.
+ // We didn't add some tables so we don't remove them.
+ //
+ if (RemoveFromRsdt) {
+ RemoveTableFromRsdt (
+ Table,
+ &AcpiSupportInstance->NumberOfTableEntries3,
+ AcpiSupportInstance->Rsdt3,
+ AcpiSupportInstance->Xsdt
+ );
+ }
+ }
+ //
+ // Free the table, clean up any dependent tables and our private data pointers.
+ //
+ switch (Table->Table->Signature) {
+
+ case EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE:
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ AcpiSupportInstance->Fadt1 = NULL;
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ AcpiSupportInstance->Fadt3 = NULL;
+ }
+ break;
+
+ case EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE:
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ AcpiSupportInstance->Facs1 = NULL;
+
+ //
+ // Update FADT table pointers
+ //
+ if (AcpiSupportInstance->Fadt1 != NULL) {
+ AcpiSupportInstance->Fadt1->FirmwareCtrl = 0;
+
+ //
+ // Checksum table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt1,
+ AcpiSupportInstance->Fadt1->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ AcpiSupportInstance->Facs3 = NULL;
+
+ //
+ // Update FADT table pointers
+ //
+ if (AcpiSupportInstance->Fadt3 != NULL) {
+ AcpiSupportInstance->Fadt3->FirmwareCtrl = 0;
+ ZeroMem (&AcpiSupportInstance->Fadt3->XFirmwareCtrl, sizeof (UINT64));
+
+ //
+ // Checksum table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt3,
+ AcpiSupportInstance->Fadt3->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+ break;
+
+ case EFI_ACPI_3_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE:
+ if ((Version & EFI_ACPI_TABLE_VERSION_1_0B) != 0) {
+ AcpiSupportInstance->Dsdt1 = NULL;
+
+ //
+ // Update FADT table pointers
+ //
+ if (AcpiSupportInstance->Fadt1 != NULL) {
+ AcpiSupportInstance->Fadt1->Dsdt = 0;
+
+ //
+ // Checksum table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt1,
+ AcpiSupportInstance->Fadt1->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+
+
+ if ((Version & EFI_ACPI_TABLE_VERSION_2_0) != 0 ||
+ (Version & EFI_ACPI_TABLE_VERSION_3_0) != 0) {
+ AcpiSupportInstance->Dsdt3 = NULL;
+
+ //
+ // Update FADT table pointers
+ //
+ if (AcpiSupportInstance->Fadt3 != NULL) {
+ AcpiSupportInstance->Fadt3->Dsdt = 0;
+ ZeroMem (&AcpiSupportInstance->Fadt3->XDsdt, sizeof (UINT64));
+
+ //
+ // Checksum table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Fadt3,
+ AcpiSupportInstance->Fadt3->Header.Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+ }
+ }
+ break;
+
+ default:
+ //
+ // Do nothing
+ //
+ break;
+ }
+ }
+ //
+ // If no version is using this table anymore, remove and free list entry.
+ //
+ if (Table->Version == 0) {
+ //
+ // Free the Table
+ //
+ gBS->FreePages (Table->PageAddress, Table->NumberOfPages);
+ RemoveEntryList (&(Table->Link));
+ gBS->FreePool (Table);
+ }
+ //
+ // Done
+ //
+ return EFI_SUCCESS;
+}
+/**
+ This function finds and removes the table specified by the handle.
+
+ @param AcpiSupportInstance Instance of the protocol.
+ @param Version Bitmask of which versions to remove.
+ @param Handle Table to remove.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @return EFI_ABORTED An error occurred.
+ @return EFI_NOT_FOUND Handle not found in table list.
+**/
+EFI_STATUS
+RemoveTableFromList (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance,
+ IN EFI_ACPI_TABLE_VERSION Version,
+ IN UINTN Handle
+ )
+{
+ EFI_ACPI_TABLE_LIST *Table;
+ EFI_STATUS Status;
+
+ Table = NULL;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (AcpiSupportInstance);
+
+ //
+ // Find the table
+ //
+ Status = FindTableByHandle (
+ Handle,
+ &AcpiSupportInstance->TableList,
+ &Table
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Remove the table
+ //
+ Status = DeleteTable (AcpiSupportInstance, Version, Table);
+ if (EFI_ERROR (Status)) {
+ return EFI_ABORTED;
+ }
+ //
+ // Completed successfully
+ //
+ return EFI_SUCCESS;
+}
+/**
+ This function calculates and updates an UINT8 checksum.
+
+ @param Buffer Pointer to buffer to checksum
+ @param Size Number of bytes to checksum
+ @param ChecksumOffset Offset to place the checksum result in
+
+ @return EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+AcpiPlatformChecksum (
+ IN VOID *Buffer,
+ IN UINTN Size,
+ IN UINTN ChecksumOffset
+ )
+{
+ UINT8 Sum;
+ UINT8 *Ptr;
+
+ Sum = 0;
+ //
+ // Initialize pointer
+ //
+ Ptr = Buffer;
+
+ //
+ // set checksum to 0 first
+ //
+ Ptr[ChecksumOffset] = 0;
+
+ //
+ // add all content of buffer
+ //
+ while ((Size--) != 0) {
+ Sum = (UINT8) (Sum + (*Ptr++));
+ }
+ //
+ // set checksum
+ //
+ Ptr = Buffer;
+ Ptr[ChecksumOffset] = (UINT8) (0xff - Sum + 1);
+
+ return EFI_SUCCESS;
+}
+/**
+ Checksum all versions of the common tables, RSDP, RSDT, XSDT.
+
+ @param AcpiSupportInstance Protocol instance private data.
+
+ @return EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+ChecksumCommonTables (
+ IN OUT EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance
+ )
+{
+ //
+ // RSDP ACPI 1.0 checksum for 1.0 table. This is only the first 20 bytes of the structure
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Rsdp1,
+ sizeof (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER),
+ OFFSET_OF (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER,
+ Checksum)
+ );
+
+ //
+ // RSDP ACPI 1.0 checksum for 2.0/3.0 table. This is only the first 20 bytes of the structure
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Rsdp3,
+ sizeof (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER),
+ OFFSET_OF (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER,
+ Checksum)
+ );
+
+ //
+ // RSDP ACPI 2.0/3.0 checksum, this is the entire table
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Rsdp3,
+ sizeof (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER),
+ OFFSET_OF (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER,
+ ExtendedChecksum)
+ );
+
+ //
+ // RSDT checksums
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Rsdt1,
+ AcpiSupportInstance->Rsdt1->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Rsdt3,
+ AcpiSupportInstance->Rsdt3->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+
+ //
+ // XSDT checksum
+ //
+ AcpiPlatformChecksum (
+ AcpiSupportInstance->Xsdt,
+ AcpiSupportInstance->Xsdt->Length,
+ OFFSET_OF (EFI_ACPI_DESCRIPTION_HEADER,
+ Checksum)
+ );
+
+ return EFI_SUCCESS;
+}
+/**
+ Constructor for the ACPI support protocol to initializes instance data.
+
+ @param AcpiSupportInstance Instance to construct
+
+ @retval EFI_SUCCESS Instance initialized.
+ @retval EFI_OUT_OF_RESOURCES Unable to allocate required resources.
+**/
+EFI_STATUS
+AcpiSupportAcpiSupportConstructor (
+ IN EFI_ACPI_SUPPORT_INSTANCE *AcpiSupportInstance
+ )
+{
+ EFI_STATUS Status;
+ UINT64 CurrentData;
+ UINTN TotalSize;
+ UINTN RsdpTableSize;
+ UINT8 *Pointer;
+ EFI_PHYSICAL_ADDRESS PageAddress;
+
+ //
+ // Check for invalid input parameters
+ //
+ ASSERT (AcpiSupportInstance);
+
+ InitializeListHead (&AcpiSupportInstance->TableList);
+ AcpiSupportInstance->CurrentHandle = 1;
+ AcpiSupportInstance->AcpiSupport.GetAcpiTable = GetAcpiTable;
+ AcpiSupportInstance->AcpiSupport.SetAcpiTable = SetAcpiTable;
+ AcpiSupportInstance->AcpiSupport.PublishTables = PublishTables;
+
+ AcpiSupportInstance->AcpiTableProtocol.InstallAcpiTable = InstallAcpiTable;
+ AcpiSupportInstance->AcpiTableProtocol.UninstallAcpiTable = UninstallAcpiTable;
+
+ //
+ // Create RSDP table
+ //
+ RsdpTableSize = sizeof (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER) +
+ sizeof (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER);
+
+ PageAddress = 0xFFFFFFFF;
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiACPIReclaimMemory,
+ EFI_SIZE_TO_PAGES (RsdpTableSize),
+ &PageAddress
+ );
+
+ if (EFI_ERROR (Status)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Pointer = (UINT8 *) (UINTN) PageAddress;
+ ZeroMem (Pointer, RsdpTableSize);
+
+ AcpiSupportInstance->Rsdp1 = (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER *) Pointer;
+ Pointer += sizeof (EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER);
+ AcpiSupportInstance->Rsdp3 = (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER *) Pointer;
+
+ //
+ // Create RSDT, XSDT structures
+ //
+ TotalSize = sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 1.0 RSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 RSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT32) +
+ sizeof (EFI_ACPI_DESCRIPTION_HEADER) + // for ACPI 2.0/3.0 XSDT
+ mEfiAcpiMaxNumTables * sizeof (UINT64);
+
+ //
+ // Allocate memory in the lower 32 bit of address range for
+ // compatibility with ACPI 1.0 OS.
+ //
+ // This is done because ACPI 1.0 pointers are 32 bit values.
+ // ACPI 2.0 OS and all 64 bit OS must use the 64 bit ACPI table addresses.
+ // There is no architectural reason these should be below 4GB, it is purely
+ // for convenience of implementation that we force memory below 4GB.
+ //
+ PageAddress = 0xFFFFFFFF;
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiACPIReclaimMemory,
+ EFI_SIZE_TO_PAGES (TotalSize),
+ &PageAddress
+ );
+
+ if (EFI_ERROR (Status)) {
+ gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)AcpiSupportInstance->Rsdp1, EFI_SIZE_TO_PAGES (RsdpTableSize));
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Pointer = (UINT8 *) (UINTN) PageAddress;
+ ZeroMem (Pointer, TotalSize);
+
+ AcpiSupportInstance->Rsdt1 = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+ Pointer += (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + EFI_ACPI_MAX_NUM_TABLES * sizeof (UINT32));
+ AcpiSupportInstance->Rsdt3 = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+ Pointer += (sizeof (EFI_ACPI_DESCRIPTION_HEADER) + EFI_ACPI_MAX_NUM_TABLES * sizeof (UINT32));
+ AcpiSupportInstance->Xsdt = (EFI_ACPI_DESCRIPTION_HEADER *) Pointer;
+
+ //
+ // Initialize RSDP
+ //
+ CurrentData = EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_POINTER_SIGNATURE;
+ CopyMem (&AcpiSupportInstance->Rsdp1->Signature, &CurrentData, sizeof (UINT64));
+ CopyMem (AcpiSupportInstance->Rsdp1->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (AcpiSupportInstance->Rsdp1->OemId));
+ AcpiSupportInstance->Rsdp1->Reserved = EFI_ACPI_RESERVED_BYTE;
+ AcpiSupportInstance->Rsdp1->RsdtAddress = (UINT32) (UINTN) AcpiSupportInstance->Rsdt1;
+
+ CurrentData = EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER_SIGNATURE;
+ CopyMem (&AcpiSupportInstance->Rsdp3->Signature, &CurrentData, sizeof (UINT64));
+ CopyMem (AcpiSupportInstance->Rsdp3->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (AcpiSupportInstance->Rsdp3->OemId));
+ AcpiSupportInstance->Rsdp3->Revision = EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER_REVISION;
+ AcpiSupportInstance->Rsdp3->RsdtAddress = (UINT32) (UINTN) AcpiSupportInstance->Rsdt3;
+ AcpiSupportInstance->Rsdp3->Length = sizeof (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER);
+ CurrentData = (UINT64) (UINTN) AcpiSupportInstance->Xsdt;
+ CopyMem (&AcpiSupportInstance->Rsdp3->XsdtAddress, &CurrentData, sizeof (UINT64));
+ SetMem (AcpiSupportInstance->Rsdp3->Reserved, 3, EFI_ACPI_RESERVED_BYTE);
+
+ //
+ // Initialize Rsdt
+ //
+ // Note that we "reserve" one entry for the FADT so it can always be
+ // at the beginning of the list of tables. Some OS don't seem
+ // to find it correctly if it is too far down the list.
+ //
+ AcpiSupportInstance->Rsdt1->Signature = EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_TABLE_SIGNATURE;
+ AcpiSupportInstance->Rsdt1->Length = sizeof (EFI_ACPI_DESCRIPTION_HEADER);
+ AcpiSupportInstance->Rsdt1->Revision = EFI_ACPI_1_0_ROOT_SYSTEM_DESCRIPTION_TABLE_REVISION;
+ CopyMem (AcpiSupportInstance->Rsdt1->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (AcpiSupportInstance->Rsdt1->OemId));
+ CurrentData = PcdGet64 (PcdAcpiDefaultOemTableId);
+ CopyMem (&AcpiSupportInstance->Rsdt1->OemTableId, &CurrentData, sizeof (UINT64));
+ AcpiSupportInstance->Rsdt1->OemRevision = PcdGet32 (PcdAcpiDefaultOemRevision);
+ AcpiSupportInstance->Rsdt1->CreatorId = PcdGet32 (PcdAcpiDefaultCreatorId);
+ AcpiSupportInstance->Rsdt1->CreatorRevision = PcdGet32 (PcdAcpiDefaultCreatorRevision);
+ //
+ // We always reserve first one for FADT
+ //
+ AcpiSupportInstance->NumberOfTableEntries1 = 1;
+ AcpiSupportInstance->Rsdt1->Length = AcpiSupportInstance->Rsdt1->Length + sizeof(UINT32);
+
+ AcpiSupportInstance->Rsdt3->Signature = EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_TABLE_SIGNATURE;
+ AcpiSupportInstance->Rsdt3->Length = sizeof (EFI_ACPI_DESCRIPTION_HEADER);
+ AcpiSupportInstance->Rsdt3->Revision = EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_TABLE_REVISION;
+ CopyMem (AcpiSupportInstance->Rsdt3->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (AcpiSupportInstance->Rsdt3->OemId));
+ CurrentData = PcdGet64 (PcdAcpiDefaultOemTableId);
+ CopyMem (&AcpiSupportInstance->Rsdt3->OemTableId, &CurrentData, sizeof (UINT64));
+ AcpiSupportInstance->Rsdt3->OemRevision = PcdGet32 (PcdAcpiDefaultOemRevision);
+ AcpiSupportInstance->Rsdt3->CreatorId = PcdGet32 (PcdAcpiDefaultCreatorId);
+ AcpiSupportInstance->Rsdt3->CreatorRevision = PcdGet32 (PcdAcpiDefaultCreatorRevision);
+ //
+ // We always reserve first one for FADT
+ //
+ AcpiSupportInstance->NumberOfTableEntries3 = 1;
+ AcpiSupportInstance->Rsdt3->Length = AcpiSupportInstance->Rsdt3->Length + sizeof(UINT32);
+
+ //
+ // Initialize Xsdt
+ //
+ AcpiSupportInstance->Xsdt->Signature = EFI_ACPI_3_0_EXTENDED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE;
+ AcpiSupportInstance->Xsdt->Length = sizeof (EFI_ACPI_DESCRIPTION_HEADER);
+ AcpiSupportInstance->Xsdt->Revision = EFI_ACPI_3_0_EXTENDED_SYSTEM_DESCRIPTION_TABLE_REVISION;
+ CopyMem (AcpiSupportInstance->Xsdt->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (AcpiSupportInstance->Xsdt->OemId));
+ CurrentData = PcdGet64 (PcdAcpiDefaultOemTableId);
+ CopyMem (&AcpiSupportInstance->Xsdt->OemTableId, &CurrentData, sizeof (UINT64));
+ AcpiSupportInstance->Xsdt->OemRevision = PcdGet32 (PcdAcpiDefaultOemRevision);
+ AcpiSupportInstance->Xsdt->CreatorId = PcdGet32 (PcdAcpiDefaultCreatorId);
+ AcpiSupportInstance->Xsdt->CreatorRevision = PcdGet32 (PcdAcpiDefaultCreatorRevision);
+ //
+ // We always reserve first one for FADT
+ //
+ AcpiSupportInstance->Xsdt->Length = AcpiSupportInstance->Xsdt->Length + sizeof(UINT64);
+
+ ChecksumCommonTables (AcpiSupportInstance);
+
+ //
+ // Completed successfully
+ //
+ return EFI_SUCCESS;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.inf b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.inf
new file mode 100644
index 0000000000..32ca4f648f
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.inf
@@ -0,0 +1,81 @@
+## @file
+# Acpi Support Dirver to install Framework Acpi Support Protocol.
+#
+# This driver initializes ACPI support protocol instance data structure and intstall
+# ACPI support protocol to provide Get, Set and Publish Table services.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions
+# of the BSD License which accompanies this distribution. The
+# full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = AcpiSupportDxe
+ MODULE_UNI_FILE = AcpiSupportDxe.uni
+ FILE_GUID = 506533a6-e626-4500-b14f-17939c0e5b60
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = InstallAcpiSupport
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ AcpiSupportAcpiSupportProtocol.c
+ AcpiSupport.h
+ AcpiSupport.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ UefiBootServicesTableLib
+ MemoryAllocationLib
+ UefiDriverEntryPoint
+ BaseMemoryLib
+ UefiLib
+ DebugLib
+ BaseLib
+ PcdLib
+
+
+[Guids]
+ gEfiAcpi10TableGuid ## PRODUCES ## SystemTable
+ gEfiAcpiTableGuid ## PRODUCES ## SystemTable
+
+[FeaturePcd]
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdInstallAcpiSupportProtocol ## CONSUMES
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemTableId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemRevision ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision ## CONSUMES
+
+[Protocols]
+ gEfiAcpiTableProtocolGuid ## PRODUCES
+ gEfiAcpiSupportProtocolGuid ## SOMETIMES_PRODUCES
+
+[Depex]
+ TRUE
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ AcpiSupportDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.uni b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.uni
new file mode 100644
index 0000000000..b463bb7414
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxe.uni
@@ -0,0 +1,24 @@
+// /** @file
+// Acpi Support Dirver to install Framework Acpi Support Protocol.
+//
+// This driver initializes ACPI support protocol instance data structure and intstall
+// ACPI support protocol to provide Get, Set and Publish Table services.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "ACPI Support Driver to install the FrameworkAcpiSupportProtocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "This driver initializes ACPI support protocol instance data structure and installs ACPI support protocol to provide Get, Set and Publish Table services."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxeExtra.uni
new file mode 100644
index 0000000000..0520a0cc2c
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Acpi/AcpiSupportDxe/AcpiSupportDxeExtra.uni
@@ -0,0 +1,21 @@
+// /** @file
+// AcpiSupportDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"ACPI Support DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Bds.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Bds.h
new file mode 100644
index 0000000000..93bafd2dd8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Bds.h
@@ -0,0 +1,237 @@
+/** @file
+ Head file for BDS Architectural Protocol implementation
+
+Copyright (c) 2004 - 2014, 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 _BDS_MODULE_H_
+#define _BDS_MODULE_H_
+
+#include <FrameworkDxe.h>
+#include <IndustryStandard/PeImage.h>
+#include <Guid/MdeModuleHii.h>
+#include <Guid/FileSystemVolumeLabelInfo.h>
+#include <Guid/HiiPlatformSetupFormset.h>
+#include <Guid/StatusCodeDataTypeVariable.h>
+#include <Protocol/DevicePath.h>
+#include <IndustryStandard/SmBios.h>
+#include <Protocol/LoadFile.h>
+#include <Guid/FileInfo.h>
+#include <Protocol/HiiConfigRouting.h>
+#include <Protocol/Bds.h>
+#include <Protocol/Smbios.h>
+#include <Protocol/UgaDraw.h>
+#include <Protocol/BlockIo.h>
+#include <Guid/GlobalVariable.h>
+#include <Guid/CapsuleVendor.h>
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/LegacyDevOrder.h>
+#include <Guid/BdsHii.h>
+#include <Guid/ConnectConInEvent.h>
+#include <Guid/Performance.h>
+#include <Guid/FmpCapsule.h>
+#include <Protocol/GenericMemoryTest.h>
+#include <Protocol/FormBrowser2.h>
+#include <Protocol/HiiConfigAccess.h>
+#include <Protocol/GraphicsOutput.h>
+#include <Protocol/SimpleFileSystem.h>
+#include <Protocol/HiiDatabase.h>
+#include <Protocol/HiiString.h>
+#include <Protocol/SerialIo.h>
+#include <Protocol/LegacyBios.h>
+#include <Protocol/SimpleTextInEx.h>
+#include <Protocol/DriverHealth.h>
+#include <Protocol/BootLogo.h>
+#include <Protocol/VariableLock.h>
+
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/PrintLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PerformanceLib.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/HobLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/PcdLib.h>
+#include <Library/CapsuleLib.h>
+#include <Library/HiiLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiHiiServicesLib.h>
+
+#include <Library/GenericBdsLib.h>
+#include <Library/PlatformBdsLib.h>
+
+#pragma pack(1)
+
+///
+/// HII specific Vendor Device Path definition.
+///
+typedef struct {
+ VENDOR_DEVICE_PATH VendorDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL End;
+} HII_VENDOR_DEVICE_PATH;
+
+#pragma pack()
+
+/**
+
+ Show progress bar with title above it. It only works in Graphics mode.
+
+ @param TitleForeground Foreground color for Title.
+ @param TitleBackground Background color for Title.
+ @param Title Title above progress bar.
+ @param ProgressColor Progress bar color.
+ @param Progress Progress (0-100)
+ @param PreviousValue The previous value of the progress.
+
+ @retval EFI_STATUS Success update the progress bar
+
+**/
+EFI_STATUS
+PlatformBdsShowProgress (
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground,
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground,
+ IN CHAR16 *Title,
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor,
+ IN UINTN Progress,
+ IN UINTN PreviousValue
+ );
+
+//
+// Prototypes
+//
+
+/**
+
+ Install Boot Device Selection Protocol
+
+ @param ImageHandle The image handle.
+ @param SystemTable The system table.
+
+ @retval EFI_SUCEESS BDS has finished initializing.
+ Return the dispatcher and recall BDS.Entry
+ @retval Other Return status from AllocatePool() or gBS->InstallProtocolInterface
+
+**/
+EFI_STATUS
+EFIAPI
+BdsInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ );
+
+/**
+
+ Service routine for BdsInstance->Entry(). Devices are connected, the
+ consoles are initialized, and the boot options are tried.
+
+ @param This Protocol Instance structure.
+
+**/
+VOID
+EFIAPI
+BdsEntry (
+ IN EFI_BDS_ARCH_PROTOCOL *This
+ );
+
+
+/**
+ Perform the memory test base on the memory test intensive level,
+ and update the memory resource.
+
+ @param Level The memory test intensive level.
+
+ @retval EFI_STATUS Success test all the system memory and update
+ the memory resource
+
+**/
+EFI_STATUS
+EFIAPI
+BdsMemoryTest (
+ IN EXTENDMEM_COVERAGE_LEVEL Level
+ );
+
+/**
+
+ This routine is called to see if there are any capsules we need to process.
+ If the boot mode is not UPDATE, then we do nothing. Otherwise find the
+ capsule HOBS and produce firmware volumes for them via the DXE service.
+ Then call the dispatcher to dispatch drivers from them. Finally, check
+ the status of the updates.
+
+ This function should be called by BDS in case we need to do some
+ sort of processing even if there is no capsule to process. We
+ need to do this if an earlier update went away and we need to
+ clear the capsule variable so on the next reset PEI does not see it and
+ think there is a capsule available.
+
+ @param BootMode the current boot mode
+
+ @retval EFI_INVALID_PARAMETER boot mode is not correct for an update
+ @retval EFI_SUCCESS There is no error when processing capsule
+
+**/
+EFI_STATUS
+EFIAPI
+BdsProcessCapsules (
+ EFI_BOOT_MODE BootMode
+ );
+
+/**
+ Set the variable and report the error through status code upon failure.
+
+ @param VariableName A Null-terminated string that is the name of the vendor's variable.
+ Each VariableName is unique for each VendorGuid. VariableName must
+ contain 1 or more characters. If VariableName is an empty string,
+ then EFI_INVALID_PARAMETER is returned.
+ @param VendorGuid A unique identifier for the vendor.
+ @param Attributes Attributes bitmask to set for the variable.
+ @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
+ EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS, or
+ EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
+ causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
+ set, then a SetVariable() call with a DataSize of zero will not cause any change to
+ the variable value (the timestamp associated with the variable may be updated however
+ even if no new data value is provided,see the description of the
+ EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
+ be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
+ @param Data The contents for the variable.
+
+ @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
+ defined by the Attributes.
+ @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
+ DataSize exceeds the maximum allowed.
+ @retval EFI_INVALID_PARAMETER VariableName is an empty string.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
+ @retval EFI_WRITE_PROTECTED The variable in question is read-only.
+ @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
+ @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
+ or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS being set, but the AuthInfo
+ does NOT pass the validation check carried out by the firmware.
+
+ @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
+**/
+EFI_STATUS
+BdsDxeSetVariableAndReportStatusCodeOnError (
+ IN CHAR16 *VariableName,
+ IN EFI_GUID *VendorGuid,
+ IN UINT32 Attributes,
+ IN UINTN DataSize,
+ IN VOID *Data
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.inf b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.inf
new file mode 100644
index 0000000000..95a707c48b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.inf
@@ -0,0 +1,229 @@
+## @file
+# BDSDxe module is core driver for BDS phase.
+#
+# When DxeCore dispatching all DXE driver, this module will produce architecture protocol
+# gEfiBdsArchProtocolGuid. After DxeCore finish dispatching, DxeCore will invoke Entry
+# interface of protocol gEfiBdsArchProtocolGuid, then BDS phase is entered.
+#
+# Generally, this module take reposiblity to connect all necessary devices for platform boot,
+# these boot device path are hold in PlatformBdsLib library instance produced by platform.
+# For legacy boot, BDS will transfer control to legacy BIOS after legacy boot device is select.
+# For EFI boot, BDS will load boot loader file EFI\BOOT\BOOTIA32.EFI, EFI\BOOT\BOOTX64.EFI,
+# EFI\BOOT\BOOTIA64.EFI file from selected boot device and transfer control to boot loader.
+#
+# BDSDxe also maintain the UI for "Boot Manager, Boot Maintaince Manager, Device Manager" which
+# is used for user to configure boot option or maintain hardware device.
+#
+# Copyright (c) 2008 - 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.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = BdsDxe
+ MODULE_UNI_FILE = BdsDxe.uni
+ FILE_GUID = FC5C7020-1A48-4198-9BE2-EAD5ABC8CF2F
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = BdsInitialize
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ FrontPage.h
+ Language.h
+ Bds.h
+ Hotkey.h
+ BootMaint/BBSsupport.h
+ BootMngr/BootManager.h
+ BootMaint/BootMaint.h
+ String.h
+ BootMaint/FormGuid.h
+ HwErrRecSupport.c
+ HwErrRecSupport.h
+
+ DeviceMngr/DeviceManager.h
+ DeviceMngr/DeviceManagerVfr.h
+ DeviceMngr/DeviceManagerVfr.Vfr
+ DeviceMngr/DriverHealthVfr.Vfr
+ DeviceMngr/DeviceManagerStrings.uni
+ DeviceMngr/DeviceManager.c
+ BootMngr/BootManagerVfr.Vfr
+ BootMngr/BootManagerStrings.uni
+ BootMngr/BootManager.c
+ BootMaint/FE.vfr
+ BootMaint/FileExplorer.c
+ BootMaint/BootMaint.c
+ BootMaint/BBSsupport.c
+ BootMaint/UpdatePage.c
+ BootMaint/Variable.c
+ BootMaint/Data.c
+ BootMaint/ConsoleOption.c
+ BootMaint/BootOption.c
+ BootMaint/BmLib.c
+ BootMaint/Bm.vfr
+ BootMaint/Bmstring.uni
+ Hotkey.c
+ MemoryTest.c
+ Capsules.c
+ Strings.uni
+ String.c
+ Language.c
+ FrontPageVfr.Vfr
+ FrontPageStrings.uni
+ FrontPage.c
+ BdsEntry.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ DevicePathLib
+ BaseLib
+ HobLib
+ UefiRuntimeServicesTableLib
+ GenericBdsLib
+ ReportStatusCodeLib
+ PerformanceLib
+ MemoryAllocationLib
+ UefiLib
+ UefiBootServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ PrintLib
+ HiiLib
+ UefiDriverEntryPoint
+ PlatformBdsLib
+ CapsuleLib
+ PcdLib
+ UefiHiiServicesLib
+
+[Guids]
+ ## SOMETIMES_PRODUCES ## Variable:L"BootXXXX" # Boot option variable
+ ## SOMETIMES_PRODUCES ## Variable:L"DriverXXXX" # Driver load option.
+ ## SOMETIMES_PRODUCES ## Variable:L"PlatformLang" # Platform supported languange in Rfc4646 format
+ ## SOMETIMES_PRODUCES ## Variable:L"Lang" # Platform supported languange in Iso639 format
+ ## SOMETIMES_PRODUCES ## Variable:L"LangCodes" # Value of PcdUefiVariableDefaultLangCodes
+ ## PRODUCES ## Variable:L"PlatformLangCodes" # Value of PcdUefiVariableDefaultPlatformLangCodes
+ ## SOMETIMES_PRODUCES ## Variable:L"KeyXXXX" # Hotkey option variable
+ ## PRODUCES ## Variable:L"HwErrRecSupport" # The level of platform supported hardware Error Record Persistence
+ ## PRODUCES ## Variable:L"Timeout" # The time out value in second of showing progress bar
+ ## SOMETIMES_PRODUCES ## Variable:L"BootOptionSupport" # The feature supported in boot option menu, value could be: EFI_BOOT_OPTION_SUPPORT_KEY, EFI_BOOT_OPTION_SUPPORT_APP
+ ## SOMETIMES_PRODUCES ## Variable:L"BootOrder" # The boot option array
+ ## SOMETIMES_PRODUCES ## Variable:L"DriverOrder" # The driver order list
+ ## SOMETIMES_CONSUMES ## Variable:L"ConIn" # The device path of console in device
+ ## SOMETIMES_PRODUCES ## Variable:L"ConIn" # The device path of console in device
+ ## SOMETIMES_CONSUMES ## Variable:L"ConOut" # The device path of console out device
+ ## SOMETIMES_PRODUCES ## Variable:L"ConOut" # The device path of console out device
+ ## SOMETIMES_CONSUMES ## Variable:L"ErrOut" # The device path of error out device
+ ## SOMETIMES_PRODUCES ## Variable:L"ErrOut" # The device path of error out device
+ ## SOMETIMES_CONSUMES ## Variable:L"ConInDev" # The device path of console in device
+ ## SOMETIMES_CONSUMES ## Variable:L"ConOutDev" # The device path of console out device
+ ## SOMETIMES_CONSUMES ## Variable:L"ErrOutDev" # The device path of error out device
+ ## SOMETIMES_PRODUCES ## Variable:L"BootNext" # The number of next boot option
+ gEfiGlobalVariableGuid
+ gEfiFileSystemVolumeLabelInfoIdGuid ## SOMETIMES_CONSUMES ## UNDEFINED # Indicate the information type is volume
+ gEfiFileInfoGuid ## SOMETIMES_CONSUMES ## UNDEFINED # Indicate the information type is file
+ gEfiHiiPlatformSetupFormsetGuid ## SOMETIMES_CONSUMES ## UNDEFINED # Indicate the formset class guid to be displayed
+ gEfiIfrTianoGuid ## SOMETIMES_PRODUCES ## UNDEFINED # Extended IFR Guid Opcode
+ gEfiHiiDriverHealthFormsetGuid ## SOMETIMES_CONSUMES ## UNDEFINED # Indicate the Driver Health formset class guid to be displayed
+ ## SOMETIMES_PRODUCES ## Variable:L"LegacyDevOrder"
+ ## SOMETIMES_CONSUMES ## Variable:L"LegacyDevOrder"
+ gEfiLegacyDevOrderVariableGuid
+ gFrontPageFormSetGuid ## SOMETIMES_CONSUMES ## HII # FrontPage HII Package
+ gBootMaintFormSetGuid ## SOMETIMES_CONSUMES ## HII # BootMaint HII Package
+ gFileExploreFormSetGuid ## SOMETIMES_CONSUMES ## HII # FileExplore HII Package
+ gBootManagerFormSetGuid ## SOMETIMES_CONSUMES ## HII # BootManager HII Package
+ gDeviceManagerFormSetGuid ## SOMETIMES_CONSUMES ## HII # DeviceManager HII Package
+ gDriverHealthFormSetGuid ## SOMETIMES_CONSUMES ## HII # DriverHealth HII Package
+ ## SOMETIMES_PRODUCES ## Event
+ ## SOMETIMES_CONSUMES ## Event
+ gConnectConInEventGuid
+ gEfiFmpCapsuleGuid ## SOMETIMES_CONSUMES ## GUID # FMP Capsule
+ gEdkiiStatusCodeDataTypeVariableGuid ## SOMETIMES_CONSUMES ## GUID
+ gEfiUartDevicePathGuid ## SOMETIMES_CONSUMES ## GUID (Identify the device path for UARD device)
+ gPerformanceProtocolGuid ## SOMETIMES_PRODUCES ## Variable:L"PerfDataMemAddr" (The ACPI address of performance data)
+
+[Protocols]
+ gEfiSimpleFileSystemProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiLoadFileProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiBdsArchProtocolGuid ## PRODUCES
+ gEfiSmbiosProtocolGuid ## CONSUMES
+ gEfiGenericMemTestProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiLegacyBiosProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiUgaDrawProtocolGuid |gEfiMdePkgTokenSpaceGuid.PcdUgaConsumeSupport ## SOMETIMES_CONSUMES
+ gEfiBlockIoProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiGraphicsOutputProtocolGuid ## SOMETIMES_CONSUMES
+ ## CONSUMES
+ ## NOTIFY
+ gEfiSimpleTextInputExProtocolGuid
+ gEfiHiiConfigAccessProtocolGuid ## SOMETIMES_PRODUCES
+ gEfiFormBrowser2ProtocolGuid ## CONSUMES
+ gEfiSerialIoProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiDevicePathProtocolGuid ## CONSUMES
+ gEfiDriverHealthProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiPciIoProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiBootLogoProtocolGuid ## SOMETIMES_CONSUMES
+ gEdkiiVariableLockProtocolGuid ## SOMETIMES_CONSUMES
+
+[FeaturePcd]
+ gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultLangDeprecate ## CONSUMES
+ gEfiMdePkgTokenSpaceGuid.PcdUgaConsumeSupport ## CONSUMES
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdBootlogoOnlyEnable ## CONSUMES
+
+[Pcd]
+ gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultLangCodes ## SOMETIMES_CONSUMES
+ gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultLang ## SOMETIMES_CONSUMES
+ gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultPlatformLangCodes ## CONSUMES
+ gEfiMdePkgTokenSpaceGuid.PcdUefiVariableDefaultPlatformLang ## SOMETIMES_CONSUMES
+ ## CONSUMES
+ ## PRODUCES
+ gEfiMdePkgTokenSpaceGuid.PcdHardwareErrorRecordLevel
+ gEfiMdeModulePkgTokenSpaceGuid.PcdConOutRow ## PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdConOutColumn ## PRODUCES
+ ## SOMETIMES_CONSUMES
+ ## SOMETIMES_PRODUCES
+ gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut
+ ## CONSUMES
+ ## PRODUCES
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdBootState
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVendor ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareRevision ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution ## PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution ## PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdConInConnectOnDemand ## SOMETIMES_CONSUMES
+ ## CONSUMES
+ ## SOMETIMES_PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSetupConOutColumn
+ ## CONSUMES
+ ## SOMETIMES_PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSetupConOutRow
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdErrorCodeSetVariable ## CONSUMES
+
+[Depex]
+ TRUE
+
+#
+# [BootMode]
+# FLASH_UPDATE ## SOMETIMES_CONSUMES # Update Capsule Image
+#
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ BdsDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.uni
new file mode 100644
index 0000000000..5911c7b305
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxe.uni
@@ -0,0 +1,33 @@
+// /** @file
+// BDSDxe module is core driver for BDS phase.
+//
+// When DxeCore dispatching all DXE driver, this module will produce architecture protocol
+// gEfiBdsArchProtocolGuid. After DxeCore finish dispatching, DxeCore will invoke Entry
+// interface of protocol gEfiBdsArchProtocolGuid, then BDS phase is entered.
+//
+// Generally, this module take reposiblity to connect all necessary devices for platform boot,
+// these boot device path are hold in PlatformBdsLib library instance produced by platform.
+// For legacy boot, BDS will transfer control to legacy BIOS after legacy boot device is select.
+// For EFI boot, BDS will load boot loader file EFI\BOOT\BOOTIA32.EFI, EFI\BOOT\BOOTX64.EFI,
+// EFI\BOOT\BOOTIA64.EFI file from selected boot device and transfer control to boot loader.
+//
+// BDSDxe also maintain the UI for "Boot Manager, Boot Maintaince Manager, Device Manager" which
+// is used for user to configure boot option or maintain hardware device.
+//
+// Copyright (c) 2008 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "BDSDxe module is core driver for BDS phase"
+
+#string STR_MODULE_DESCRIPTION #language en-US "When DxeCore dispatching all DXE driver, this module will produce architecture protocol gEfiBdsArchProtocolGuid. After DxeCore finishes dispatching, DxeCore will invoke the Entry interface of protocol gEfiBdsArchProtocolGuid. Then BDS phase is entered. Generally, this module takes reposiblity to connect all necessary devices for platform boot. These boot device paths are held in PlatformBdsLib a library instance produced by the platform. For legacy boot, BDS will transfer control to legacy BIOS after legacy boot device is selected. For EFI boot, BDS will load boot loader file EFI\BOOT\BOOTIA32.EFI, EFI\BOOT\BOOTX64.EFI, EFI\BOOT\BOOTIA64.EFI files from selected boot devices, and transfers control to the boot loader. BDSDxe also maintains the UI for \"Boot Manager, Boot Maintaince Manager, Device Manager\", which is used by the user to configure boot options or to maintain hardware devices."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxeExtra.uni
new file mode 100644
index 0000000000..b73cfead99
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// BdsDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Boot Device Selection Core DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c
new file mode 100644
index 0000000000..6e3e5b05f9
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c
@@ -0,0 +1,736 @@
+/** @file
+ This module produce main entry for BDS phase - BdsEntry.
+ When this module was dispatched by DxeCore, gEfiBdsArchProtocolGuid will be installed
+ which contains interface of BdsEntry.
+ After DxeCore finish DXE phase, gEfiBdsArchProtocolGuid->BdsEntry will be invoked
+ to enter BDS phase.
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "Bds.h"
+#include "Language.h"
+#include "FrontPage.h"
+#include "Hotkey.h"
+#include "HwErrRecSupport.h"
+
+///
+/// BDS arch protocol instance initial value.
+///
+/// Note: Current BDS not directly get the BootMode, DefaultBoot,
+/// TimeoutDefault, MemoryTestLevel value from the BDS arch protocol.
+/// Please refer to the library useage of BdsLibGetBootMode, BdsLibGetTimeout
+/// and PlatformBdsDiagnostics in BdsPlatform.c
+///
+EFI_HANDLE gBdsHandle = NULL;
+
+EFI_BDS_ARCH_PROTOCOL gBds = {
+ BdsEntry
+};
+
+UINT16 *mBootNext = NULL;
+
+///
+/// The read-only variables defined in UEFI Spec.
+///
+CHAR16 *mReadOnlyVariables[] = {
+ L"PlatformLangCodes",
+ L"LangCodes",
+ L"BootOptionSupport",
+ L"HwErrRecSupport",
+ L"OsIndicationsSupported"
+ };
+
+/**
+
+ Install Boot Device Selection Protocol
+
+ @param ImageHandle The image handle.
+ @param SystemTable The system table.
+
+ @retval EFI_SUCEESS BDS has finished initializing.
+ Return the dispatcher and recall BDS.Entry
+ @retval Other Return status from AllocatePool() or gBS->InstallProtocolInterface
+
+**/
+EFI_STATUS
+EFIAPI
+BdsInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Install protocol interface
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gBdsHandle,
+ &gEfiBdsArchProtocolGuid, &gBds,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
+
+/**
+
+ This function attempts to boot for the boot order specified
+ by platform policy.
+
+**/
+VOID
+BdsBootDeviceSelect (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ LIST_ENTRY *Link;
+ BDS_COMMON_OPTION *BootOption;
+ UINTN ExitDataSize;
+ CHAR16 *ExitData;
+ UINT16 Timeout;
+ LIST_ENTRY BootLists;
+ CHAR16 Buffer[20];
+ BOOLEAN BootNextExist;
+ LIST_ENTRY *LinkBootNext;
+ EFI_EVENT ConnectConInEvent;
+
+ //
+ // Got the latest boot option
+ //
+ BootNextExist = FALSE;
+ LinkBootNext = NULL;
+ ConnectConInEvent = NULL;
+ InitializeListHead (&BootLists);
+
+ //
+ // First check the boot next option
+ //
+ ZeroMem (Buffer, sizeof (Buffer));
+
+ //
+ // Create Event to signal ConIn connection request
+ //
+ if (PcdGetBool (PcdConInConnectOnDemand)) {
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ EfiEventEmptyFunction,
+ NULL,
+ &gConnectConInEventGuid,
+ &ConnectConInEvent
+ );
+ if (EFI_ERROR(Status)) {
+ ConnectConInEvent = NULL;
+ }
+ }
+
+ if (mBootNext != NULL) {
+ //
+ // Indicate we have the boot next variable, so this time
+ // boot will always have this boot option
+ //
+ BootNextExist = TRUE;
+
+ //
+ // Clear the this variable so it's only exist in this time boot
+ //
+ Status = gRT->SetVariable (
+ L"BootNext",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ 0,
+ NULL
+ );
+ //
+ // Deleting variable with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Add the boot next boot option
+ //
+ UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", *mBootNext);
+ BootOption = BdsLibVariableToOption (&BootLists, Buffer);
+
+ //
+ // If fail to get boot option from variable, just return and do nothing.
+ //
+ if (BootOption == NULL) {
+ return;
+ }
+
+ BootOption->BootCurrent = *mBootNext;
+ }
+ //
+ // Parse the boot order to get boot option
+ //
+ BdsLibBuildOptionFromVar (&BootLists, L"BootOrder");
+
+ //
+ // When we didn't have chance to build boot option variables in the first
+ // full configuration boot (e.g.: Reset in the first page or in Device Manager),
+ // we have no boot options in the following mini configuration boot.
+ // Give the last chance to enumerate the boot options.
+ //
+ if (IsListEmpty (&BootLists)) {
+ BdsLibEnumerateAllBootOption (&BootLists);
+ }
+
+ Link = BootLists.ForwardLink;
+
+ //
+ // Parameter check, make sure the loop will be valid
+ //
+ if (Link == NULL) {
+ return ;
+ }
+ //
+ // Here we make the boot in a loop, every boot success will
+ // return to the front page
+ //
+ for (;;) {
+ //
+ // Check the boot option list first
+ //
+ if (Link == &BootLists) {
+ //
+ // When LazyConIn enabled, signal connect ConIn event before enter UI
+ //
+ if (PcdGetBool (PcdConInConnectOnDemand) && ConnectConInEvent != NULL) {
+ gBS->SignalEvent (ConnectConInEvent);
+ }
+
+ //
+ // There are two ways to enter here:
+ // 1. There is no active boot option, give user chance to
+ // add new boot option
+ // 2. All the active boot option processed, and there is no
+ // one is success to boot, then we back here to allow user
+ // add new active boot option
+ //
+ Timeout = 0xffff;
+ PlatformBdsEnterFrontPage (Timeout, FALSE);
+ InitializeListHead (&BootLists);
+ BdsLibBuildOptionFromVar (&BootLists, L"BootOrder");
+ Link = BootLists.ForwardLink;
+ continue;
+ }
+ //
+ // Get the boot option from the link list
+ //
+ BootOption = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
+
+ //
+ // According to EFI Specification, if a load option is not marked
+ // as LOAD_OPTION_ACTIVE, the boot manager will not automatically
+ // load the option.
+ //
+ if (!IS_LOAD_OPTION_TYPE (BootOption->Attribute, LOAD_OPTION_ACTIVE)) {
+ //
+ // skip the header of the link list, because it has no boot option
+ //
+ Link = Link->ForwardLink;
+ continue;
+ }
+ //
+ // Make sure the boot option device path connected,
+ // but ignore the BBS device path
+ //
+ if (DevicePathType (BootOption->DevicePath) != BBS_DEVICE_PATH) {
+ //
+ // Notes: the internal shell can not been connected with device path
+ // so we do not check the status here
+ //
+ BdsLibConnectDevicePath (BootOption->DevicePath);
+ }
+
+ //
+ // Restore to original mode before launching boot option.
+ //
+ BdsSetConsoleMode (FALSE);
+
+ //
+ // All the driver options should have been processed since
+ // now boot will be performed.
+ //
+ Status = BdsLibBootViaBootOption (BootOption, BootOption->DevicePath, &ExitDataSize, &ExitData);
+ if (Status != EFI_SUCCESS) {
+ //
+ // Call platform action to indicate the boot fail
+ //
+ BootOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_FAILED));
+ PlatformBdsBootFail (BootOption, Status, ExitData, ExitDataSize);
+
+ //
+ // Check the next boot option
+ //
+ Link = Link->ForwardLink;
+
+ } else {
+ //
+ // Call platform action to indicate the boot success
+ //
+ BootOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_SUCCEEDED));
+ PlatformBdsBootSuccess (BootOption);
+
+ //
+ // Boot success, then stop process the boot order, and
+ // present the boot manager menu, front page
+ //
+
+ //
+ // When LazyConIn enabled, signal connect ConIn Event before enter UI
+ //
+ if (PcdGetBool (PcdConInConnectOnDemand) && ConnectConInEvent != NULL) {
+ gBS->SignalEvent (ConnectConInEvent);
+ }
+
+ Timeout = 0xffff;
+ PlatformBdsEnterFrontPage (Timeout, FALSE);
+
+ //
+ // Rescan the boot option list, avoid potential risk of the boot
+ // option change in front page
+ //
+ if (BootNextExist) {
+ LinkBootNext = BootLists.ForwardLink;
+ }
+
+ InitializeListHead (&BootLists);
+ if (LinkBootNext != NULL) {
+ //
+ // Reserve the boot next option
+ //
+ InsertTailList (&BootLists, LinkBootNext);
+ }
+
+ BdsLibBuildOptionFromVar (&BootLists, L"BootOrder");
+ Link = BootLists.ForwardLink;
+ }
+ }
+
+}
+
+/**
+
+ Validate input console variable data.
+
+ If found the device path is not a valid device path, remove the variable.
+
+ @param VariableName Input console variable name.
+
+**/
+VOID
+BdsFormalizeConsoleVariable (
+ IN CHAR16 *VariableName
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ UINTN VariableSize;
+ EFI_STATUS Status;
+
+ DevicePath = BdsLibGetVariableAndSize (
+ VariableName,
+ &gEfiGlobalVariableGuid,
+ &VariableSize
+ );
+ if ((DevicePath != NULL) && !IsDevicePathValid (DevicePath, VariableSize)) {
+ Status = gRT->SetVariable (
+ VariableName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ 0,
+ NULL
+ );
+ //
+ // Deleting variable with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+}
+
+/**
+
+ Formalize Bds global variables.
+
+ 1. For ConIn/ConOut/ConErr, if found the device path is not a valid device path, remove the variable.
+ 2. For OsIndicationsSupported, Create a BS/RT/UINT64 variable to report caps
+ 3. Delete OsIndications variable if it is not NV/BS/RT UINT64
+ Item 3 is used to solve case when OS corrupts OsIndications. Here simply delete this NV variable.
+
+**/
+VOID
+BdsFormalizeEfiGlobalVariable (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT64 OsIndicationSupport;
+ UINT64 OsIndication;
+ UINTN DataSize;
+ UINT32 Attributes;
+
+ //
+ // Validate Console variable.
+ //
+ BdsFormalizeConsoleVariable (L"ConIn");
+ BdsFormalizeConsoleVariable (L"ConOut");
+ BdsFormalizeConsoleVariable (L"ErrOut");
+
+ //
+ // OS indicater support variable
+ //
+ OsIndicationSupport = EFI_OS_INDICATIONS_BOOT_TO_FW_UI \
+ | EFI_OS_INDICATIONS_FMP_CAPSULE_SUPPORTED;
+
+ BdsDxeSetVariableAndReportStatusCodeOnError (
+ L"OsIndicationsSupported",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ sizeof(UINT64),
+ &OsIndicationSupport
+ );
+
+ //
+ // If OsIndications is invalid, remove it.
+ // Invalid case
+ // 1. Data size != UINT64
+ // 2. OsIndication value inconsistence
+ // 3. OsIndication attribute inconsistence
+ //
+ OsIndication = 0;
+ Attributes = 0;
+ DataSize = sizeof(UINT64);
+ Status = gRT->GetVariable (
+ L"OsIndications",
+ &gEfiGlobalVariableGuid,
+ &Attributes,
+ &DataSize,
+ &OsIndication
+ );
+
+ if (!EFI_ERROR(Status)) {
+ if (DataSize != sizeof(UINT64) ||
+ (OsIndication & ~OsIndicationSupport) != 0 ||
+ Attributes != (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE)){
+
+ DEBUG ((EFI_D_ERROR, "Unformalized OsIndications variable exists. Delete it\n"));
+ Status = gRT->SetVariable (
+ L"OsIndications",
+ &gEfiGlobalVariableGuid,
+ 0,
+ 0,
+ NULL
+ );
+ //
+ // Deleting variable with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+ }
+
+}
+
+/**
+
+ Allocate a block of memory that will contain performance data to OS.
+
+**/
+VOID
+BdsAllocateMemoryForPerformanceData (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_PHYSICAL_ADDRESS AcpiLowMemoryBase;
+ EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
+
+ AcpiLowMemoryBase = 0x0FFFFFFFFULL;
+
+ //
+ // Allocate a block of memory that will contain performance data to OS.
+ //
+ Status = gBS->AllocatePages (
+ AllocateMaxAddress,
+ EfiReservedMemoryType,
+ EFI_SIZE_TO_PAGES (PERF_DATA_MAX_LENGTH),
+ &AcpiLowMemoryBase
+ );
+ if (!EFI_ERROR (Status)) {
+ //
+ // Save the pointer to variable for use in S3 resume.
+ //
+ BdsDxeSetVariableAndReportStatusCodeOnError (
+ L"PerfDataMemAddr",
+ &gPerformanceProtocolGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ sizeof (EFI_PHYSICAL_ADDRESS),
+ &AcpiLowMemoryBase
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((EFI_D_ERROR, "[Bds] PerfDataMemAddr (%08x) cannot be saved to NV storage.\n", AcpiLowMemoryBase));
+ }
+ //
+ // Mark L"PerfDataMemAddr" variable to read-only if the Variable Lock protocol exists
+ // Still lock it even the variable cannot be saved to prevent it's set by 3rd party code.
+ //
+ Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
+ if (!EFI_ERROR (Status)) {
+ Status = VariableLock->RequestToLock (VariableLock, L"PerfDataMemAddr", &gPerformanceProtocolGuid);
+ ASSERT_EFI_ERROR (Status);
+ }
+ }
+}
+
+/**
+
+ Service routine for BdsInstance->Entry(). Devices are connected, the
+ consoles are initialized, and the boot options are tried.
+
+ @param This Protocol Instance structure.
+
+**/
+VOID
+EFIAPI
+BdsEntry (
+ IN EFI_BDS_ARCH_PROTOCOL *This
+ )
+{
+ LIST_ENTRY DriverOptionList;
+ LIST_ENTRY BootOptionList;
+ UINTN BootNextSize;
+ CHAR16 *FirmwareVendor;
+ EFI_STATUS Status;
+ UINT16 BootTimeOut;
+ UINTN Index;
+ EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
+
+ //
+ // Insert the performance probe
+ //
+ PERF_END (NULL, "DXE", NULL, 0);
+ PERF_START (NULL, "BDS", NULL, 0);
+
+ PERF_CODE (
+ BdsAllocateMemoryForPerformanceData ();
+ );
+
+ //
+ // Initialize the global system boot option and driver option
+ //
+ InitializeListHead (&DriverOptionList);
+ InitializeListHead (&BootOptionList);
+
+ //
+ // Initialize hotkey service
+ //
+ InitializeHotkeyService ();
+
+ //
+ // Fill in FirmwareVendor and FirmwareRevision from PCDs
+ //
+ FirmwareVendor = (CHAR16 *)PcdGetPtr (PcdFirmwareVendor);
+ gST->FirmwareVendor = AllocateRuntimeCopyPool (StrSize (FirmwareVendor), FirmwareVendor);
+ ASSERT (gST->FirmwareVendor != NULL);
+ gST->FirmwareRevision = PcdGet32 (PcdFirmwareRevision);
+
+ //
+ // Fixup Tasble CRC after we updated Firmware Vendor and Revision
+ //
+ gST->Hdr.CRC32 = 0;
+ gBS->CalculateCrc32 ((VOID *)gST, sizeof(EFI_SYSTEM_TABLE), &gST->Hdr.CRC32);
+
+ //
+ // Validate Variable.
+ //
+ BdsFormalizeEfiGlobalVariable();
+
+ //
+ // Mark the read-only variables if the Variable Lock protocol exists
+ //
+ Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
+ DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n", Status));
+ if (!EFI_ERROR (Status)) {
+ for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) {
+ Status = VariableLock->RequestToLock (VariableLock, mReadOnlyVariables[Index], &gEfiGlobalVariableGuid);
+ ASSERT_EFI_ERROR (Status);
+ }
+ }
+
+ //
+ // Report Status Code to indicate connecting drivers will happen
+ //
+ REPORT_STATUS_CODE (
+ EFI_PROGRESS_CODE,
+ (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_BEGIN_CONNECTING_DRIVERS)
+ );
+
+ InitializeHwErrRecSupport();
+
+ //
+ // Initialize L"Timeout" EFI global variable.
+ //
+ BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
+ if (BootTimeOut != 0xFFFF) {
+ //
+ // If time out value equal 0xFFFF, no need set to 0xFFFF to variable area because UEFI specification
+ // define same behavior between no value or 0xFFFF value for L"Timeout".
+ //
+ BdsDxeSetVariableAndReportStatusCodeOnError (
+ L"Timeout",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof (UINT16),
+ &BootTimeOut
+ );
+ }
+
+ //
+ // bugbug: platform specific code
+ // Initialize the platform specific string and language
+ //
+ InitializeStringSupport ();
+ InitializeLanguage (TRUE);
+ InitializeFrontPage (TRUE);
+
+ //
+ // Do the platform init, can be customized by OEM/IBV
+ //
+ PERF_START (NULL, "PlatformBds", "BDS", 0);
+ PlatformBdsInit ();
+
+ //
+ // Set up the device list based on EFI 1.1 variables
+ // process Driver#### and Load the driver's in the
+ // driver option list
+ //
+ BdsLibBuildOptionFromVar (&DriverOptionList, L"DriverOrder");
+ if (!IsListEmpty (&DriverOptionList)) {
+ BdsLibLoadDrivers (&DriverOptionList);
+ }
+ //
+ // Check if we have the boot next option
+ //
+ mBootNext = BdsLibGetVariableAndSize (
+ L"BootNext",
+ &gEfiGlobalVariableGuid,
+ &BootNextSize
+ );
+
+ //
+ // Setup some platform policy here
+ //
+ PlatformBdsPolicyBehavior (&DriverOptionList, &BootOptionList, BdsProcessCapsules, BdsMemoryTest);
+ PERF_END (NULL, "PlatformBds", "BDS", 0);
+
+ //
+ // BDS select the boot device to load OS
+ //
+ BdsBootDeviceSelect ();
+
+ //
+ // Only assert here since this is the right behavior, we should never
+ // return back to DxeCore.
+ //
+ ASSERT (FALSE);
+
+ return ;
+}
+
+
+/**
+ Set the variable and report the error through status code upon failure.
+
+ @param VariableName A Null-terminated string that is the name of the vendor's variable.
+ Each VariableName is unique for each VendorGuid. VariableName must
+ contain 1 or more characters. If VariableName is an empty string,
+ then EFI_INVALID_PARAMETER is returned.
+ @param VendorGuid A unique identifier for the vendor.
+ @param Attributes Attributes bitmask to set for the variable.
+ @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
+ EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS, or
+ EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
+ causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
+ set, then a SetVariable() call with a DataSize of zero will not cause any change to
+ the variable value (the timestamp associated with the variable may be updated however
+ even if no new data value is provided,see the description of the
+ EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
+ be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
+ @param Data The contents for the variable.
+
+ @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
+ defined by the Attributes.
+ @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
+ DataSize exceeds the maximum allowed.
+ @retval EFI_INVALID_PARAMETER VariableName is an empty string.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
+ @retval EFI_WRITE_PROTECTED The variable in question is read-only.
+ @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
+ @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS
+ or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS being set, but the AuthInfo
+ does NOT pass the validation check carried out by the firmware.
+
+ @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
+**/
+EFI_STATUS
+BdsDxeSetVariableAndReportStatusCodeOnError (
+ IN CHAR16 *VariableName,
+ IN EFI_GUID *VendorGuid,
+ IN UINT32 Attributes,
+ IN UINTN DataSize,
+ IN VOID *Data
+ )
+{
+ EFI_STATUS Status;
+ EDKII_SET_VARIABLE_STATUS *SetVariableStatus;
+ UINTN NameSize;
+
+ Status = gRT->SetVariable (
+ VariableName,
+ VendorGuid,
+ Attributes,
+ DataSize,
+ Data
+ );
+ if (EFI_ERROR (Status)) {
+ NameSize = StrSize (VariableName);
+ SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize);
+ if (SetVariableStatus != NULL) {
+ CopyGuid (&SetVariableStatus->Guid, VendorGuid);
+ SetVariableStatus->NameSize = NameSize;
+ SetVariableStatus->DataSize = DataSize;
+ SetVariableStatus->SetStatus = Status;
+ SetVariableStatus->Attributes = Attributes;
+ CopyMem (SetVariableStatus + 1, VariableName, NameSize);
+ CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize);
+
+ REPORT_STATUS_CODE_EX (
+ EFI_ERROR_CODE,
+ PcdGet32 (PcdErrorCodeSetVariable),
+ 0,
+ NULL,
+ &gEdkiiStatusCodeDataTypeVariableGuid,
+ SetVariableStatus,
+ sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize
+ );
+
+ FreePool (SetVariableStatus);
+ }
+ }
+
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.c
new file mode 100644
index 0000000000..2ef9cf13eb
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.c
@@ -0,0 +1,254 @@
+/** @file
+ This function deal with the legacy boot option, it create, delete
+ and manage the legacy boot option, all legacy boot option is getting from
+ the legacy BBS table.
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BBSsupport.h"
+
+#pragma pack(1)
+typedef struct {
+ BBS_TABLE BbsEntry;
+ UINT16 BbsIndex;
+} LEGACY_BOOT_OPTION_BBS_DATA;
+#pragma pack()
+
+/**
+ Re-order the Boot Option according to the DevOrder.
+
+ The routine re-orders the Boot Option in BootOption array according to
+ the order specified by DevOrder.
+
+ @param DevOrder Pointer to buffer containing the BBS Index,
+ high 8-bit value 0xFF indicating a disabled boot option
+ @param DevOrderCount Count of the BBS Index
+ @param EnBootOption Callee allocated buffer containing the enabled Boot Option Numbers
+ @param EnBootOptionCount Count of the enabled Boot Option Numbers
+ @param DisBootOption Callee allocated buffer containing the disabled Boot Option Numbers
+ @param DisBootOptionCount Count of the disabled Boot Option Numbers
+**/
+VOID
+OrderLegacyBootOption4SameType (
+ UINT16 *DevOrder,
+ UINTN DevOrderCount,
+ UINT16 **EnBootOption,
+ UINTN *EnBootOptionCount,
+ UINT16 **DisBootOption,
+ UINTN *DisBootOptionCount
+ )
+{
+ EFI_STATUS Status;
+ UINT16 *NewBootOption;
+ UINT16 *BootOrder;
+ UINTN BootOrderSize;
+ UINTN Index;
+ UINTN StartPosition;
+
+ BDS_COMMON_OPTION *BootOption;
+
+ CHAR16 OptionName[sizeof ("Boot####")];
+ UINT16 *BbsIndexArray;
+ UINT16 *DeviceTypeArray;
+ LIST_ENTRY List;
+
+ BootOrder = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderSize
+ );
+ ASSERT (BootOrder != NULL);
+
+ BbsIndexArray = AllocatePool (BootOrderSize);
+ DeviceTypeArray = AllocatePool (BootOrderSize);
+ *EnBootOption = AllocatePool (BootOrderSize);
+ *DisBootOption = AllocatePool (BootOrderSize);
+ *DisBootOptionCount = 0;
+ *EnBootOptionCount = 0;
+ Index = 0;
+
+ ASSERT (BbsIndexArray != NULL);
+ ASSERT (DeviceTypeArray != NULL);
+ ASSERT (*EnBootOption != NULL);
+ ASSERT (*DisBootOption != NULL);
+
+ for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
+
+ UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", BootOrder[Index]);
+ InitializeListHead (&List);
+ BootOption = BdsLibVariableToOption (&List, OptionName);
+ ASSERT (BootOption != NULL);
+
+ if ((DevicePathType (BootOption->DevicePath) == BBS_DEVICE_PATH) &&
+ (DevicePathSubType (BootOption->DevicePath) == BBS_BBS_DP)) {
+ //
+ // Legacy Boot Option
+ //
+ ASSERT (BootOption->LoadOptionsSize == sizeof (LEGACY_BOOT_OPTION_BBS_DATA));
+
+ DeviceTypeArray[Index] = ((BBS_BBS_DEVICE_PATH *) BootOption->DevicePath)->DeviceType;
+ BbsIndexArray [Index] = ((LEGACY_BOOT_OPTION_BBS_DATA *) BootOption->LoadOptions)->BbsIndex;
+ } else {
+ DeviceTypeArray[Index] = BBS_TYPE_UNKNOWN;
+ BbsIndexArray [Index] = 0xFFFF;
+ }
+ FreePool (BootOption->DevicePath);
+ FreePool (BootOption->Description);
+ FreePool (BootOption->LoadOptions);
+ FreePool (BootOption);
+ }
+
+ //
+ // Record the corresponding Boot Option Numbers according to the DevOrder
+ // Record the EnBootOption and DisBootOption according to the DevOrder
+ //
+ StartPosition = BootOrderSize / sizeof (UINT16);
+ NewBootOption = AllocatePool (DevOrderCount * sizeof (UINT16));
+ ASSERT (NewBootOption != NULL);
+ while (DevOrderCount-- != 0) {
+ for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
+ if (BbsIndexArray[Index] == (DevOrder[DevOrderCount] & 0xFF)) {
+ StartPosition = MIN (StartPosition, Index);
+ NewBootOption[DevOrderCount] = BootOrder[Index];
+
+ if ((DevOrder[DevOrderCount] & 0xFF00) == 0xFF00) {
+ (*DisBootOption)[*DisBootOptionCount] = BootOrder[Index];
+ (*DisBootOptionCount)++;
+ } else {
+ (*EnBootOption)[*EnBootOptionCount] = BootOrder[Index];
+ (*EnBootOptionCount)++;
+ }
+ break;
+ }
+ }
+ }
+
+ //
+ // Overwrite the old BootOption
+ //
+ CopyMem (&BootOrder[StartPosition], NewBootOption, (*DisBootOptionCount + *EnBootOptionCount) * sizeof (UINT16));
+ Status = gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BootOrderSize,
+ BootOrder
+ );
+ //
+ // Changing content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ FreePool (NewBootOption);
+ FreePool (DeviceTypeArray);
+ FreePool (BbsIndexArray);
+ FreePool (BootOrder);
+}
+
+/**
+ Group the legacy boot options in the BootOption.
+
+ The routine assumes the boot options in the beginning that covers all the device
+ types are ordered properly and re-position the following boot options just after
+ the corresponding boot options with the same device type.
+ For example:
+ 1. Input = [Harddisk1 CdRom2 Efi1 Harddisk0 CdRom0 CdRom1 Harddisk2 Efi0]
+ Assuming [Harddisk1 CdRom2 Efi1] is ordered properly
+ Output = [Harddisk1 Harddisk0 Harddisk2 CdRom2 CdRom0 CdRom1 Efi1 Efi0]
+
+ 2. Input = [Efi1 Efi0 CdRom1 Harddisk0 Harddisk1 Harddisk2 CdRom0 CdRom2]
+ Assuming [Efi1 Efi0 CdRom1 Harddisk0] is ordered properly
+ Output = [Efi1 Efi0 CdRom1 CdRom0 CdRom2 Harddisk0 Harddisk1 Harddisk2]
+
+**/
+VOID
+GroupMultipleLegacyBootOption4SameType (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN DeviceIndex;
+ UINTN DeviceTypeIndex[7];
+ UINTN *NextIndex;
+ UINT16 OptionNumber;
+ UINT16 *BootOrder;
+ UINTN BootOrderSize;
+ CHAR16 OptionName[sizeof ("Boot####")];
+ BDS_COMMON_OPTION *BootOption;
+ LIST_ENTRY List;
+
+ SetMem (DeviceTypeIndex, sizeof (DeviceTypeIndex), 0xff);
+
+ BootOrder = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderSize
+ );
+
+ for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
+ UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", BootOrder[Index]);
+ InitializeListHead (&List);
+ BootOption = BdsLibVariableToOption (&List, OptionName);
+ ASSERT (BootOption != NULL);
+
+ if ((DevicePathType (BootOption->DevicePath) == BBS_DEVICE_PATH) &&
+ (DevicePathSubType (BootOption->DevicePath) == BBS_BBS_DP)) {
+ //
+ // Legacy Boot Option
+ //
+ ASSERT ((((BBS_BBS_DEVICE_PATH *) BootOption->DevicePath)->DeviceType & 0xF) < ARRAY_SIZE (DeviceTypeIndex));
+ NextIndex = &DeviceTypeIndex[((BBS_BBS_DEVICE_PATH *) BootOption->DevicePath)->DeviceType & 0xF];
+
+ if (*NextIndex == (UINTN) -1) {
+ //
+ // *NextIndex is the Index in BootOrder to put the next Option Number for the same type
+ //
+ *NextIndex = Index + 1;
+ } else {
+ //
+ // insert the current boot option before *NextIndex, causing [*Next .. Index] shift right one position
+ //
+ OptionNumber = BootOrder[Index];
+ CopyMem (&BootOrder[*NextIndex + 1], &BootOrder[*NextIndex], (Index - *NextIndex) * sizeof (UINT16));
+ BootOrder[*NextIndex] = OptionNumber;
+
+ //
+ // Update the DeviceTypeIndex array to reflect the right shift operation
+ //
+ for (DeviceIndex = 0; DeviceIndex < ARRAY_SIZE (DeviceTypeIndex); DeviceIndex++) {
+ if (DeviceTypeIndex[DeviceIndex] != (UINTN) -1 && DeviceTypeIndex[DeviceIndex] >= *NextIndex) {
+ DeviceTypeIndex[DeviceIndex]++;
+ }
+ }
+ }
+ }
+ FreePool (BootOption->DevicePath);
+ FreePool (BootOption->Description);
+ FreePool (BootOption->LoadOptions);
+ FreePool (BootOption);
+ }
+
+ Status = gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BootOrderSize,
+ BootOrder
+ );
+ //
+ // Changing content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ FreePool (BootOrder);
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.h
new file mode 100644
index 0000000000..e73dc85995
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BBSsupport.h
@@ -0,0 +1,82 @@
+/** @file
+ declares interface functions
+
+Copyright (c) 2004 - 2012, 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 _EFI_BDS_BBS_SUPPORT_H_
+#define _EFI_BDS_BBS_SUPPORT_H_
+
+#include "BootMaint.h"
+
+/**
+ Build Legacy Device Name String according.
+
+ @param CurBBSEntry BBS Table.
+ @param Index Index.
+ @param BufSize The buffer size.
+ @param BootString The output string.
+
+ @return VOID No output.
+
+**/
+VOID
+BdsBuildLegacyDevNameString (
+ IN BBS_TABLE *CurBBSEntry,
+ IN UINTN Index,
+ IN UINTN BufSize,
+ OUT CHAR16 *BootString
+ );
+
+/**
+ Group the legacy boot options in the BootOption.
+
+ The routine assumes the boot options in the beginning that covers all the device
+ types are ordered properly and re-position the following boot options just after
+ the corresponding boot options with the same device type.
+ For example:
+ 1. Input = [Harddisk1 CdRom2 Efi1 Harddisk0 CdRom0 CdRom1 Harddisk2 Efi0]
+ Assuming [Harddisk1 CdRom2 Efi1] is ordered properly
+ Output = [Harddisk1 Harddisk0 Harddisk2 CdRom2 CdRom0 CdRom1 Efi1 Efi0]
+
+ 2. Input = [Efi1 Efi0 CdRom1 Harddisk0 Harddisk1 Harddisk2 CdRom0 CdRom2]
+ Assuming [Efi1 Efi0 CdRom1 Harddisk0] is ordered properly
+ Output = [Efi1 Efi0 CdRom1 CdRom0 CdRom2 Harddisk0 Harddisk1 Harddisk2]
+**/
+VOID
+GroupMultipleLegacyBootOption4SameType (
+ VOID
+ );
+
+/**
+ Re-order the Boot Option according to the DevOrder.
+
+ The routine re-orders the Boot Option in BootOption array according to
+ the order specified by DevOrder.
+
+ @param DevOrder Pointer to buffer containing the BBS Index,
+ high 8-bit value 0xFF indicating a disabled boot option
+ @param DevOrderCount Count of the BBS Index
+ @param EnBootOption Callee allocated buffer containing the enabled Boot Option Numbers
+ @param EnBootOptionCount Count of the enabled Boot Option Numbers
+ @param DisBootOption Callee allocated buffer containing the disabled Boot Option Numbers
+ @param DisBootOptionCount Count of the disabled Boot Option Numbers
+**/
+VOID
+OrderLegacyBootOption4SameType (
+ UINT16 *DevOrder,
+ UINTN DevOrderCount,
+ UINT16 **EnBootOption,
+ UINTN *EnBootOptionCount,
+ UINT16 **DisBootOption,
+ UINTN *DisBootOptionCount
+ );
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bm.vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bm.vfr
new file mode 100644
index 0000000000..0d35c2c37e
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bm.vfr
@@ -0,0 +1,365 @@
+///** @file
+//
+// Boot Maintenance Utility Formset
+//
+// Copyright (c) 2004 - 2010, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+#include "FormGuid.h"
+
+formset
+ guid = BOOT_MAINT_FORMSET_GUID,
+ title = STRING_TOKEN(STR_FORM_MAIN_TITLE),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ classguid = BOOT_MAINT_FORMSET_GUID,
+
+ varstore BMM_FAKE_NV_DATA,
+ varid = VARSTORE_ID_BOOT_MAINT,
+ name = BmmData,
+ guid = BOOT_MAINT_FORMSET_GUID;
+
+ form formid = FORM_MAIN_ID,
+ title = STRING_TOKEN(STR_FORM_MAIN_TITLE);
+
+ goto FORM_BOOT_SETUP_ID,
+ prompt = STRING_TOKEN(STR_FORM_BOOT_SETUP_TITLE),
+ help = STRING_TOKEN(STR_FORM_BOOT_SETUP_HELP),
+ flags = INTERACTIVE,
+ key = FORM_BOOT_SETUP_ID;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ goto FORM_DRIVER_SETUP_ID,
+ prompt = STRING_TOKEN(STR_FORM_DRIVER_SETUP_TITLE),
+ help = STRING_TOKEN(STR_FORM_DRIVER_SETUP_HELP),
+ flags = INTERACTIVE,
+ key = FORM_DRIVER_SETUP_ID;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ goto FORM_CON_MAIN_ID,
+ prompt = STRING_TOKEN(STR_FORM_CON_MAIN_TITLE),
+ help = STRING_TOKEN(STR_FORM_CON_MAIN_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_MAIN_ID;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ goto FORM_BOOT_FROM_FILE_ID,
+ prompt = STRING_TOKEN(STR_BOOT_FROM_FILE),
+ help = STRING_TOKEN(STR_BOOT_FROM_FILE_HELP),
+ flags = INTERACTIVE,
+ key = KEY_VALUE_BOOT_FROM_FILE;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+// label FORM_MAIN_ID;
+
+ goto FORM_BOOT_NEXT_ID,
+ prompt = STRING_TOKEN(STR_FORM_BOOT_NEXT_TITLE),
+ help = STRING_TOKEN(STR_FORM_BOOT_NEXT_HELP),
+ flags = INTERACTIVE,
+ key = FORM_BOOT_NEXT_ID;
+
+ goto FORM_TIME_OUT_ID,
+ prompt = STRING_TOKEN(STR_FORM_TIME_OUT_TITLE),
+ help = STRING_TOKEN(STR_FORM_TIME_OUT_HELP),
+ flags = INTERACTIVE,
+ key = FORM_TIME_OUT_ID;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ text
+ help = STRING_TOKEN(STR_RESET),
+ text = STRING_TOKEN(STR_RESET),
+ flags = INTERACTIVE,
+ key = FORM_RESET;
+
+ endform;
+
+ form formid = FORM_BOOT_SETUP_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_SETUP_TITLE);
+
+ goto FORM_MAIN_ID,
+ prompt = STRING_TOKEN(STR_FORM_GOTO_MAIN),
+ help = STRING_TOKEN(STR_FORM_GOTO_MAIN);
+ //flags = INTERACTIVE,
+ //key = FORM_MAIN_ID;
+
+ goto FORM_BOOT_ADD_ID,
+ prompt = STRING_TOKEN(STR_FORM_BOOT_ADD_TITLE),
+ help = STRING_TOKEN(STR_FORM_BOOT_ADD_HELP),
+ flags = INTERACTIVE,
+ key = FORM_BOOT_ADD_ID;
+
+ goto FORM_BOOT_DEL_ID,
+ prompt = STRING_TOKEN(STR_FORM_BOOT_DEL_TITLE),
+ help = STRING_TOKEN(STR_FORM_BOOT_IMMEDIATE_HELP),
+ flags = INTERACTIVE,
+ key = FORM_BOOT_DEL_ID;
+
+ goto FORM_BOOT_CHG_ID,
+ prompt = STRING_TOKEN(STR_FORM_BOOT_CHG_TITLE),
+ help = STRING_TOKEN(STR_FORM_BOOT_IMMEDIATE_HELP),
+ flags = INTERACTIVE,
+ key = FORM_BOOT_CHG_ID;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+ //
+ // We will add "Select Legacy Boot Floppy Drive" and "Select Legacy Boot Hard Drive"
+ // here dynamically
+ //
+ label FORM_BOOT_LEGACY_DEVICE_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_DRIVER_SETUP_ID,
+ title = STRING_TOKEN(STR_FORM_DRIVER_SETUP_TITLE);
+
+ goto FORM_MAIN_ID,
+ prompt = STRING_TOKEN(STR_FORM_GOTO_MAIN),
+ help = STRING_TOKEN(STR_FORM_GOTO_MAIN);
+ //help = STRING_TOKEN(STR_FORM_GOTO_MAIN),
+ //flags = INTERACTIVE,
+ //key = FORM_MAIN_ID;
+
+ goto FORM_DRV_ADD_ID,
+ prompt = STRING_TOKEN(STR_FORM_DRV_ADD_TITLE),
+ help = STRING_TOKEN(STR_FORM_DRV_ADD_HELP),
+ flags = INTERACTIVE,
+ key = FORM_DRV_ADD_ID;
+
+ goto FORM_DRV_DEL_ID,
+ prompt = STRING_TOKEN(STR_FORM_DRV_DEL_TITLE),
+ help = STRING_TOKEN(STR_FORM_NEXT_BOOT_HELP),
+ flags = INTERACTIVE,
+ key = FORM_DRV_DEL_ID;
+
+ goto FORM_DRV_CHG_ID,
+ prompt = STRING_TOKEN(STR_FORM_DRV_CHG_TITLE),
+ help = STRING_TOKEN(STR_FORM_NEXT_BOOT_HELP),
+ flags = INTERACTIVE,
+ key = FORM_DRV_CHG_ID;
+ endform;
+
+ form formid = FORM_BOOT_DEL_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_DEL_TITLE);
+
+ label FORM_BOOT_DEL_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_BOOT_CHG_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_CHG_TITLE);
+
+ label FORM_BOOT_CHG_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_BOOT_NEXT_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_NEXT_TITLE);
+
+ label FORM_BOOT_NEXT_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_TIME_OUT_ID,
+ title = STRING_TOKEN(STR_FORM_TIME_OUT_TITLE);
+
+ label FORM_TIME_OUT_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_DRV_ADD_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_ADD_TITLE);
+
+ goto FORM_MAIN_ID,
+ prompt = STRING_TOKEN(STR_FORM_GOTO_MAIN),
+ help = STRING_TOKEN(STR_FORM_GOTO_MAIN);
+ //flags = INTERACTIVE,
+ //key = FORM_MAIN_ID;
+
+ goto FORM_DRV_ADD_FILE_ID,
+ prompt = STRING_TOKEN(STR_FORM_DRV_ADD_FILE_TITLE),
+ help = STRING_TOKEN(STR_FORM_DRV_ADD_FILE_TITLE),
+ flags = INTERACTIVE,
+ key = FORM_DRV_ADD_FILE_ID;
+
+ endform;
+
+ form formid = FORM_DRV_DEL_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_DEL_TITLE);
+
+ label FORM_DRV_DEL_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_DRV_CHG_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_CHG_TITLE);
+
+ label FORM_DRV_CHG_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_CON_MAIN_ID,
+ title = STRING_TOKEN(STR_FORM_CON_MAIN_TITLE);
+
+ goto FORM_MAIN_ID,
+ prompt = STRING_TOKEN(STR_FORM_GOTO_MAIN),
+ help = STRING_TOKEN(STR_FORM_GOTO_MAIN);
+ //flags = INTERACTIVE,
+ //key = FORM_MAIN_ID;
+
+ goto FORM_CON_IN_ID,
+ prompt = STRING_TOKEN(STR_FORM_CON_IN_TITLE),
+ help = STRING_TOKEN(STR_FORM_CON_IN_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_IN_ID;
+
+ goto FORM_CON_OUT_ID,
+ prompt = STRING_TOKEN(STR_FORM_CON_OUT_TITLE),
+ help = STRING_TOKEN(STR_FORM_CON_OUT_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_OUT_ID;
+
+ goto FORM_CON_ERR_ID,
+ prompt = STRING_TOKEN(STR_FORM_STD_ERR_TITLE),
+ help = STRING_TOKEN(STR_FORM_STD_ERR_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_ERR_ID;
+
+ goto FORM_CON_MODE_ID,
+ prompt = STRING_TOKEN(STR_FORM_MODE_TITLE),
+ help = STRING_TOKEN(STR_FORM_MODE_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_MODE_ID;
+
+ goto FORM_CON_COM_ID,
+ prompt = STRING_TOKEN(STR_FORM_COM_TITLE),
+ help = STRING_TOKEN(STR_FORM_COM_HELP),
+ flags = INTERACTIVE,
+ key = FORM_CON_COM_ID;
+ endform;
+
+ form formid = FORM_CON_MODE_ID,
+ title = STRING_TOKEN(STR_FORM_MODE_TITLE);
+
+ label FORM_CON_MODE_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_CON_COM_ID,
+ title = STRING_TOKEN(STR_FORM_COM_TITLE);
+
+ label FORM_CON_COM_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_CON_COM_SETUP_ID,
+ title = STRING_TOKEN(STR_CON_COM_SETUP);
+
+ label FORM_CON_COM_SETUP_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_FILE_SEEK_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_ADD_TITLE);
+
+ label FORM_FILE_SEEK_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_FILE_NEW_SEEK_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_ADD_TITLE);
+
+ label FORM_FILE_NEW_SEEK_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_DRV_ADD_HANDLE_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_ADD_HANDLE_TITLE);
+
+ label FORM_DRV_ADD_HANDLE_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_DRV_ADD_HANDLE_DESC_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_ADD_DESC_TITLE);
+
+ label FORM_DRV_ADD_HANDLE_DESC_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_CON_IN_ID,
+ title = STRING_TOKEN(STR_FORM_CON_IN_TITLE);
+
+ label FORM_CON_IN_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_CON_OUT_ID,
+ title = STRING_TOKEN(STR_FORM_CON_OUT_TITLE);
+
+ label FORM_CON_OUT_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_CON_ERR_ID,
+ title = STRING_TOKEN(STR_FORM_STD_ERR_TITLE);
+
+ label FORM_CON_ERR_ID;
+ label LABEL_END;
+
+ endform;
+
+ form formid = FORM_SET_FD_ORDER_ID,
+ title = STRING_TOKEN(STR_FORM_SET_FD_ORDER_TITLE);
+
+ label FORM_SET_FD_ORDER_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_SET_HD_ORDER_ID,
+ title = STRING_TOKEN(STR_FORM_SET_HD_ORDER_TITLE);
+
+ label FORM_SET_HD_ORDER_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_SET_CD_ORDER_ID,
+ title = STRING_TOKEN(STR_FORM_SET_CD_ORDER_TITLE);
+
+ label FORM_SET_CD_ORDER_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_SET_NET_ORDER_ID,
+ title = STRING_TOKEN(STR_FORM_SET_NET_ORDER_TITLE);
+
+ label FORM_SET_NET_ORDER_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_SET_BEV_ORDER_ID,
+ title = STRING_TOKEN(STR_FORM_SET_BEV_ORDER_TITLE);
+
+ label FORM_SET_BEV_ORDER_ID;
+ label LABEL_END;
+ endform;
+
+endformset;
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BmLib.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BmLib.c
new file mode 100644
index 0000000000..4424831859
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BmLib.c
@@ -0,0 +1,411 @@
+/** @file
+ Utility routines used by boot maintenance modules.
+
+Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "BootMaint.h"
+
+/**
+
+ Function opens and returns a file handle to the root directory of a volume.
+
+ @param DeviceHandle A handle for a device
+
+ @return A valid file handle or NULL is returned
+
+**/
+EFI_FILE_HANDLE
+EfiLibOpenRoot (
+ IN EFI_HANDLE DeviceHandle
+ )
+{
+ EFI_STATUS Status;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume;
+ EFI_FILE_HANDLE File;
+
+ File = NULL;
+
+ //
+ // File the file system interface to the device
+ //
+ Status = gBS->HandleProtocol (
+ DeviceHandle,
+ &gEfiSimpleFileSystemProtocolGuid,
+ (VOID *) &Volume
+ );
+
+ //
+ // Open the root directory of the volume
+ //
+ if (!EFI_ERROR (Status)) {
+ Status = Volume->OpenVolume (
+ Volume,
+ &File
+ );
+ }
+ //
+ // Done
+ //
+ return EFI_ERROR (Status) ? NULL : File;
+}
+
+/**
+
+ Helper function called as part of the code needed
+ to allocate the proper sized buffer for various
+ EFI interfaces.
+
+
+ @param Status Current status
+ @param Buffer Current allocated buffer, or NULL
+ @param BufferSize Current buffer size needed
+
+ @retval TRUE if the buffer was reallocated and the caller
+ should try the API again.
+ @retval FALSE The caller should not call this function again.
+
+**/
+BOOLEAN
+EfiGrowBuffer (
+ IN OUT EFI_STATUS *Status,
+ IN OUT VOID **Buffer,
+ IN UINTN BufferSize
+ )
+{
+ BOOLEAN TryAgain;
+
+ //
+ // If this is an initial request, buffer will be null with a new buffer size
+ //
+ if ((*Buffer == NULL) && (BufferSize != 0)) {
+ *Status = EFI_BUFFER_TOO_SMALL;
+ }
+ //
+ // If the status code is "buffer too small", resize the buffer
+ //
+ TryAgain = FALSE;
+ if (*Status == EFI_BUFFER_TOO_SMALL) {
+
+ if (*Buffer != NULL) {
+ FreePool (*Buffer);
+ }
+
+ *Buffer = AllocateZeroPool (BufferSize);
+
+ if (*Buffer != NULL) {
+ TryAgain = TRUE;
+ } else {
+ *Status = EFI_OUT_OF_RESOURCES;
+ }
+ }
+ //
+ // If there's an error, free the buffer
+ //
+ if (!TryAgain && EFI_ERROR (*Status) && (*Buffer != NULL)) {
+ FreePool (*Buffer);
+ *Buffer = NULL;
+ }
+
+ return TryAgain;
+}
+
+/**
+ Function returns the value of the specified variable.
+
+
+ @param Name A Null-terminated Unicode string that is
+ the name of the vendor's variable.
+ @param VendorGuid A unique identifier for the vendor.
+
+ @return The payload of the variable.
+ @retval NULL If the variable can't be read.
+
+**/
+VOID *
+EfiLibGetVariable (
+ IN CHAR16 *Name,
+ IN EFI_GUID *VendorGuid
+ )
+{
+ UINTN VarSize;
+
+ return BdsLibGetVariableAndSize (Name, VendorGuid, &VarSize);
+}
+
+/**
+ Function deletes the variable specified by VarName and VarGuid.
+
+ @param VarName A Null-terminated Unicode string that is
+ the name of the vendor's variable.
+
+ @param VarGuid A unique identifier for the vendor.
+
+ @retval EFI_SUCCESS The variable was found and removed
+ @retval EFI_UNSUPPORTED The variable store was inaccessible
+ @retval EFI_OUT_OF_RESOURCES The temporary buffer was not available
+ @retval EFI_NOT_FOUND The variable was not found
+
+**/
+EFI_STATUS
+EfiLibDeleteVariable (
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VarGuid
+ )
+{
+ VOID *VarBuf;
+ EFI_STATUS Status;
+
+ VarBuf = EfiLibGetVariable (VarName, VarGuid);
+ Status = EFI_NOT_FOUND;
+
+ if (VarBuf != NULL) {
+ //
+ // Delete variable from Storage
+ //
+ Status = gRT->SetVariable (
+ VarName,
+ VarGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ 0,
+ NULL
+ );
+ //
+ // Deleting variable with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ FreePool (VarBuf);
+ }
+
+ return Status;
+}
+
+/**
+
+ Function gets the file system information from an open file descriptor,
+ and stores it in a buffer allocated from pool.
+
+
+ @param FHand The file handle.
+
+ @return A pointer to a buffer with file information.
+ @retval NULL is returned if failed to get Vaolume Label Info.
+
+**/
+EFI_FILE_SYSTEM_VOLUME_LABEL *
+EfiLibFileSystemVolumeLabelInfo (
+ IN EFI_FILE_HANDLE FHand
+ )
+{
+ EFI_STATUS Status;
+ EFI_FILE_SYSTEM_VOLUME_LABEL *Buffer;
+ UINTN BufferSize;
+ //
+ // Initialize for GrowBuffer loop
+ //
+ Buffer = NULL;
+ BufferSize = SIZE_OF_EFI_FILE_SYSTEM_VOLUME_LABEL + 200;
+
+ //
+ // Call the real function
+ //
+ while (EfiGrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) {
+ Status = FHand->GetInfo (
+ FHand,
+ &gEfiFileSystemVolumeLabelInfoIdGuid,
+ &BufferSize,
+ Buffer
+ );
+ }
+
+ return Buffer;
+}
+
+/**
+ Duplicate a string.
+
+ @param Src The source.
+
+ @return A new string which is duplicated copy of the source.
+ @retval NULL If there is not enough memory.
+
+**/
+CHAR16 *
+EfiStrDuplicate (
+ IN CHAR16 *Src
+ )
+{
+ CHAR16 *Dest;
+ UINTN Size;
+
+ Size = StrSize (Src);
+ Dest = AllocateZeroPool (Size);
+ ASSERT (Dest != NULL);
+ if (Dest != NULL) {
+ CopyMem (Dest, Src, Size);
+ }
+
+ return Dest;
+}
+
+/**
+
+ Function gets the file information from an open file descriptor, and stores it
+ in a buffer allocated from pool.
+
+ @param FHand File Handle.
+
+ @return A pointer to a buffer with file information or NULL is returned
+
+**/
+EFI_FILE_INFO *
+EfiLibFileInfo (
+ IN EFI_FILE_HANDLE FHand
+ )
+{
+ EFI_STATUS Status;
+ EFI_FILE_INFO *Buffer;
+ UINTN BufferSize;
+
+ //
+ // Initialize for GrowBuffer loop
+ //
+ Buffer = NULL;
+ BufferSize = SIZE_OF_EFI_FILE_INFO + 200;
+
+ //
+ // Call the real function
+ //
+ while (EfiGrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) {
+ Status = FHand->GetInfo (
+ FHand,
+ &gEfiFileInfoGuid,
+ &BufferSize,
+ Buffer
+ );
+ }
+
+ return Buffer;
+}
+
+/**
+ Function is used to determine the number of device path instances
+ that exist in a device path.
+
+
+ @param DevicePath A pointer to a device path data structure.
+
+ @return This function counts and returns the number of device path instances
+ in DevicePath.
+
+**/
+UINTN
+EfiDevicePathInstanceCount (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ )
+{
+ UINTN Count;
+ UINTN Size;
+
+ Count = 0;
+ while (GetNextDevicePathInstance (&DevicePath, &Size) != NULL) {
+ Count += 1;
+ }
+
+ return Count;
+}
+
+/**
+ Adjusts the size of a previously allocated buffer.
+
+
+ @param OldPool - A pointer to the buffer whose size is being adjusted.
+ @param OldSize - The size of the current buffer.
+ @param NewSize - The size of the new buffer.
+
+ @return The newly allocated buffer.
+ @retval NULL Allocation failed.
+
+**/
+VOID *
+EfiReallocatePool (
+ IN VOID *OldPool,
+ IN UINTN OldSize,
+ IN UINTN NewSize
+ )
+{
+ VOID *NewPool;
+
+ NewPool = NULL;
+ if (NewSize != 0) {
+ NewPool = AllocateZeroPool (NewSize);
+ }
+
+ if (OldPool != NULL) {
+ if (NewPool != NULL) {
+ CopyMem (NewPool, OldPool, OldSize < NewSize ? OldSize : NewSize);
+ }
+
+ FreePool (OldPool);
+ }
+
+ return NewPool;
+}
+
+/**
+ Get a string from the Data Hub record based on
+ a device path.
+
+ @param DevPath The device Path.
+
+ @return A string located from the Data Hub records based on
+ the device path.
+ @retval NULL If failed to get the String from Data Hub.
+
+**/
+UINT16 *
+EfiLibStrFromDatahub (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevPath
+ )
+{
+ return NULL;
+}
+
+/**
+
+ Find the first instance of this Protocol
+ in the system and return it's interface.
+
+
+ @param ProtocolGuid Provides the protocol to search for
+ @param Interface On return, a pointer to the first interface
+ that matches ProtocolGuid
+
+ @retval EFI_SUCCESS A protocol instance matching ProtocolGuid was found
+ @retval EFI_NOT_FOUND No protocol instances were found that match ProtocolGuid
+
+**/
+EFI_STATUS
+EfiLibLocateProtocol (
+ IN EFI_GUID *ProtocolGuid,
+ OUT VOID **Interface
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol (
+ ProtocolGuid,
+ NULL,
+ (VOID **) Interface
+ );
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bmstring.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bmstring.uni
new file mode 100644
index 0000000000..6066549049
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Bmstring.uni
@@ -0,0 +1,263 @@
+///** @file
+//
+// String definitions for Boot Maintenance Utility.
+//
+// Copyright (c) 2004 - 2010, 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.
+//
+//**/
+
+/=#
+
+#langdef en-US "English"
+#langdef fr-FR "Français"
+
+#string STR_NULL_STRING #language en-US " "
+ #language fr-FR " "
+#string STR_NONE #language en-US "NONE"
+ #language fr-FR "NONE"
+#string STR_FORM_MAIN_TITLE #language en-US "Boot Maintenance Manager"
+ #language fr-FR "Boot Maintenance Manager"
+#string STR_FORM_BOOT_SETUP_TITLE #language en-US "Boot Options"
+ #language fr-FR "Boot Options"
+#string STR_FORM_BOOT_SETUP_HELP #language en-US "Modify system boot options"
+ #language fr-FR "Modify system boot options"
+#string STR_FORM_DRIVER_SETUP_TITLE #language en-US "Driver Options"
+ #language fr-FR "Driver Options"
+#string STR_FORM_DRIVER_SETUP_HELP #language en-US "Modify boot driver options"
+ #language fr-FR "Modify boot driver options"
+#string STR_FORM_BOOT_ADD_TITLE #language en-US "Add Boot Option"
+ #language fr-FR "Add Boot Option"
+#string STR_FORM_BOOT_ADD_HELP #language en-US "Add EFI Application or Removable Fs as Boot Option"
+ #language fr-FR "Add EFI Application or Removable Fs as Boot Option"
+#string STR_FORM_BOOT_DEL_TITLE #language en-US "Delete Boot Option"
+ #language fr-FR "Delete Boot Option"
+#string STR_FORM_BOOT_IMMEDIATE_HELP #language en-US "Will be valid immediately"
+ #language fr-FR "Will be valid immediately"
+#string STR_FORM_BOOT_CHG_TITLE #language en-US "Change Boot Order"
+ #language fr-FR "Change Boot Order"
+#string STR_FORM_DRV_ADD_TITLE #language en-US "Add Driver Option"
+ #language fr-FR "Add Driver Option"
+#string STR_FORM_DRV_ADD_HELP #language en-US "Add .EFI Driver as Driver Option"
+ #language fr-FR "Add .EFI Driver as Driver Option"
+#string STR_FORM_DRV_DEL_TITLE #language en-US "Delete Driver Option"
+ #language fr-FR "Delete Driver Option"
+#string STR_FORM_DRV_CHG_TITLE #language en-US "Change Driver Order"
+ #language fr-FR "Change Driver Order"
+#string STR_FORM_NEXT_BOOT_HELP #language en-US "Will be valid on next boot"
+ #language fr-FR "Will be valid on next boot"
+#string STR_FORM_BOOT_NEXT_TITLE #language en-US "Set Boot Next Value"
+ #language fr-FR "Set Boot Next Value"
+#string STR_FORM_BOOT_NEXT_HELP #language en-US "Modify next boot behavior"
+ #language fr-FR "Modify next boot behavior"
+#string STR_FORM_TIME_OUT_TITLE #language en-US "Set Time Out Value"
+ #language fr-FR "Set Time Out Value"
+#string STR_FORM_TIME_OUT_HELP #language en-US "Modify automatic boot time-out value"
+ #language fr-FR "Modify automatic boot time-out value"
+#string STR_FORM_CON_MAIN_TITLE #language en-US "Console Options"
+ #language fr-FR "Console Options"
+#string STR_FORM_CON_MAIN_HELP #language en-US "Modify system console options"
+ #language fr-FR "Modify system console options"
+#string STR_FORM_CON_IN_TITLE #language en-US "Console Input Device Select"
+ #language fr-FR "Console Input Device Select"
+#string STR_FORM_CON_IN_HELP #language en-US "Enable console device as ConIn"
+ #language fr-FR "Enable console device as ConIn"
+#string STR_FORM_SET_FD_ORDER_TITLE #language en-US "Set Legacy Floppy Drive Order"
+ #language fr-FR "Set Legacy Floppy Drive Order"
+#string STR_FORM_SET_HD_ORDER_TITLE #language en-US "Set Legacy HardDisk Drive Order"
+ #language fr-FR "Set Legacy HardDisk Drive Order"
+#string STR_FORM_SET_CD_ORDER_TITLE #language en-US "Set Legacy CD-ROM Drive Order"
+ #language fr-FR "Set Legacy CD-ROM Drive Order"
+#string STR_FORM_SET_NET_ORDER_TITLE #language en-US "Set Legacy NET Drive Order"
+ #language fr-FR "Set Legacy NET Drive Order"
+#string STR_FORM_SET_BEV_ORDER_TITLE #language en-US "Set Legacy BEV Drive Order"
+ #language fr-FR "Set Legacy BEV Drive Order"
+#string STR_FORM_GOTO_SETTING #language en-US "Go Back To Setting Page"
+ #language fr-FR "Go Back To Setting Page"
+#string STR_COM1 #language en-US "COM1"
+ #language fr-FR "COM1"
+#string STR_COM2 #language en-US "COM2"
+ #language fr-FR "COM2"
+#string STR_COM_AS_CONSOLE_OPTION #language en-US "Select this COM port as Console"
+ #language fr-FR "Select this COM port as Console"
+#string STR_FORM_CON_OUT_TITLE #language en-US "Console Output Device Select"
+ #language fr-FR "Console Output Device Select"
+#string STR_FORM_CON_OUT_HELP #language en-US "Enable console device as ConOut"
+ #language fr-FR "Enable console device as ConOut"
+#string STR_FORM_STD_ERR_TITLE #language en-US "Console Standard Error Device Select"
+ #language fr-FR "Console Standard Error Device Select"
+#string STR_FORM_STD_ERR_HELP #language en-US "Enable console device as StdErr"
+ #language fr-FR "Enable console device as StdErr"
+#string STR_FORM_MODE_TITLE #language en-US "Console Output Mode Select"
+ #language fr-FR "Console Output Mode Select"
+#string STR_FORM_MODE_HELP #language en-US "Select Console Output Mode: 80x25, 100x31, etc."
+ #language fr-FR "Select Console Output Mode: 80x25, 100x31, etc."
+#string STR_FORM_COM_TITLE #language en-US "COM Attribute Setup Page"
+ #language fr-FR "COM Attribute Setup Page"
+#string STR_FORM_COM_HELP #language en-US "Setup ComPort BaudRate, DataBits, StopBits, Parity and TerminalType"
+ #language fr-FR "Setup ComPort BaudRate, DataBits, StopBits, Parity and TerminalType"
+#string STR_FORM_DRV_ADD_FILE_TITLE #language en-US "Add Driver Option Using File"
+ #language fr-FR "Add Driver Option Using File"
+#string STR_FORM_DRV_ADD_HANDLE_TITLE #language en-US "Add Driver Option Using Handle"
+ #language fr-FR "Add Driver Option Using Handle"
+#string STR_FORM_BOOT_ADD_DESC_TITLE #language en-US "Modify Boot Option Description"
+ #language fr-FR "Modify Boot Option Description"
+#string STR_FORM_DRV_ADD_DESC_TITLE #language en-US "Modify Driver Option Description"
+ #language fr-FR "Modify Driver Option Description"
+#string STR_NUM_AUTO_BOOT #language en-US "Auto Boot Time-out"
+ #language fr-FR "Auto Boot Time-out"
+#string STR_HLP_AUTO_BOOT #language en-US "Range: 0 to 65535 seconds, 0 means no wait, 65535 means waiting for key"
+ #language fr-FR "Range: 0 to 65535 seconds, 0 means no wait, 65535 means waiting for key"
+#string STR_BOOT_NEXT #language en-US "Boot Next Value"
+ #language fr-FR "Boot Next Value"
+#string STR_BOOT_NEXT_HELP #language en-US "Next boot use this boot option"
+ #language fr-FR "Next boot use this boot option"
+#string STR_LOAD_OPTION_DEVPATH #language en-US "This is the devicepath"
+ #language fr-FR "This is the devicepath"
+#string STR_LOAD_OPTION_DESC #language en-US "Input the description"
+ #language fr-FR "Input the description"
+#string STR_LOAD_OPTION_ACTIVE #language en-US "Load Option Active"
+ #language fr-FR "Load Option Active"
+#string STR_LOAD_OPTION_FORCE_RECON #language en-US "Load Option Reconnect"
+ #language fr-FR "Load Option Reconnect"
+#string STR_SAVE_AND_EXIT #language en-US "Commit Changes and Exit"
+ #language fr-FR "Commit Changes and Exit"
+#string STR_NO_SAVE_AND_EXIT #language en-US "Discard Changes and Exit"
+ #language fr-FR "Discard Changes and Exit"
+#string STR_CON_IN_SETUP #language en-US "Set Console Input Device"
+ #language fr-FR "Set Console Input Device"
+#string STR_CON_OUT_SETUP #language en-US "Set Console Output Device"
+ #language fr-FR "Set Console Output Device"
+#string STR_CON_ERR_SETUP #language en-US "Set Error Output Device"
+ #language fr-FR "Set Error Output Device"
+#string STR_CON_MODE_SETUP #language en-US "Set Console Output Mode"
+ #language fr-FR "Set Console Output Mode"
+#string STR_CON_COM_SETUP #language en-US "Set COM Attributes"
+ #language fr-FR "Set COM Attributes"
+#string STR_COM_TERMI_TYPE #language en-US "Set COM Terminal Type"
+ #language fr-FR "Set COM Terminal Type"
+#string STR_COM_FLOW_CONTROL #language en-US "Set COM Flow Control"
+ #language fr-FR "Set COM Flow Control"
+#string STR_COM_BAUD_RATE #language en-US "Set COM Baud Rate"
+ #language fr-FR "Set COM Baud Rate"
+#string STR_COM_DATA_BITS #language en-US "Set COM Data Bits"
+ #language fr-FR "Set COM Data Bits"
+#string STR_COM_PARITY #language en-US "Set COM Parity"
+ #language fr-FR "Set COM Parity"
+#string STR_COM_STOP_BITS #language en-US "Set COM Stop Bits"
+ #language fr-FR "Set COM Stop Bits"
+#string STR_COM_BAUD_RATE_0 #language en-US "115200"
+ #language fr-FR "115200"
+#string STR_COM_BAUD_RATE_1 #language en-US "57600"
+ #language fr-FR "57600"
+#string STR_COM_BAUD_RATE_2 #language en-US "38400"
+ #language fr-FR "38400"
+#string STR_COM_BAUD_RATE_3 #language en-US "19200"
+ #language fr-FR "19200"
+#string STR_COM_BAUD_RATE_4 #language en-US "9600"
+ #language fr-FR "9600"
+#string STR_COM_BAUD_RATE_5 #language en-US "7200"
+ #language fr-FR "7200"
+#string STR_COM_BAUD_RATE_6 #language en-US "4800"
+ #language fr-FR "4800"
+#string STR_COM_BAUD_RATE_7 #language en-US "3600"
+ #language fr-FR "3600"
+#string STR_COM_BAUD_RATE_8 #language en-US "2400"
+ #language fr-FR "2400"
+#string STR_COM_BAUD_RATE_9 #language en-US "2000"
+ #language fr-FR "2000"
+#string STR_COM_BAUD_RATE_10 #language en-US "1800"
+ #language fr-FR "1800"
+#string STR_COM_BAUD_RATE_11 #language en-US "1200"
+ #language fr-FR "1200"
+#string STR_COM_BAUD_RATE_12 #language en-US "600"
+ #language fr-FR "600"
+#string STR_COM_BAUD_RATE_13 #language en-US "300"
+ #language fr-FR "300"
+#string STR_COM_BAUD_RATE_14 #language en-US "150"
+ #language fr-FR "150"
+#string STR_COM_BAUD_RATE_15 #language en-US "134"
+ #language fr-FR "134"
+#string STR_COM_BAUD_RATE_16 #language en-US "110"
+ #language fr-FR "110"
+#string STR_COM_BAUD_RATE_17 #language en-US "75"
+ #language fr-FR "75"
+#string STR_COM_BAUD_RATE_18 #language en-US "50"
+ #language fr-FR "50"
+#string STR_COM_DATA_BITS_0 #language en-US "5"
+ #language fr-FR "5"
+#string STR_COM_DATA_BITS_1 #language en-US "6"
+ #language fr-FR "6"
+#string STR_COM_DATA_BITS_2 #language en-US "7"
+ #language fr-FR "7"
+#string STR_COM_DATA_BITS_3 #language en-US "8"
+ #language fr-FR "8"
+#string STR_COM_PAR_0 #language en-US "None"
+ #language fr-FR "None"
+#string STR_COM_PAR_1 #language en-US "Even"
+ #language fr-FR "Even"
+#string STR_COM_PAR_2 #language en-US "Odd"
+ #language fr-FR "Odd"
+#string STR_COM_PAR_3 #language en-US "Mark"
+ #language fr-FR "Mark"
+#string STR_COM_PAR_4 #language en-US "Space"
+ #language fr-FR "Space"
+#string STR_COM_STOP_BITS_0 #language en-US "One"
+ #language fr-FR "One"
+#string STR_COM_STOP_BITS_1 #language en-US "One And A Half"
+ #language fr-FR "One And A Half"
+#string STR_COM_STOP_BITS_2 #language en-US "Two"
+ #language fr-FR "Two"
+#string STR_COM_TYPE_0 #language en-US "PC_ANSI"
+ #language fr-FR "PC_ANSI"
+#string STR_COM_TYPE_1 #language en-US "VT_100"
+ #language fr-FR "VT_100"
+#string STR_COM_TYPE_2 #language en-US "VT_100_PLUS"
+ #language fr-FR "VT_100_PLUS"
+#string STR_COM_TYPE_3 #language en-US "VT_UTF8"
+ #language fr-FR "VT_UTF8"
+#string STR_RESET #language en-US "Reset System"
+ #language fr-FR "Reset System"
+#string STR_FORM_GOTO_MAIN #language en-US "Go Back To Main Page"
+ #language fr-FR "Go Back To Main Page"
+#string STR_BOOT_FROM_FILE #language en-US "Boot From File"
+ #language fr-FR "Boot From File"
+#string STR_BOOT_FROM_FILE_HELP #language en-US "Boot system from a file or device"
+ #language fr-FR "Boot system from a file or device"
+#string STR_OPTIONAL_DATA #language en-US "Input Optional Data"
+ #language fr-FR "Input Optional Data"
+#string STR_CHANGE_ORDER #language en-US "Change the order"
+ #language fr-FR "Change the order"
+#string STR_BOOT_LEGACY #language en-US "Boot Legacy System"
+ #language fr-FR "Boot Legacy System"
+#string STR_BOOT_LEGACY_HELP #language en-US "Supports boot from legacy FD, HD, CD, PCMCIA, USB, and Network"
+ #language fr-FR "Supports boot from legacy FD, HD, CD, PCMCIA, USB, and Network"
+#string STR_BOOT_LEGACY_FLOPPY #language en-US "Boot From Floppy"
+ #language fr-FR "Boot From Floppy"
+#string STR_BOOT_LEGACY_HARDDRIVE #language en-US "Boot From Hard Drive"
+ #language fr-FR "Boot From Hard Drive"
+#string STR_BOOT_LEGACY_CDROM #language en-US "Boot From CD Rom"
+ #language fr-FR "Boot From CD Rom"
+#string STR_BOOT_LEGACY_PCMCIA #language en-US "Boot From PCMCIA"
+ #language fr-FR "Boot From PCMCIA"
+#string STR_BOOT_LEGACY_USB #language en-US "Boot From USB Device"
+ #language fr-FR "Boot From USB Device"
+#string STR_BOOT_LEGACY_NETWORK #language en-US "Boot From Network"
+ #language fr-FR "Boot From Network"
+#string STR_DISABLE_LEGACY_DEVICE #language en-US "Disabled"
+ #language fr-FR "Disabled"
+#string STR_FILE_EXPLORER_TITLE #language en-US "File Explorer"
+ #language fr-FR "File Explorer"
+#string STR_HARDWARE_FLOW_CONTROL #language fr-FR "Hardware"
+ #language en-US "Hardware"
+#string STR_NONE_FLOW_CONTROL #language fr-FR "None"
+ #language en-US "None"
+//
+// BugBug : need someone to translate these strings to french
+//
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.c
new file mode 100644
index 0000000000..d5ea0f4577
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.c
@@ -0,0 +1,1690 @@
+/** @file
+ The functions for Boot Maintainence Main menu.
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BootMaint.h"
+#include "FormGuid.h"
+#include "Bds.h"
+#include "FrontPage.h"
+
+EFI_DEVICE_PATH_PROTOCOL EndDevicePath[] = {
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ END_DEVICE_PATH_LENGTH,
+ 0
+ }
+ }
+};
+
+HII_VENDOR_DEVICE_PATH mBmmHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ BOOT_MAINT_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+HII_VENDOR_DEVICE_PATH mFeHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ FILE_EXPLORE_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+CHAR16 mBootMaintStorageName[] = L"BmmData";
+CHAR16 mFileExplorerStorageName[] = L"FeData";
+BMM_CALLBACK_DATA *mBmmCallbackInfo = NULL;
+
+/**
+ Init all memu.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+InitAllMenu (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Free up all Menu Option list.
+
+**/
+VOID
+FreeAllMenu (
+ VOID
+ );
+
+/**
+ Initialize all of BMM configuration data in BmmFakeNvData and BmmOldFakeNVData member
+ in BMM context data and create all of dynamic OP code for BMM.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+InitializeBmmConfig (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 Index;
+
+ ASSERT (CallbackData != NULL);
+
+ //
+ // Initialize data which located in BMM main page
+ //
+ CallbackData->BmmFakeNvData.BootNext = (UINT16) (BootOptionMenu.MenuNumber);
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewLoadContext->IsBootNext) {
+ CallbackData->BmmFakeNvData.BootNext = Index;
+ break;
+ }
+ }
+
+ CallbackData->BmmFakeNvData.BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
+
+ //
+ // Initialize data which located in Boot Options Menu
+ //
+ GetBootOrder (CallbackData);
+ GetLegacyDeviceOrder (CallbackData);
+
+ //
+ // Initialize data which located in Driver Options Menu
+ //
+ GetDriverOrder (CallbackData);
+
+ //
+ // Initialize data which located in Console Options Menu
+ //
+ GetConsoleOutMode (CallbackData);
+ GetConsoleInCheck (CallbackData);
+ GetConsoleOutCheck (CallbackData);
+ GetConsoleErrCheck (CallbackData);
+ GetTerminalAttribute (CallbackData);
+
+ //
+ // Backup Initialize BMM configuartion data to BmmOldFakeNVData
+ //
+ CopyMem (&CallbackData->BmmOldFakeNVData, &CallbackData->BmmFakeNvData, sizeof (BMM_FAKE_NV_DATA));
+}
+
+/**
+ Create string tokens for a menu from its help strings and display strings
+
+ @param CallbackData The BMM context data.
+ @param HiiHandle Hii Handle of the package to be updated.
+ @param MenuOption The Menu whose string tokens need to be created
+
+ @retval EFI_SUCCESS String tokens created successfully
+ @retval others contain some errors
+**/
+EFI_STATUS
+CreateMenuStringToken (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_HII_HANDLE HiiHandle,
+ IN BM_MENU_OPTION *MenuOption
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINTN Index;
+
+ for (Index = 0; Index < MenuOption->MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (MenuOption, Index);
+
+ NewMenuEntry->DisplayStringToken = HiiSetString (
+ HiiHandle,
+ 0,
+ NewMenuEntry->DisplayString,
+ NULL
+ );
+
+ if (NULL == NewMenuEntry->HelpString) {
+ NewMenuEntry->HelpStringToken = NewMenuEntry->DisplayStringToken;
+ } else {
+ NewMenuEntry->HelpStringToken = HiiSetString (
+ HiiHandle,
+ 0,
+ NewMenuEntry->HelpString,
+ NULL
+ );
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function allows a caller to extract the current configuration for one
+ or more named elements from the target driver.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Request A null-terminated Unicode string in <ConfigRequest> format.
+ @param Progress On return, points to a character in the Request string.
+ Points to the string's null terminator if request was successful.
+ Points to the most recent '&' before the first failing name/value
+ pair (or the beginning of the string if the failure is in the
+ first name/value pair) if the request was not successful.
+ @param Results A null-terminated Unicode string in <ConfigAltResp> format which
+ has all values filled in for the names in the Request string.
+ String to be allocated by the called function.
+
+ @retval EFI_SUCCESS The Results is filled with the requested values.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the results.
+ @retval EFI_INVALID_PARAMETER Request is NULL, illegal syntax, or unknown name.
+ @retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
+
+**/
+EFI_STATUS
+EFIAPI
+BootMaintExtractConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Request,
+ OUT EFI_STRING *Progress,
+ OUT EFI_STRING *Results
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ BMM_CALLBACK_DATA *Private;
+ EFI_STRING ConfigRequestHdr;
+ EFI_STRING ConfigRequest;
+ BOOLEAN AllocatedRequest;
+ UINTN Size;
+
+ if (Progress == NULL || Results == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *Progress = Request;
+ if ((Request != NULL) && !HiiIsConfigHdrMatch (Request, &gBootMaintFormSetGuid, mBootMaintStorageName)) {
+ return EFI_NOT_FOUND;
+ }
+
+ ConfigRequestHdr = NULL;
+ ConfigRequest = NULL;
+ AllocatedRequest = FALSE;
+ Size = 0;
+
+ Private = BMM_CALLBACK_DATA_FROM_THIS (This);
+ //
+ // Convert buffer data to <ConfigResp> by helper function BlockToConfig()
+ //
+ BufferSize = sizeof (BMM_FAKE_NV_DATA);
+ ConfigRequest = Request;
+ if ((Request == NULL) || (StrStr (Request, L"OFFSET") == NULL)) {
+ //
+ // Request has no request element, construct full request string.
+ // Allocate and fill a buffer large enough to hold the <ConfigHdr> template
+ // followed by "&OFFSET=0&WIDTH=WWWWWWWWWWWWWWWW" followed by a Null-terminator
+ //
+ ConfigRequestHdr = HiiConstructConfigHdr (&gBootMaintFormSetGuid, mBootMaintStorageName, Private->BmmDriverHandle);
+ Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16);
+ ConfigRequest = AllocateZeroPool (Size);
+ ASSERT (ConfigRequest != NULL);
+ AllocatedRequest = TRUE;
+ UnicodeSPrint (ConfigRequest, Size, L"%s&OFFSET=0&WIDTH=%016LX", ConfigRequestHdr, (UINT64)BufferSize);
+ FreePool (ConfigRequestHdr);
+ }
+
+ Status = gHiiConfigRouting->BlockToConfig (
+ gHiiConfigRouting,
+ ConfigRequest,
+ (UINT8 *) &Private->BmmFakeNvData,
+ BufferSize,
+ Results,
+ Progress
+ );
+ //
+ // Free the allocated config request string.
+ //
+ if (AllocatedRequest) {
+ FreePool (ConfigRequest);
+ ConfigRequest = NULL;
+ }
+ //
+ // Set Progress string to the original request string.
+ //
+ if (Request == NULL) {
+ *Progress = NULL;
+ } else if (StrStr (Request, L"OFFSET") == NULL) {
+ *Progress = Request + StrLen (Request);
+ }
+
+ return Status;
+}
+
+/**
+ This function applies changes in a driver's configuration.
+ Input is a Configuration, which has the routing data for this
+ driver followed by name / value configuration pairs. The driver
+ must apply those pairs to its configurable storage. If the
+ driver's configuration is stored in a linear block of data
+ and the driver's name / value pairs are in <BlockConfig>
+ format, it may use the ConfigToBlock helper function (above) to
+ simplify the job. Currently not implemented.
+
+ @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param[in] Configuration A null-terminated Unicode string in
+ <ConfigString> format.
+ @param[out] Progress A pointer to a string filled in with the
+ offset of the most recent '&' before the
+ first failing name / value pair (or the
+ beginn ing of the string if the failure
+ is in the first name / value pair) or
+ the terminating NULL if all was
+ successful.
+
+ @retval EFI_SUCCESS The results have been distributed or are
+ awaiting distribution.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the
+ parts of the results that must be
+ stored awaiting possible future
+ protocols.
+ @retval EFI_INVALID_PARAMETERS Passing in a NULL for the
+ Results parameter would result
+ in this type of error.
+ @retval EFI_NOT_FOUND Target for the specified routing data
+ was not found.
+**/
+EFI_STATUS
+EFIAPI
+BootMaintRouteConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Configuration,
+ OUT EFI_STRING *Progress
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting;
+ BMM_FAKE_NV_DATA *NewBmmData;
+ BMM_FAKE_NV_DATA *OldBmmData;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 Index;
+ BOOLEAN TerminalAttChange;
+ BMM_CALLBACK_DATA *Private;
+
+ if (Progress == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ *Progress = Configuration;
+
+ if (Configuration == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Check routing data in <ConfigHdr>.
+ // Note: there is no name for Name/Value storage, only GUID will be checked
+ //
+ if (!HiiIsConfigHdrMatch (Configuration, &gBootMaintFormSetGuid, mBootMaintStorageName)) {
+ return EFI_NOT_FOUND;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiHiiConfigRoutingProtocolGuid,
+ NULL,
+ (VOID**) &ConfigRouting
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Private = BMM_CALLBACK_DATA_FROM_THIS (This);
+ //
+ // Get Buffer Storage data from EFI variable
+ //
+ BufferSize = sizeof (BMM_FAKE_NV_DATA);
+ OldBmmData = &Private->BmmOldFakeNVData;
+ NewBmmData = &Private->BmmFakeNvData;
+ //
+ // Convert <ConfigResp> to buffer data by helper function ConfigToBlock()
+ //
+ Status = ConfigRouting->ConfigToBlock (
+ ConfigRouting,
+ Configuration,
+ (UINT8 *) NewBmmData,
+ &BufferSize,
+ Progress
+ );
+ ASSERT_EFI_ERROR (Status);
+ //
+ // Compare new and old BMM configuration data and only do action for modified item to
+ // avoid setting unnecessary non-volatile variable
+ //
+
+ //
+ // Check data which located in BMM main page and save the settings if need
+ //
+ if (CompareMem (NewBmmData->LegacyFD, OldBmmData->LegacyFD, sizeof (NewBmmData->LegacyFD)) != 0) {
+ Var_UpdateBBSOption (Private, FORM_SET_FD_ORDER_ID);
+ }
+
+ if (CompareMem (NewBmmData->LegacyHD, OldBmmData->LegacyHD, sizeof (NewBmmData->LegacyHD)) != 0) {
+ Var_UpdateBBSOption (Private, FORM_SET_HD_ORDER_ID);
+ }
+
+ if (CompareMem (NewBmmData->LegacyCD, OldBmmData->LegacyCD, sizeof (NewBmmData->LegacyCD)) != 0) {
+ Var_UpdateBBSOption (Private, FORM_SET_CD_ORDER_ID);
+ }
+
+ if (CompareMem (NewBmmData->LegacyNET, OldBmmData->LegacyNET, sizeof (NewBmmData->LegacyNET)) != 0) {
+ Var_UpdateBBSOption (Private, FORM_SET_NET_ORDER_ID);
+ }
+
+ if (CompareMem (NewBmmData->LegacyBEV, OldBmmData->LegacyBEV, sizeof (NewBmmData->LegacyBEV)) != 0) {
+ Var_UpdateBBSOption (Private, FORM_SET_BEV_ORDER_ID);
+ }
+
+ //
+ // Change for "delete boot option" page need update NewBmmData->BootOptionOrder, so process
+ // NewBmmData->BootOptionOrder before NewBmmData->BootOptionDel
+ //
+ if (CompareMem (NewBmmData->BootOptionOrder, OldBmmData->BootOptionOrder, sizeof (NewBmmData->BootOptionOrder)) != 0) {
+ Status = Var_UpdateBootOrder (Private);
+ }
+
+ //
+ // Change for "delete driver option" page need update NewBmmData->DriverOptionOrder, so process
+ // NewBmmData->DriverOptionOrder before NewBmmData->DriverOptionDel
+ //
+ if (CompareMem (NewBmmData->DriverOptionOrder, OldBmmData->DriverOptionOrder, sizeof (NewBmmData->DriverOptionOrder)) != 0) {
+ Status = Var_UpdateDriverOrder (Private);
+ }
+
+ //
+ // Check data which located in Boot Options Menu and save the settings if need
+ //
+ if (CompareMem (NewBmmData->BootOptionDel, OldBmmData->BootOptionDel, sizeof (NewBmmData->BootOptionDel)) != 0) {
+ for (Index = 0;
+ ((Index < BootOptionMenu.MenuNumber) && (Index < (sizeof (NewBmmData->BootOptionDel) / sizeof (NewBmmData->BootOptionDel[0]))));
+ Index ++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->Deleted = NewBmmData->BootOptionDel[Index];
+ NewBmmData->BootOptionDel[Index] = FALSE;
+ NewBmmData->BootOptionDelMark[Index] = FALSE;
+ }
+
+ Var_DelBootOption ();
+ }
+
+ //
+ // Check data which located in Driver Options Menu and save the settings if need
+ //
+ if (CompareMem (NewBmmData->DriverOptionDel, OldBmmData->DriverOptionDel, sizeof (NewBmmData->DriverOptionDel)) != 0) {
+ for (Index = 0;
+ ((Index < DriverOptionMenu.MenuNumber) && (Index < (sizeof (NewBmmData->DriverOptionDel) / sizeof (NewBmmData->DriverOptionDel[0]))));
+ Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->Deleted = NewBmmData->DriverOptionDel[Index];
+ NewBmmData->DriverOptionDel[Index] = FALSE;
+ NewBmmData->DriverOptionDelMark[Index] = FALSE;
+ }
+ Var_DelDriverOption ();
+ }
+
+ if (CompareMem (&NewBmmData->BootTimeOut, &OldBmmData->BootTimeOut, sizeof (NewBmmData->BootTimeOut)) != 0) {
+ Status = gRT->SetVariable (
+ L"Timeout",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof (UINT16),
+ &(NewBmmData->BootTimeOut)
+ );
+ ASSERT_EFI_ERROR(Status);
+
+ //
+ // Bugbug: code not exit in UiApp but in IntelFrameworkModulePkg, need do more check.
+ //
+ Private->BmmOldFakeNVData.BootTimeOut = NewBmmData->BootTimeOut;
+ }
+
+ if (CompareMem (&NewBmmData->BootNext, &OldBmmData->BootNext, sizeof (NewBmmData->BootNext)) != 0) {
+ Status = Var_UpdateBootNext (Private);
+ }
+
+ if (CompareMem (&NewBmmData->ConsoleOutMode, &OldBmmData->ConsoleOutMode, sizeof (NewBmmData->ConsoleOutMode)) != 0) {
+ Var_UpdateConMode (Private);
+ }
+
+ TerminalAttChange = FALSE;
+ for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) {
+
+ //
+ // only need update modified items
+ //
+ if (CompareMem (&NewBmmData->COMBaudRate[Index], &OldBmmData->COMBaudRate[Index], sizeof (NewBmmData->COMBaudRate[Index])) == 0 &&
+ CompareMem (&NewBmmData->COMDataRate[Index], &OldBmmData->COMDataRate[Index], sizeof (NewBmmData->COMDataRate[Index])) == 0 &&
+ CompareMem (&NewBmmData->COMStopBits[Index], &OldBmmData->COMStopBits[Index], sizeof (NewBmmData->COMStopBits[Index])) == 0 &&
+ CompareMem (&NewBmmData->COMParity[Index], &OldBmmData->COMParity[Index], sizeof (NewBmmData->COMParity[Index])) == 0 &&
+ CompareMem (&NewBmmData->COMTerminalType[Index], &OldBmmData->COMTerminalType[Index], sizeof (NewBmmData->COMTerminalType[Index])) == 0 &&
+ CompareMem (&NewBmmData->COMFlowControl[Index], &OldBmmData->COMFlowControl[Index], sizeof (NewBmmData->COMFlowControl[Index])) == 0) {
+ continue;
+ }
+
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index);
+ ASSERT (NewMenuEntry != NULL);
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ NewTerminalContext->BaudRateIndex = NewBmmData->COMBaudRate[Index];
+ ASSERT (NewBmmData->COMBaudRate[Index] < (ARRAY_SIZE (BaudRateList)));
+ NewTerminalContext->BaudRate = BaudRateList[NewBmmData->COMBaudRate[Index]].Value;
+ NewTerminalContext->DataBitsIndex = NewBmmData->COMDataRate[Index];
+ ASSERT (NewBmmData->COMDataRate[Index] < (ARRAY_SIZE (DataBitsList)));
+ NewTerminalContext->DataBits = (UINT8) DataBitsList[NewBmmData->COMDataRate[Index]].Value;
+ NewTerminalContext->StopBitsIndex = NewBmmData->COMStopBits[Index];
+ ASSERT (NewBmmData->COMStopBits[Index] < (ARRAY_SIZE (StopBitsList)));
+ NewTerminalContext->StopBits = (UINT8) StopBitsList[NewBmmData->COMStopBits[Index]].Value;
+ NewTerminalContext->ParityIndex = NewBmmData->COMParity[Index];
+ ASSERT (NewBmmData->COMParity[Index] < (ARRAY_SIZE (ParityList)));
+ NewTerminalContext->Parity = (UINT8) ParityList[NewBmmData->COMParity[Index]].Value;
+ NewTerminalContext->TerminalType = NewBmmData->COMTerminalType[Index];
+ NewTerminalContext->FlowControl = NewBmmData->COMFlowControl[Index];
+ ChangeTerminalDevicePath (
+ &(NewTerminalContext->DevicePath),
+ FALSE
+ );
+ TerminalAttChange = TRUE;
+ }
+ if (TerminalAttChange) {
+ Var_UpdateConsoleInpOption ();
+ Var_UpdateConsoleOutOption ();
+ Var_UpdateErrorOutOption ();
+ }
+
+ //
+ // Check data which located in Console Options Menu and save the settings if need
+ //
+ if (CompareMem (NewBmmData->ConsoleInCheck, OldBmmData->ConsoleInCheck, sizeof (NewBmmData->ConsoleInCheck)) != 0) {
+ for (Index = 0; Index < ConsoleInpMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleInpMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ASSERT (Index < MAX_MENU_NUMBER);
+ NewConsoleContext->IsActive = NewBmmData->ConsoleInCheck[Index];
+ }
+
+ Var_UpdateConsoleInpOption ();
+ }
+
+ if (CompareMem (NewBmmData->ConsoleOutCheck, OldBmmData->ConsoleOutCheck, sizeof (NewBmmData->ConsoleOutCheck)) != 0) {
+ for (Index = 0; Index < ConsoleOutMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleOutMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ASSERT (Index < MAX_MENU_NUMBER);
+ NewConsoleContext->IsActive = NewBmmData->ConsoleOutCheck[Index];
+ }
+
+ Var_UpdateConsoleOutOption ();
+ }
+
+ if (CompareMem (NewBmmData->ConsoleErrCheck, OldBmmData->ConsoleErrCheck, sizeof (NewBmmData->ConsoleErrCheck)) != 0) {
+ for (Index = 0; Index < ConsoleErrMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleErrMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ASSERT (Index < MAX_MENU_NUMBER);
+ NewConsoleContext->IsActive = NewBmmData->ConsoleErrCheck[Index];
+ }
+
+ Var_UpdateErrorOutOption ();
+ }
+
+ //
+ // After user do the save action, need to update OldBmmData.
+ //
+ CopyMem (OldBmmData, NewBmmData, sizeof (BMM_FAKE_NV_DATA));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Create GoTo OP code into FORM_BOOT_LEGACY_DEVICE label for legacy boot option.
+
+**/
+EFI_STATUS
+InitializeLegacyBootOption (
+ VOID
+ )
+{
+ RefreshUpdateData ();
+ mStartLabel->Number = FORM_BOOT_LEGACY_DEVICE_ID;
+
+ //
+ // If LegacyBios Protocol is installed, add 3 tags about legacy boot option
+ // in BootOption form: legacy FD/HD/CD/NET/BEV
+ //
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_SET_FD_ORDER_ID,
+ STRING_TOKEN (STR_FORM_SET_FD_ORDER_TITLE),
+ STRING_TOKEN (STR_FORM_SET_FD_ORDER_TITLE),
+ EFI_IFR_FLAG_CALLBACK,
+ FORM_SET_FD_ORDER_ID
+ );
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_SET_HD_ORDER_ID,
+ STRING_TOKEN (STR_FORM_SET_HD_ORDER_TITLE),
+ STRING_TOKEN (STR_FORM_SET_HD_ORDER_TITLE),
+ EFI_IFR_FLAG_CALLBACK,
+ FORM_SET_HD_ORDER_ID
+ );
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_SET_CD_ORDER_ID,
+ STRING_TOKEN (STR_FORM_SET_CD_ORDER_TITLE),
+ STRING_TOKEN (STR_FORM_SET_CD_ORDER_TITLE),
+ EFI_IFR_FLAG_CALLBACK,
+ FORM_SET_CD_ORDER_ID
+ );
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_SET_NET_ORDER_ID,
+ STRING_TOKEN (STR_FORM_SET_NET_ORDER_TITLE),
+ STRING_TOKEN (STR_FORM_SET_NET_ORDER_TITLE),
+ EFI_IFR_FLAG_CALLBACK,
+ FORM_SET_NET_ORDER_ID
+ );
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_SET_BEV_ORDER_ID,
+ STRING_TOKEN (STR_FORM_SET_BEV_ORDER_TITLE),
+ STRING_TOKEN (STR_FORM_SET_BEV_ORDER_TITLE),
+ EFI_IFR_FLAG_CALLBACK,
+ FORM_SET_BEV_ORDER_ID
+ );
+
+ HiiUpdateForm (
+ mBmmCallbackInfo->BmmHiiHandle,
+ &gBootMaintFormSetGuid,
+ FORM_BOOT_SETUP_ID,
+ mStartOpCodeHandle, // Label FORM_BOOT_LEGACY_DEVICE_ID
+ mEndOpCodeHandle // LABEL_END
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function processes the results of changes in configuration.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be saved.
+ @retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
+ @retval EFI_INVALID_PARAMETER The parameter of Value or ActionRequest is invalid.
+**/
+EFI_STATUS
+EFIAPI
+BootMaintCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ BMM_CALLBACK_DATA *Private;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BMM_FAKE_NV_DATA *CurrentFakeNVMap;
+ EFI_STATUS Status;
+ UINTN OldValue;
+ UINTN NewValue;
+ UINTN Number;
+ UINTN Pos;
+ UINTN Bit;
+ UINT16 NewValuePos;
+ UINT16 Index3;
+ UINT16 Index2;
+ UINT16 Index;
+ UINT8 *OldLegacyDev;
+ UINT8 *NewLegacyDev;
+ UINT8 *DisMap;
+ EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
+
+ Private = BMM_CALLBACK_DATA_FROM_THIS (This);
+ if (Action == EFI_BROWSER_ACTION_FORM_OPEN && QuestionId == FORM_BOOT_SETUP_ID) {
+ //
+ // Initilize Form for legacy boot option.
+ //
+ Status = EfiLibLocateProtocol (&gEfiLegacyBiosProtocolGuid, (VOID **) &LegacyBios);
+ if (!EFI_ERROR (Status)) {
+ InitializeLegacyBootOption ();
+ }
+
+ return EFI_SUCCESS;
+ }
+
+ if (Action != EFI_BROWSER_ACTION_CHANGING && Action != EFI_BROWSER_ACTION_CHANGED) {
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ Status = EFI_SUCCESS;
+ OldValue = 0;
+ NewValue = 0;
+ Number = 0;
+ OldLegacyDev = NULL;
+ NewLegacyDev = NULL;
+ NewValuePos = 0;
+ DisMap = NULL;
+
+ Private = BMM_CALLBACK_DATA_FROM_THIS (This);
+ //
+ // Retrieve uncommitted data from Form Browser
+ //
+ CurrentFakeNVMap = &Private->BmmFakeNvData;
+ HiiGetBrowserData (&gBootMaintFormSetGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *) CurrentFakeNVMap);
+ if (Action == EFI_BROWSER_ACTION_CHANGING) {
+ if (Value == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ UpdatePageId (Private, QuestionId);
+
+ if (QuestionId < FILE_OPTION_OFFSET) {
+ if (QuestionId < CONFIG_OPTION_OFFSET) {
+ switch (QuestionId) {
+ case KEY_VALUE_BOOT_FROM_FILE:
+ Private->FeCurrentState = FileExplorerStateBootFromFile;
+ break;
+
+ case FORM_BOOT_ADD_ID:
+ Private->FeCurrentState = FileExplorerStateAddBootOption;
+ break;
+
+ case FORM_DRV_ADD_FILE_ID:
+ Private->FeCurrentState = FileExplorerStateAddDriverOptionState;
+ break;
+
+ case FORM_DRV_ADD_HANDLE_ID:
+ CleanUpPage (FORM_DRV_ADD_HANDLE_ID, Private);
+ UpdateDrvAddHandlePage (Private);
+ break;
+
+ case FORM_BOOT_DEL_ID:
+ CleanUpPage (FORM_BOOT_DEL_ID, Private);
+ UpdateBootDelPage (Private);
+ break;
+
+ case FORM_BOOT_CHG_ID:
+ case FORM_DRV_CHG_ID:
+ UpdatePageBody (QuestionId, Private);
+ break;
+
+ case FORM_DRV_DEL_ID:
+ CleanUpPage (FORM_DRV_DEL_ID, Private);
+ UpdateDrvDelPage (Private);
+ break;
+
+ case FORM_BOOT_NEXT_ID:
+ CleanUpPage (FORM_BOOT_NEXT_ID, Private);
+ UpdateBootNextPage (Private);
+ break;
+
+ case FORM_TIME_OUT_ID:
+ CleanUpPage (FORM_TIME_OUT_ID, Private);
+ UpdateTimeOutPage (Private);
+ break;
+
+ case FORM_CON_IN_ID:
+ case FORM_CON_OUT_ID:
+ case FORM_CON_ERR_ID:
+ UpdatePageBody (QuestionId, Private);
+ break;
+
+ case FORM_CON_MODE_ID:
+ CleanUpPage (FORM_CON_MODE_ID, Private);
+ UpdateConModePage (Private);
+ break;
+
+ case FORM_CON_COM_ID:
+ CleanUpPage (FORM_CON_COM_ID, Private);
+ UpdateConCOMPage (Private);
+ break;
+
+ case FORM_SET_FD_ORDER_ID:
+ case FORM_SET_HD_ORDER_ID:
+ case FORM_SET_CD_ORDER_ID:
+ case FORM_SET_NET_ORDER_ID:
+ case FORM_SET_BEV_ORDER_ID:
+ CleanUpPage (QuestionId, Private);
+ UpdateSetLegacyDeviceOrderPage (QuestionId, Private);
+ break;
+
+ default:
+ break;
+ }
+ } else if ((QuestionId >= TERMINAL_OPTION_OFFSET) && (QuestionId < CONSOLE_OPTION_OFFSET)) {
+ Index2 = (UINT16) (QuestionId - TERMINAL_OPTION_OFFSET);
+ Private->CurrentTerminal = Index2;
+
+ CleanUpPage (FORM_CON_COM_SETUP_ID, Private);
+ UpdateTerminalPage (Private);
+
+ } else if (QuestionId >= HANDLE_OPTION_OFFSET) {
+ Index2 = (UINT16) (QuestionId - HANDLE_OPTION_OFFSET);
+
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverMenu, Index2);
+ ASSERT (NewMenuEntry != NULL);
+ Private->HandleContext = (BM_HANDLE_CONTEXT *) NewMenuEntry->VariableContext;
+
+ CleanUpPage (FORM_DRV_ADD_HANDLE_DESC_ID, Private);
+
+ Private->MenuEntry = NewMenuEntry;
+ Private->LoadContext->FilePathList = Private->HandleContext->DevicePath;
+
+ UpdateDriverAddHandleDescPage (Private);
+ }
+ }
+ } else if (Action == EFI_BROWSER_ACTION_CHANGED) {
+ if ((Value == NULL) || (ActionRequest == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+ if ((QuestionId >= BOOT_OPTION_DEL_QUESTION_ID) && (QuestionId < BOOT_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER)) {
+ if (Value->b){
+ //
+ // Means user try to delete this boot option but not press F10 or "Commit Changes and Exit" menu.
+ //
+ CurrentFakeNVMap->BootOptionDelMark[QuestionId - BOOT_OPTION_DEL_QUESTION_ID] = TRUE;
+ } else {
+ //
+ // Means user remove the old check status.
+ //
+ CurrentFakeNVMap->BootOptionDelMark[QuestionId - BOOT_OPTION_DEL_QUESTION_ID] = FALSE;
+ }
+ } else if ((QuestionId >= DRIVER_OPTION_DEL_QUESTION_ID) && (QuestionId < DRIVER_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER)) {
+ if (Value->b){
+ CurrentFakeNVMap->DriverOptionDelMark[QuestionId - DRIVER_OPTION_DEL_QUESTION_ID] = TRUE;
+ } else {
+ CurrentFakeNVMap->DriverOptionDelMark[QuestionId - DRIVER_OPTION_DEL_QUESTION_ID] = FALSE;
+ }
+ } else if ((QuestionId >= LEGACY_FD_QUESTION_ID) && (QuestionId < LEGACY_BEV_QUESTION_ID + MAX_MENU_NUMBER)) {
+ //
+ // Update Select FD/HD/CD/NET/BEV Order Form
+ //
+
+ DisMap = Private->BmmOldFakeNVData.DisableMap;
+
+ if (QuestionId >= LEGACY_FD_QUESTION_ID && QuestionId < LEGACY_FD_QUESTION_ID + MAX_MENU_NUMBER) {
+ Number = (UINT16) LegacyFDMenu.MenuNumber;
+ OldLegacyDev = Private->BmmOldFakeNVData.LegacyFD;
+ NewLegacyDev = CurrentFakeNVMap->LegacyFD;
+ } else if (QuestionId >= LEGACY_HD_QUESTION_ID && QuestionId < LEGACY_HD_QUESTION_ID + MAX_MENU_NUMBER) {
+ Number = (UINT16) LegacyHDMenu.MenuNumber;
+ OldLegacyDev = Private->BmmOldFakeNVData.LegacyHD;
+ NewLegacyDev = CurrentFakeNVMap->LegacyHD;
+ } else if (QuestionId >= LEGACY_CD_QUESTION_ID && QuestionId < LEGACY_CD_QUESTION_ID + MAX_MENU_NUMBER) {
+ Number = (UINT16) LegacyCDMenu.MenuNumber;
+ OldLegacyDev = Private->BmmOldFakeNVData.LegacyCD;
+ NewLegacyDev = CurrentFakeNVMap->LegacyCD;
+ } else if (QuestionId >= LEGACY_NET_QUESTION_ID && QuestionId < LEGACY_NET_QUESTION_ID + MAX_MENU_NUMBER) {
+ Number = (UINT16) LegacyNETMenu.MenuNumber;
+ OldLegacyDev = Private->BmmOldFakeNVData.LegacyNET;
+ NewLegacyDev = CurrentFakeNVMap->LegacyNET;
+ } else if (QuestionId >= LEGACY_BEV_QUESTION_ID && QuestionId < LEGACY_BEV_QUESTION_ID + MAX_MENU_NUMBER) {
+ Number = (UINT16) LegacyBEVMenu.MenuNumber;
+ OldLegacyDev = Private->BmmOldFakeNVData.LegacyBEV;
+ NewLegacyDev = CurrentFakeNVMap->LegacyBEV;
+ }
+ //
+ // First, find the different position
+ // if there is change, it should be only one
+ //
+ for (Index = 0; Index < Number; Index++) {
+ if (OldLegacyDev[Index] != NewLegacyDev[Index]) {
+ OldValue = OldLegacyDev[Index];
+ NewValue = NewLegacyDev[Index];
+ break;
+ }
+ }
+
+ if (Index != Number) {
+ //
+ // there is change, now process
+ //
+ if (0xFF == NewValue) {
+ //
+ // This item will be disable
+ // Just move the items behind this forward to overlap it
+ //
+ Pos = OldValue / 8;
+ Bit = 7 - (OldValue % 8);
+ DisMap[Pos] = (UINT8) (DisMap[Pos] | (UINT8) (1 << Bit));
+ for (Index2 = Index; Index2 < Number - 1; Index2++) {
+ NewLegacyDev[Index2] = NewLegacyDev[Index2 + 1];
+ }
+
+ NewLegacyDev[Index2] = 0xFF;
+ } else {
+ for (Index2 = 0; Index2 < Number; Index2++) {
+ if (Index2 == Index) {
+ continue;
+ }
+
+ if (OldLegacyDev[Index2] == NewValue) {
+ //
+ // If NewValue is in OldLegacyDev array
+ // remember its old position
+ //
+ NewValuePos = Index2;
+ break;
+ }
+ }
+
+ if (Index2 != Number) {
+ //
+ // We will change current item to an existing item
+ // (It's hard to describe here, please read code, it's like a cycle-moving)
+ //
+ for (Index2 = NewValuePos; Index2 != Index;) {
+ if (NewValuePos < Index) {
+ NewLegacyDev[Index2] = OldLegacyDev[Index2 + 1];
+ Index2++;
+ } else {
+ NewLegacyDev[Index2] = OldLegacyDev[Index2 - 1];
+ Index2--;
+ }
+ }
+ } else {
+ //
+ // If NewValue is not in OldlegacyDev array, we are changing to a disabled item
+ // so we should modify DisMap to reflect the change
+ //
+ Pos = NewValue / 8;
+ Bit = 7 - (NewValue % 8);
+ DisMap[Pos] = (UINT8) (DisMap[Pos] & (~ (UINT8) (1 << Bit)));
+ if (0xFF != OldValue) {
+ //
+ // Because NewValue is a item that was disabled before
+ // so after changing the OldValue should be disabled
+ // actually we are doing a swap of enable-disable states of two items
+ //
+ Pos = OldValue / 8;
+ Bit = 7 - (OldValue % 8);
+ DisMap[Pos] = (UINT8) (DisMap[Pos] | (UINT8) (1 << Bit));
+ }
+ }
+ }
+ //
+ // To prevent DISABLE appears in the middle of the list
+ // we should perform a re-ordering
+ //
+ Index3 = Index;
+ Index = 0;
+ while (Index < Number) {
+ if (0xFF != NewLegacyDev[Index]) {
+ Index++;
+ continue;
+ }
+
+ Index2 = Index;
+ Index2++;
+ while (Index2 < Number) {
+ if (0xFF != NewLegacyDev[Index2]) {
+ break;
+ }
+
+ Index2++;
+ }
+
+ if (Index2 < Number) {
+ NewLegacyDev[Index] = NewLegacyDev[Index2];
+ NewLegacyDev[Index2] = 0xFF;
+ }
+
+ Index++;
+ }
+
+ //
+ // Return correct question value.
+ //
+ Value->u8 = NewLegacyDev[Index3];
+ }
+ } else {
+ switch (QuestionId) {
+ case KEY_VALUE_SAVE_AND_EXIT:
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT;
+ break;
+
+ case KEY_VALUE_NO_SAVE_AND_EXIT:
+ //
+ // Restore local maintain data.
+ //
+ DiscardChangeHandler (Private, CurrentFakeNVMap);
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT;
+ break;
+
+ case FORM_RESET:
+ gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
+ return EFI_UNSUPPORTED;
+
+ default:
+ break;
+ }
+ }
+ }
+
+ //
+ // Pass changed uncommitted data back to Form Browser
+ //
+ HiiSetBrowserData (&gBootMaintFormSetGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *) CurrentFakeNVMap, NULL);
+ return EFI_SUCCESS;
+}
+
+/**
+ Discard all changes done to the BMM pages such as Boot Order change,
+ Driver order change.
+
+ @param Private The BMM context data.
+ @param CurrentFakeNVMap The current Fack NV Map.
+
+**/
+VOID
+DiscardChangeHandler (
+ IN BMM_CALLBACK_DATA *Private,
+ IN BMM_FAKE_NV_DATA *CurrentFakeNVMap
+ )
+{
+ UINT16 Index;
+
+ switch (Private->BmmPreviousPageId) {
+ case FORM_BOOT_CHG_ID:
+ CopyMem (CurrentFakeNVMap->BootOptionOrder, Private->BmmOldFakeNVData.BootOptionOrder, sizeof (CurrentFakeNVMap->BootOptionOrder));
+ break;
+
+ case FORM_DRV_CHG_ID:
+ CopyMem (CurrentFakeNVMap->DriverOptionOrder, Private->BmmOldFakeNVData.DriverOptionOrder, sizeof (CurrentFakeNVMap->DriverOptionOrder));
+ break;
+
+ case FORM_BOOT_DEL_ID:
+ ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->BootOptionDel) / sizeof (CurrentFakeNVMap->BootOptionDel[0])));
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ CurrentFakeNVMap->BootOptionDel[Index] = FALSE;
+ CurrentFakeNVMap->BootOptionDelMark[Index] = FALSE;
+ }
+ break;
+
+ case FORM_DRV_DEL_ID:
+ ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->DriverOptionDel) / sizeof (CurrentFakeNVMap->DriverOptionDel[0])));
+ for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) {
+ CurrentFakeNVMap->DriverOptionDel[Index] = FALSE;
+ CurrentFakeNVMap->DriverOptionDelMark[Index] = FALSE;
+ }
+ break;
+
+ case FORM_BOOT_NEXT_ID:
+ CurrentFakeNVMap->BootNext = Private->BmmOldFakeNVData.BootNext;
+ break;
+
+ case FORM_TIME_OUT_ID:
+ CurrentFakeNVMap->BootTimeOut = Private->BmmOldFakeNVData.BootTimeOut;
+ break;
+
+ case FORM_DRV_ADD_HANDLE_DESC_ID:
+ case FORM_DRV_ADD_FILE_ID:
+ case FORM_DRV_ADD_HANDLE_ID:
+ CurrentFakeNVMap->DriverAddHandleDesc[0] = 0x0000;
+ CurrentFakeNVMap->DriverAddHandleOptionalData[0] = 0x0000;
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ Initialize the Boot Maintenance Utitliy.
+
+
+ @retval EFI_SUCCESS utility ended successfully
+ @retval others contain some errors
+
+**/
+EFI_STATUS
+InitializeBM (
+ VOID
+ )
+{
+ BMM_CALLBACK_DATA *BmmCallbackInfo;
+ EFI_STATUS Status;
+ EFI_HII_PACKAGE_LIST_HEADER *PackageListHeader;
+ UINT32 Length;
+ UINT8 *Data;
+
+ Status = EFI_SUCCESS;
+ BmmCallbackInfo = mBmmCallbackInfo;
+
+ BmmCallbackInfo->BmmPreviousPageId = FORM_MAIN_ID;
+ BmmCallbackInfo->BmmCurrentPageId = FORM_MAIN_ID;
+ BmmCallbackInfo->FeCurrentState = FileExplorerStateInActive;
+ BmmCallbackInfo->FeDisplayContext = FileExplorerDisplayUnknown;
+
+ //
+ // Reinstall String packages to include more new strings.
+ //
+
+ //
+ // String package size
+ //
+ Length = ReadUnaligned32 ((UINT32 *) BdsDxeStrings) - sizeof (UINT32);
+
+ //
+ // Add the length of the Package List Header and the terminating Package Header
+ //
+ Length += sizeof (EFI_HII_PACKAGE_LIST_HEADER) + sizeof (EFI_HII_PACKAGE_HEADER);
+
+ //
+ // Allocate the storage for the entire Package List
+ //
+ PackageListHeader = AllocateZeroPool (Length);
+
+ //
+ // If the Package List can not be allocated, then return a NULL HII Handle
+ //
+ if (PackageListHeader == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Fill in the GUID and Length of the Package List Header
+ //
+ PackageListHeader->PackageLength = Length;
+
+ //
+ // Copy String Data into Package list.
+ //
+ Data = (UINT8 *)(PackageListHeader + 1);
+ Length = ReadUnaligned32 ((UINT32 *) BdsDxeStrings) - sizeof (UINT32);
+ CopyMem (Data, (UINT8 *) BdsDxeStrings + sizeof (UINT32), Length);
+
+ //
+ // Add End type HII package.
+ //
+ Data += Length;
+ ((EFI_HII_PACKAGE_HEADER *) Data)->Type = EFI_HII_PACKAGE_END;
+ ((EFI_HII_PACKAGE_HEADER *) Data)->Length = sizeof (EFI_HII_PACKAGE_HEADER);
+
+ //
+ // Update String package for BM
+ //
+ CopyGuid (&PackageListHeader->PackageListGuid, &gBootMaintFormSetGuid);
+ Status = gHiiDatabase->UpdatePackageList (gHiiDatabase, BmmCallbackInfo->BmmHiiHandle, PackageListHeader);
+
+ //
+ // Update String package for FE.
+ //
+ CopyGuid (&PackageListHeader->PackageListGuid, &gFileExploreFormSetGuid);
+ Status = gHiiDatabase->UpdatePackageList (gHiiDatabase, BmmCallbackInfo->FeHiiHandle, PackageListHeader);
+
+ FreePool (PackageListHeader);
+
+ //
+ // Init OpCode Handle and Allocate space for creation of Buffer
+ //
+ mStartOpCodeHandle = HiiAllocateOpCodeHandle ();
+ if (mStartOpCodeHandle == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Exit;
+ }
+
+ mEndOpCodeHandle = HiiAllocateOpCodeHandle ();
+ if (mEndOpCodeHandle == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Exit;
+ }
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ mStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ mStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ mEndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mEndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ mEndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ mEndLabel->Number = LABEL_END;
+
+ InitializeStringDepository ();
+
+ InitAllMenu (BmmCallbackInfo);
+
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &ConsoleInpMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &ConsoleOutMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &ConsoleErrMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &BootOptionMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &DriverOptionMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &TerminalMenu);
+ CreateMenuStringToken (BmmCallbackInfo, BmmCallbackInfo->BmmHiiHandle, &DriverMenu);
+
+ InitializeBmmConfig (BmmCallbackInfo);
+
+ //
+ // Dispatch BMM main formset and File Explorer formset.
+ //
+ FormSetDispatcher (BmmCallbackInfo);
+
+ //
+ // Clean up.
+ //
+ CleanUpStringDepository ();
+
+ FreeAllMenu ();
+
+Exit:
+ if (mStartOpCodeHandle != NULL) {
+ HiiFreeOpCodeHandle (mStartOpCodeHandle);
+ }
+
+ if (mEndOpCodeHandle != NULL) {
+ HiiFreeOpCodeHandle (mEndOpCodeHandle);
+ }
+
+ return Status;
+}
+
+
+/**
+ Initialized all Menu Option List.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+InitAllMenu (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ InitializeListHead (&BootOptionMenu.Head);
+ InitializeListHead (&DriverOptionMenu.Head);
+ BOpt_GetBootOptions (CallbackData);
+ BOpt_GetDriverOptions (CallbackData);
+ BOpt_GetLegacyOptions ();
+ InitializeListHead (&FsOptionMenu.Head);
+ BOpt_FindDrivers ();
+ InitializeListHead (&DirectoryMenu.Head);
+ InitializeListHead (&ConsoleInpMenu.Head);
+ InitializeListHead (&ConsoleOutMenu.Head);
+ InitializeListHead (&ConsoleErrMenu.Head);
+ InitializeListHead (&TerminalMenu.Head);
+ LocateSerialIo ();
+ GetAllConsoles ();
+}
+
+/**
+ Free up all Menu Option list.
+
+**/
+VOID
+FreeAllMenu (
+ VOID
+ )
+{
+ BOpt_FreeMenu (&DirectoryMenu);
+ BOpt_FreeMenu (&FsOptionMenu);
+ BOpt_FreeMenu (&BootOptionMenu);
+ BOpt_FreeMenu (&DriverOptionMenu);
+ BOpt_FreeMenu (&DriverMenu);
+ BOpt_FreeLegacyOptions ();
+ FreeAllConsoles ();
+}
+
+/**
+ Initialize all the string depositories.
+
+**/
+VOID
+InitializeStringDepository (
+ VOID
+ )
+{
+ STRING_DEPOSITORY *StringDepository;
+ StringDepository = AllocateZeroPool (sizeof (STRING_DEPOSITORY) * STRING_DEPOSITORY_NUMBER);
+ FileOptionStrDepository = StringDepository++;
+ ConsoleOptionStrDepository = StringDepository++;
+ BootOptionStrDepository = StringDepository++;
+ BootOptionHelpStrDepository = StringDepository++;
+ DriverOptionStrDepository = StringDepository++;
+ DriverOptionHelpStrDepository = StringDepository++;
+ TerminalStrDepository = StringDepository;
+}
+
+/**
+ Fetch a usable string node from the string depository and return the string token.
+
+ @param CallbackData The BMM context data.
+ @param StringDepository The string repository.
+
+ @retval EFI_STRING_ID String token.
+
+**/
+EFI_STRING_ID
+GetStringTokenFromDepository (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN STRING_DEPOSITORY *StringDepository
+ )
+{
+ STRING_LIST_NODE *CurrentListNode;
+ STRING_LIST_NODE *NextListNode;
+
+ CurrentListNode = StringDepository->CurrentNode;
+
+ if ((NULL != CurrentListNode) && (NULL != CurrentListNode->Next)) {
+ //
+ // Fetch one reclaimed node from the list.
+ //
+ NextListNode = StringDepository->CurrentNode->Next;
+ } else {
+ //
+ // If there is no usable node in the list, update the list.
+ //
+ NextListNode = AllocateZeroPool (sizeof (STRING_LIST_NODE));
+ ASSERT (NextListNode != NULL);
+ NextListNode->StringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, L" ", NULL);
+ ASSERT (NextListNode->StringToken != 0);
+
+ StringDepository->TotalNodeNumber++;
+
+ if (NULL == CurrentListNode) {
+ StringDepository->ListHead = NextListNode;
+ } else {
+ CurrentListNode->Next = NextListNode;
+ }
+ }
+
+ StringDepository->CurrentNode = NextListNode;
+
+ return StringDepository->CurrentNode->StringToken;
+}
+
+/**
+ Reclaim string depositories by moving the current node pointer to list head..
+
+**/
+VOID
+ReclaimStringDepository (
+ VOID
+ )
+{
+ UINTN DepositoryIndex;
+ STRING_DEPOSITORY *StringDepository;
+
+ StringDepository = FileOptionStrDepository;
+ for (DepositoryIndex = 0; DepositoryIndex < STRING_DEPOSITORY_NUMBER; DepositoryIndex++) {
+ StringDepository->CurrentNode = StringDepository->ListHead;
+ StringDepository++;
+ }
+}
+
+/**
+ Release resource for all the string depositories.
+
+**/
+VOID
+CleanUpStringDepository (
+ VOID
+ )
+{
+ UINTN NodeIndex;
+ UINTN DepositoryIndex;
+ STRING_LIST_NODE *CurrentListNode;
+ STRING_LIST_NODE *NextListNode;
+ STRING_DEPOSITORY *StringDepository;
+
+ //
+ // Release string list nodes.
+ //
+ StringDepository = FileOptionStrDepository;
+ for (DepositoryIndex = 0; DepositoryIndex < STRING_DEPOSITORY_NUMBER; DepositoryIndex++) {
+ CurrentListNode = StringDepository->ListHead;
+ for (NodeIndex = 0; NodeIndex < StringDepository->TotalNodeNumber; NodeIndex++) {
+ NextListNode = CurrentListNode->Next;
+ FreePool (CurrentListNode);
+ CurrentListNode = NextListNode;
+ }
+
+ StringDepository++;
+ }
+ //
+ // Release string depository.
+ //
+ FreePool (FileOptionStrDepository);
+}
+
+/**
+ Start boot maintenance manager
+
+ @retval EFI_SUCCESS If BMM is invoked successfully.
+ @return Other value if BMM return unsuccessfully.
+
+**/
+EFI_STATUS
+BdsStartBootMaint (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ LIST_ENTRY BdsBootOptionList;
+
+ InitializeListHead (&BdsBootOptionList);
+
+ //
+ // Connect all prior to entering the platform setup menu.
+ //
+ if (!gConnectAllHappened) {
+ BdsLibConnectAllDriversToAllControllers ();
+ gConnectAllHappened = TRUE;
+ }
+ //
+ // Have chance to enumerate boot device
+ //
+ BdsLibEnumerateAllBootOption (&BdsBootOptionList);
+
+ //
+ // Group the legacy boot options for the same device type
+ //
+ GroupMultipleLegacyBootOption4SameType ();
+
+ //
+ // Init the BMM
+ //
+ Status = InitializeBM ();
+
+ return Status;
+}
+
+/**
+ Dispatch BMM formset and FileExplorer formset.
+
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS If function complete successfully.
+ @return Other value if the Setup Browser process BMM's pages and
+ return unsuccessfully.
+
+**/
+EFI_STATUS
+FormSetDispatcher (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ EFI_STATUS Status;
+ EFI_BROWSER_ACTION_REQUEST ActionRequest;
+
+ while (TRUE) {
+ UpdatePageId (CallbackData, FORM_MAIN_ID);
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &CallbackData->BmmHiiHandle,
+ 1,
+ &gBootMaintFormSetGuid,
+ 0,
+ NULL,
+ &ActionRequest
+ );
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ ReclaimStringDepository ();
+
+ //
+ // When this Formset returns, check if we are going to explore files.
+ //
+ if (FileExplorerStateInActive != CallbackData->FeCurrentState) {
+ UpdateFileExplorer (CallbackData, 0);
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &CallbackData->FeHiiHandle,
+ 1,
+ &gFileExploreFormSetGuid,
+ 0,
+ NULL,
+ &ActionRequest
+ );
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ CallbackData->FeCurrentState = FileExplorerStateInActive;
+ CallbackData->FeDisplayContext = FileExplorerDisplayUnknown;
+ ReclaimStringDepository ();
+ } else {
+ break;
+ }
+ }
+
+ return Status;
+}
+
+/**
+ Intall BootMaint and FileExplorer HiiPackages.
+
+**/
+EFI_STATUS
+InitBMPackage (
+ VOID
+ )
+{
+ BMM_CALLBACK_DATA *BmmCallbackInfo;
+ EFI_STATUS Status;
+ UINT8 *Ptr;
+
+ //
+ // Create CallbackData structures for Driver Callback
+ //
+ BmmCallbackInfo = AllocateZeroPool (sizeof (BMM_CALLBACK_DATA));
+ if (BmmCallbackInfo == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Create LoadOption in BmmCallbackInfo for Driver Callback
+ //
+ Ptr = AllocateZeroPool (sizeof (BM_LOAD_CONTEXT) + sizeof (BM_FILE_CONTEXT) + sizeof (BM_HANDLE_CONTEXT) + sizeof (BM_MENU_ENTRY));
+ if (Ptr == NULL) {
+ FreePool (BmmCallbackInfo);
+ BmmCallbackInfo = NULL;
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Initialize Bmm callback data.
+ //
+ BmmCallbackInfo->LoadContext = (BM_LOAD_CONTEXT *) Ptr;
+ Ptr += sizeof (BM_LOAD_CONTEXT);
+
+ BmmCallbackInfo->FileContext = (BM_FILE_CONTEXT *) Ptr;
+ Ptr += sizeof (BM_FILE_CONTEXT);
+
+ BmmCallbackInfo->HandleContext = (BM_HANDLE_CONTEXT *) Ptr;
+ Ptr += sizeof (BM_HANDLE_CONTEXT);
+
+ BmmCallbackInfo->MenuEntry = (BM_MENU_ENTRY *) Ptr;
+
+ BmmCallbackInfo->Signature = BMM_CALLBACK_DATA_SIGNATURE;
+ BmmCallbackInfo->BmmConfigAccess.ExtractConfig = BootMaintExtractConfig;
+ BmmCallbackInfo->BmmConfigAccess.RouteConfig = BootMaintRouteConfig;
+ BmmCallbackInfo->BmmConfigAccess.Callback = BootMaintCallback;
+ BmmCallbackInfo->FeConfigAccess.ExtractConfig = FakeExtractConfig;
+ BmmCallbackInfo->FeConfigAccess.RouteConfig = FileExplorerRouteConfig;
+ BmmCallbackInfo->FeConfigAccess.Callback = FileExplorerCallback;
+
+ //
+ // Install Device Path Protocol and Config Access protocol to driver handle
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &BmmCallbackInfo->BmmDriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mBmmHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &BmmCallbackInfo->BmmConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Install Device Path Protocol and Config Access protocol to driver handle
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &BmmCallbackInfo->FeDriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mFeHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &BmmCallbackInfo->FeConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Post our Boot Maint VFR binary to the HII database.
+ //
+ BmmCallbackInfo->BmmHiiHandle = HiiAddPackages (
+ &gBootMaintFormSetGuid,
+ BmmCallbackInfo->BmmDriverHandle,
+ BmBin,
+ BdsDxeStrings,
+ NULL
+ );
+ ASSERT (BmmCallbackInfo->BmmHiiHandle != NULL);
+
+ //
+ // Post our File Explorer VFR binary to the HII database.
+ //
+ BmmCallbackInfo->FeHiiHandle = HiiAddPackages (
+ &gFileExploreFormSetGuid,
+ BmmCallbackInfo->FeDriverHandle,
+ FEBin,
+ BdsDxeStrings,
+ NULL
+ );
+ ASSERT (BmmCallbackInfo->FeHiiHandle != NULL);
+
+ mBmmCallbackInfo = BmmCallbackInfo;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Remvoe the intalled BootMaint and FileExplorer HiiPackages.
+
+**/
+VOID
+FreeBMPackage (
+ VOID
+ )
+{
+ BMM_CALLBACK_DATA *BmmCallbackInfo;
+
+ BmmCallbackInfo = mBmmCallbackInfo;
+
+ //
+ // Remove our IFR data from HII database
+ //
+ HiiRemovePackages (BmmCallbackInfo->BmmHiiHandle);
+ HiiRemovePackages (BmmCallbackInfo->FeHiiHandle);
+
+ if (BmmCallbackInfo->FeDriverHandle != NULL) {
+ gBS->UninstallMultipleProtocolInterfaces (
+ BmmCallbackInfo->FeDriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mFeHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &BmmCallbackInfo->FeConfigAccess,
+ NULL
+ );
+ }
+
+ if (BmmCallbackInfo->BmmDriverHandle != NULL) {
+ gBS->UninstallMultipleProtocolInterfaces (
+ BmmCallbackInfo->BmmDriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mBmmHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &BmmCallbackInfo->BmmConfigAccess,
+ NULL
+ );
+ }
+
+ FreePool (BmmCallbackInfo->LoadContext);
+ FreePool (BmmCallbackInfo);
+
+ mBmmCallbackInfo = NULL;
+
+ return;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.h
new file mode 100644
index 0000000000..098692fa53
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootMaint.h
@@ -0,0 +1,1679 @@
+/** @file
+ Header file for boot maintenance module.
+
+Copyright (c) 2004 - 2014, 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 _BOOT_MAINT_H_
+#define _BOOT_MAINT_H_
+
+#include "Bds.h"
+#include "BBSsupport.h"
+#include "FormGuid.h"
+#include "FrontPage.h"
+
+//
+// Constants which are variable names used to access variables
+//
+#define VAR_CON_OUT_MODE L"ConOutMode"
+
+//
+// String Contant
+//
+#define STR_FLOPPY L"Floppy Drive #%02x"
+#define STR_HARDDISK L"HardDisk Drive #%02x"
+#define STR_CDROM L"ATAPI CDROM Drive #%02x"
+#define STR_NET L"NET Drive #%02x"
+#define STR_BEV L"BEV Drive #%02x"
+#define STR_FLOPPY_HELP L"Select Floppy Drive #%02x"
+#define STR_HARDDISK_HELP L"Select HardDisk Drive #%02x"
+#define STR_CDROM_HELP L"Select ATAPI CDROM Drive #%02x"
+#define STR_NET_HELP L"NET Drive #%02x"
+#define STR_BEV_HELP L"BEV Drive #%02x"
+
+extern CHAR16 mFileExplorerStorageName[];
+extern CHAR16 mBootMaintStorageName[];
+//
+// These are the VFR compiler generated data representing our VFR data.
+//
+extern UINT8 BmBin[];
+extern UINT8 FEBin[];
+
+//
+// Below are the number of options in Baudrate, Databits,
+// Parity and Stopbits selection for serial ports.
+//
+#define BM_COM_ATTR_BUADRATE 19
+#define BM_COM_ATTR_DATABITS 4
+#define BM_COM_ATTR_PARITY 5
+#define BM_COM_ATTR_STOPBITS 3
+
+//
+// Callback function helper
+//
+#define BMM_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('C', 'b', 'c', 'k')
+#define BMM_CALLBACK_DATA_FROM_THIS(a) CR (a, BMM_CALLBACK_DATA, BmmConfigAccess, BMM_CALLBACK_DATA_SIGNATURE)
+
+#define FE_CALLBACK_DATA_FROM_THIS(a) CR (a, BMM_CALLBACK_DATA, FeConfigAccess, BMM_CALLBACK_DATA_SIGNATURE)
+
+//
+// Enumeration type definition
+//
+typedef enum _TYPE_OF_TERMINAL {
+ TerminalTypePcAnsi = 0,
+ TerminalTypeVt100,
+ TerminalTypeVt100Plus,
+ TerminalTypeVtUtf8
+} TYPE_OF_TERMINAL;
+
+typedef enum _FILE_EXPLORER_STATE {
+ FileExplorerStateInActive = 0,
+ FileExplorerStateBootFromFile,
+ FileExplorerStateAddBootOption,
+ FileExplorerStateAddDriverOptionState,
+ FileExplorerStateUnknown
+} FILE_EXPLORER_STATE;
+
+typedef enum _FILE_EXPLORER_DISPLAY_CONTEXT {
+ FileExplorerDisplayFileSystem,
+ FileExplorerDisplayDirectory,
+ FileExplorerDisplayUnknown
+} FILE_EXPLORER_DISPLAY_CONTEXT;
+
+//
+// All of the signatures that will be used in list structure
+//
+#define BM_MENU_OPTION_SIGNATURE SIGNATURE_32 ('m', 'e', 'n', 'u')
+#define BM_LOAD_OPTION_SIGNATURE SIGNATURE_32 ('l', 'o', 'a', 'd')
+#define BM_CONSOLE_OPTION_SIGNATURE SIGNATURE_32 ('c', 'n', 's', 'l')
+#define BM_FILE_OPTION_SIGNATURE SIGNATURE_32 ('f', 'i', 'l', 'e')
+#define BM_HANDLE_OPTION_SIGNATURE SIGNATURE_32 ('h', 'n', 'd', 'l')
+#define BM_TERMINAL_OPTION_SIGNATURE SIGNATURE_32 ('t', 'r', 'm', 'l')
+#define BM_MENU_ENTRY_SIGNATURE SIGNATURE_32 ('e', 'n', 't', 'r')
+
+#define BM_LOAD_CONTEXT_SELECT 0x0
+#define BM_CONSOLE_CONTEXT_SELECT 0x1
+#define BM_FILE_CONTEXT_SELECT 0x2
+#define BM_HANDLE_CONTEXT_SELECT 0x3
+#define BM_TERMINAL_CONTEXT_SELECT 0x5
+
+#define BM_CONSOLE_IN_CONTEXT_SELECT 0x6
+#define BM_CONSOLE_OUT_CONTEXT_SELECT 0x7
+#define BM_CONSOLE_ERR_CONTEXT_SELECT 0x8
+#define BM_LEGACY_DEV_CONTEXT_SELECT 0x9
+
+//
+// Buffer size for update data
+//
+#define UPDATE_DATA_SIZE 0x100000
+
+//
+// Namespace of callback keys used in display and file system navigation
+//
+#define MAX_BBS_OFFSET 0xE000
+#define NET_OPTION_OFFSET 0xD800
+#define BEV_OPTION_OFFSET 0xD000
+#define FD_OPTION_OFFSET 0xC000
+#define HD_OPTION_OFFSET 0xB000
+#define CD_OPTION_OFFSET 0xA000
+#define FILE_OPTION_GOTO_OFFSET 0xC000
+#define FILE_OPTION_OFFSET 0x8000
+#define FILE_OPTION_MASK 0x3FFF
+#define HANDLE_OPTION_OFFSET 0x7000
+#define CONSOLE_OPTION_OFFSET 0x6000
+#define TERMINAL_OPTION_OFFSET 0x5000
+#define CONFIG_OPTION_OFFSET 0x1200
+#define KEY_VALUE_OFFSET 0x1100
+#define FORM_ID_OFFSET 0x1000
+
+//
+// VarOffset that will be used to create question
+// all these values are computed from the structure
+// defined below
+//
+#define VAR_OFFSET(Field) ((UINT16) ((UINTN) &(((BMM_FAKE_NV_DATA *) 0)->Field)))
+
+//
+// Question Id of Zero is invalid, so add an offset to it
+//
+#define QUESTION_ID(Field) (VAR_OFFSET (Field) + CONFIG_OPTION_OFFSET)
+
+#define BOOT_TIME_OUT_VAR_OFFSET VAR_OFFSET (BootTimeOut)
+#define BOOT_NEXT_VAR_OFFSET VAR_OFFSET (BootNext)
+#define COM1_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COM1BaudRate)
+#define COM1_DATA_RATE_VAR_OFFSET VAR_OFFSET (COM1DataRate)
+#define COM1_STOP_BITS_VAR_OFFSET VAR_OFFSET (COM1StopBits)
+#define COM1_PARITY_VAR_OFFSET VAR_OFFSET (COM1Parity)
+#define COM1_TERMINAL_VAR_OFFSET VAR_OFFSET (COM2TerminalType)
+#define COM2_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COM2BaudRate)
+#define COM2_DATA_RATE_VAR_OFFSET VAR_OFFSET (COM2DataRate)
+#define COM2_STOP_BITS_VAR_OFFSET VAR_OFFSET (COM2StopBits)
+#define COM2_PARITY_VAR_OFFSET VAR_OFFSET (COM2Parity)
+#define COM2_TERMINAL_VAR_OFFSET VAR_OFFSET (COM2TerminalType)
+#define DRV_ADD_HANDLE_DESC_VAR_OFFSET VAR_OFFSET (DriverAddHandleDesc)
+#define DRV_ADD_ACTIVE_VAR_OFFSET VAR_OFFSET (DriverAddActive)
+#define DRV_ADD_RECON_VAR_OFFSET VAR_OFFSET (DriverAddForceReconnect)
+#define CON_IN_COM1_VAR_OFFSET VAR_OFFSET (ConsoleInputCOM1)
+#define CON_IN_COM2_VAR_OFFSET VAR_OFFSET (ConsoleInputCOM2)
+#define CON_OUT_COM1_VAR_OFFSET VAR_OFFSET (ConsoleOutputCOM1)
+#define CON_OUT_COM2_VAR_OFFSET VAR_OFFSET (ConsoleOutputCOM2)
+#define CON_ERR_COM1_VAR_OFFSET VAR_OFFSET (ConsoleErrorCOM1)
+#define CON_ERR_COM2_VAR_OFFSET VAR_OFFSET (ConsoleErrorCOM2)
+#define CON_MODE_VAR_OFFSET VAR_OFFSET (ConsoleOutMode)
+#define CON_IN_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleInCheck)
+#define CON_OUT_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleOutCheck)
+#define CON_ERR_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleErrCheck)
+#define BOOT_OPTION_ORDER_VAR_OFFSET VAR_OFFSET (BootOptionOrder)
+#define DRIVER_OPTION_ORDER_VAR_OFFSET VAR_OFFSET (DriverOptionOrder)
+#define BOOT_OPTION_DEL_VAR_OFFSET VAR_OFFSET (BootOptionDel)
+#define DRIVER_OPTION_DEL_VAR_OFFSET VAR_OFFSET (DriverOptionDel)
+#define DRIVER_ADD_OPTION_VAR_OFFSET VAR_OFFSET (DriverAddHandleOptionalData)
+#define COM_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COMBaudRate)
+#define COM_DATA_RATE_VAR_OFFSET VAR_OFFSET (COMDataRate)
+#define COM_STOP_BITS_VAR_OFFSET VAR_OFFSET (COMStopBits)
+#define COM_PARITY_VAR_OFFSET VAR_OFFSET (COMParity)
+#define COM_TERMINAL_VAR_OFFSET VAR_OFFSET (COMTerminalType)
+#define COM_FLOWCONTROL_VAR_OFFSET VAR_OFFSET (COMFlowControl)
+#define LEGACY_FD_VAR_OFFSET VAR_OFFSET (LegacyFD)
+#define LEGACY_HD_VAR_OFFSET VAR_OFFSET (LegacyHD)
+#define LEGACY_CD_VAR_OFFSET VAR_OFFSET (LegacyCD)
+#define LEGACY_NET_VAR_OFFSET VAR_OFFSET (LegacyNET)
+#define LEGACY_BEV_VAR_OFFSET VAR_OFFSET (LegacyBEV)
+
+#define BOOT_TIME_OUT_QUESTION_ID QUESTION_ID (BootTimeOut)
+#define BOOT_NEXT_QUESTION_ID QUESTION_ID (BootNext)
+#define COM1_BAUD_RATE_QUESTION_ID QUESTION_ID (COM1BaudRate)
+#define COM1_DATA_RATE_QUESTION_ID QUESTION_ID (COM1DataRate)
+#define COM1_STOP_BITS_QUESTION_ID QUESTION_ID (COM1StopBits)
+#define COM1_PARITY_QUESTION_ID QUESTION_ID (COM1Parity)
+#define COM1_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType)
+#define COM2_BAUD_RATE_QUESTION_ID QUESTION_ID (COM2BaudRate)
+#define COM2_DATA_RATE_QUESTION_ID QUESTION_ID (COM2DataRate)
+#define COM2_STOP_BITS_QUESTION_ID QUESTION_ID (COM2StopBits)
+#define COM2_PARITY_QUESTION_ID QUESTION_ID (COM2Parity)
+#define COM2_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType)
+#define DRV_ADD_HANDLE_DESC_QUESTION_ID QUESTION_ID (DriverAddHandleDesc)
+#define DRV_ADD_ACTIVE_QUESTION_ID QUESTION_ID (DriverAddActive)
+#define DRV_ADD_RECON_QUESTION_ID QUESTION_ID (DriverAddForceReconnect)
+#define CON_IN_COM1_QUESTION_ID QUESTION_ID (ConsoleInputCOM1)
+#define CON_IN_COM2_QUESTION_ID QUESTION_ID (ConsoleInputCOM2)
+#define CON_OUT_COM1_QUESTION_ID QUESTION_ID (ConsoleOutputCOM1)
+#define CON_OUT_COM2_QUESTION_ID QUESTION_ID (ConsoleOutputCOM2)
+#define CON_ERR_COM1_QUESTION_ID QUESTION_ID (ConsoleErrorCOM1)
+#define CON_ERR_COM2_QUESTION_ID QUESTION_ID (ConsoleErrorCOM2)
+#define CON_MODE_QUESTION_ID QUESTION_ID (ConsoleOutMode)
+#define CON_IN_DEVICE_QUESTION_ID QUESTION_ID (ConsoleInCheck)
+#define CON_OUT_DEVICE_QUESTION_ID QUESTION_ID (ConsoleOutCheck)
+#define CON_ERR_DEVICE_QUESTION_ID QUESTION_ID (ConsoleErrCheck)
+#define BOOT_OPTION_ORDER_QUESTION_ID QUESTION_ID (BootOptionOrder)
+#define DRIVER_OPTION_ORDER_QUESTION_ID QUESTION_ID (DriverOptionOrder)
+#define BOOT_OPTION_DEL_QUESTION_ID QUESTION_ID (BootOptionDel)
+#define DRIVER_OPTION_DEL_QUESTION_ID QUESTION_ID (DriverOptionDel)
+#define DRIVER_ADD_OPTION_QUESTION_ID QUESTION_ID (DriverAddHandleOptionalData)
+#define COM_BAUD_RATE_QUESTION_ID QUESTION_ID (COMBaudRate)
+#define COM_DATA_RATE_QUESTION_ID QUESTION_ID (COMDataRate)
+#define COM_STOP_BITS_QUESTION_ID QUESTION_ID (COMStopBits)
+#define COM_PARITY_QUESTION_ID QUESTION_ID (COMParity)
+#define COM_TERMINAL_QUESTION_ID QUESTION_ID (COMTerminalType)
+#define COM_FLOWCONTROL_QUESTION_ID QUESTION_ID (COMFlowControl)
+#define LEGACY_FD_QUESTION_ID QUESTION_ID (LegacyFD)
+#define LEGACY_HD_QUESTION_ID QUESTION_ID (LegacyHD)
+#define LEGACY_CD_QUESTION_ID QUESTION_ID (LegacyCD)
+#define LEGACY_NET_QUESTION_ID QUESTION_ID (LegacyNET)
+#define LEGACY_BEV_QUESTION_ID QUESTION_ID (LegacyBEV)
+
+#define STRING_DEPOSITORY_NUMBER 8
+
+///
+/// Serial Ports attributes, first one is the value for
+/// return from callback function, stringtoken is used to
+/// display the value properly
+///
+typedef struct {
+ UINTN Value;
+ UINT16 StringToken;
+} COM_ATTR;
+
+typedef struct {
+ UINT64 BaudRate;
+ UINT8 DataBits;
+ UINT8 Parity;
+ UINT8 StopBits;
+
+ UINT8 BaudRateIndex;
+ UINT8 DataBitsIndex;
+ UINT8 ParityIndex;
+ UINT8 StopBitsIndex;
+
+ UINT8 FlowControl;
+
+ UINT8 IsConIn;
+ UINT8 IsConOut;
+ UINT8 IsStdErr;
+ UINT8 TerminalType;
+
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+} BM_TERMINAL_CONTEXT;
+
+typedef struct {
+ BOOLEAN IsBootNext;
+ BOOLEAN LoadOptionModified;
+ BOOLEAN Deleted;
+
+ BOOLEAN IsLegacy;
+ BOOLEAN IsActive;
+ BOOLEAN ForceReconnect;
+ UINTN OptionalDataSize;
+
+ UINTN LoadOptionSize;
+ UINT8 *LoadOption;
+
+ UINT32 Attributes;
+ UINT16 FilePathListLength;
+ UINT16 *Description;
+ EFI_DEVICE_PATH_PROTOCOL *FilePathList;
+ UINT8 *OptionalData;
+
+ UINT16 BbsIndex;
+} BM_LOAD_CONTEXT;
+
+typedef struct {
+ BBS_TABLE *BbsEntry;
+ UINT16 BbsIndex;
+ UINT16 BbsCount;
+ CHAR16 *Description;
+} BM_LEGACY_DEVICE_CONTEXT;
+
+typedef struct {
+
+ BOOLEAN IsActive;
+
+ BOOLEAN IsTerminal;
+
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+} BM_CONSOLE_CONTEXT;
+
+typedef struct {
+ UINTN Column;
+ UINTN Row;
+} CONSOLE_OUT_MODE;
+
+typedef struct {
+ EFI_HANDLE Handle;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ EFI_FILE_HANDLE FHandle;
+ UINT16 *FileName;
+ EFI_FILE_SYSTEM_VOLUME_LABEL *Info;
+
+ BOOLEAN IsRoot;
+ BOOLEAN IsDir;
+ BOOLEAN IsRemovableMedia;
+ BOOLEAN IsLoadFile;
+ BOOLEAN IsBootLegacy;
+} BM_FILE_CONTEXT;
+
+typedef struct {
+ EFI_HANDLE Handle;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+} BM_HANDLE_CONTEXT;
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Head;
+ UINTN MenuNumber;
+} BM_MENU_OPTION;
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Link;
+ UINTN OptionNumber;
+ UINT16 *DisplayString;
+ UINT16 *HelpString;
+ EFI_STRING_ID DisplayStringToken;
+ EFI_STRING_ID HelpStringToken;
+ UINTN ContextSelection;
+ VOID *VariableContext;
+} BM_MENU_ENTRY;
+
+typedef struct {
+ //
+ // Shared callback data.
+ //
+ UINTN Signature;
+
+ BM_MENU_ENTRY *MenuEntry;
+ BM_HANDLE_CONTEXT *HandleContext;
+ BM_FILE_CONTEXT *FileContext;
+ BM_LOAD_CONTEXT *LoadContext;
+ BM_TERMINAL_CONTEXT *TerminalContext;
+ UINTN CurrentTerminal;
+ BBS_TYPE BbsType;
+
+ //
+ // BMM main formset callback data.
+ //
+ EFI_HII_HANDLE BmmHiiHandle;
+ EFI_HANDLE BmmDriverHandle;
+ EFI_HII_CONFIG_ACCESS_PROTOCOL BmmConfigAccess;
+ EFI_FORM_ID BmmCurrentPageId;
+ EFI_FORM_ID BmmPreviousPageId;
+ BOOLEAN BmmAskSaveOrNot;
+ BMM_FAKE_NV_DATA BmmFakeNvData;
+ BMM_FAKE_NV_DATA BmmOldFakeNVData;
+
+ //
+ // File explorer formset callback data.
+ //
+ EFI_HII_HANDLE FeHiiHandle;
+ EFI_HANDLE FeDriverHandle;
+ EFI_HII_CONFIG_ACCESS_PROTOCOL FeConfigAccess;
+ FILE_EXPLORER_STATE FeCurrentState;
+ FILE_EXPLORER_DISPLAY_CONTEXT FeDisplayContext;
+ FILE_EXPLORER_NV_DATA FeFakeNvData;
+} BMM_CALLBACK_DATA;
+
+typedef struct _STRING_LIST_NODE STRING_LIST_NODE;
+
+struct _STRING_LIST_NODE {
+ EFI_STRING_ID StringToken;
+ STRING_LIST_NODE *Next;
+};
+
+typedef struct _STRING_DEPOSITORY {
+ UINTN TotalNodeNumber;
+ STRING_LIST_NODE *CurrentNode;
+ STRING_LIST_NODE *ListHead;
+} STRING_DEPOSITORY;
+
+//
+// #pragma pack()
+//
+// For initializing File System menu
+//
+
+/**
+ This function build the FsOptionMenu list which records all
+ available file system in the system. They includes all instances
+ of EFI_SIMPLE_FILE_SYSTEM_PROTOCOL, all instances of EFI_LOAD_FILE_SYSTEM
+ and all type of legacy boot device.
+
+ @param CallbackData BMM context data
+
+ @retval EFI_SUCCESS Success find the file system
+ @retval EFI_OUT_OF_RESOURCES Can not create menu entry
+
+**/
+EFI_STATUS
+BOpt_FindFileSystem (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Find files under current directory
+ All files and sub-directories in current directory
+ will be stored in DirectoryMenu for future use.
+
+ @param CallbackData The BMM context data.
+ @param MenuEntry The Menu Entry.
+
+ @retval EFI_SUCCESS Get files from current dir successfully.
+ @return Other value if can't get files from current dir.
+
+**/
+EFI_STATUS
+BOpt_FindFiles (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN BM_MENU_ENTRY *MenuEntry
+ );
+
+/**
+
+ Find drivers that will be added as Driver#### variables from handles
+ in current system environment
+ All valid handles in the system except those consume SimpleFs, LoadFile
+ are stored in DriverMenu for future use.
+
+ @retval EFI_SUCCESS The function complets successfully.
+ @return Other value if failed to build the DriverMenu.
+
+**/
+EFI_STATUS
+BOpt_FindDrivers (
+ VOID
+ );
+
+/**
+
+ Build the BootOptionMenu according to BootOrder Variable.
+ This Routine will access the Boot#### to get EFI_LOAD_OPTION.
+
+ @param CallbackData The BMM context data.
+
+ @return The number of the Var Boot####.
+
+**/
+EFI_STATUS
+BOpt_GetBootOptions (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Build up all DriverOptionMenu
+
+ @param CallbackData The BMM context data.
+
+ @return EFI_SUCESS The functin completes successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to compete the operation.
+
+
+**/
+EFI_STATUS
+BOpt_GetDriverOptions (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+
+/**
+ Build the LegacyFDMenu LegacyHDMenu LegacyCDMenu according to LegacyBios.GetBbsInfo().
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to complete this function.
+
+**/
+EFI_STATUS
+BOpt_GetLegacyOptions (
+ VOID
+ );
+
+/**
+ Free out resouce allocated from Legacy Boot Options.
+
+**/
+VOID
+BOpt_FreeLegacyOptions (
+ VOID
+ );
+
+/**
+ Free resources allocated in Allocate Rountine.
+
+ @param FreeMenu Menu to be freed
+
+**/
+VOID
+BOpt_FreeMenu (
+ BM_MENU_OPTION *FreeMenu
+ );
+
+
+/**
+
+ Append file name to existing file name.
+
+ @param Str1 The existing file name
+ @param Str2 The file name to be appended
+
+ @return Allocate a new string to hold the appended result.
+ Caller is responsible to free the returned string.
+
+**/
+CHAR16*
+BOpt_AppendFileName (
+ IN CHAR16 *Str1,
+ IN CHAR16 *Str2
+ );
+
+/**
+
+ Check whether current FileName point to a valid
+ Efi Image File.
+
+ @param FileName File need to be checked.
+
+ @retval TRUE Is Efi Image
+ @retval FALSE Not a valid Efi Image
+
+**/
+BOOLEAN
+BOpt_IsEfiImageName (
+ IN UINT16 *FileName
+ );
+
+/**
+
+ Check whether current FileName point to a valid Efi Application
+
+ @param Dir Pointer to current Directory
+ @param FileName Pointer to current File name.
+
+ @retval TRUE Is a valid Efi Application
+ @retval FALSE not a valid Efi Application
+
+**/
+BOOLEAN
+BOpt_IsEfiApp (
+ IN EFI_FILE_HANDLE Dir,
+ IN UINT16 *FileName
+ );
+
+/**
+
+ Get the Option Number that has not been allocated for use.
+
+ @param Type The type of Option.
+
+ @return The available Option Number.
+
+**/
+UINT16
+BOpt_GetOptionNumber (
+ CHAR16 *Type
+ );
+
+/**
+
+ Get the Option Number for Boot#### that does not used.
+
+ @return The available Option Number.
+
+**/
+UINT16
+BOpt_GetBootOptionNumber (
+ VOID
+ );
+
+/**
+
+Get the Option Number for Driver#### that does not used.
+
+@return The unused Option Number.
+
+**/
+UINT16
+BOpt_GetDriverOptionNumber (
+ VOID
+ );
+
+/**
+ Create a menu entry give a Menu type.
+
+ @param MenuType The Menu type to be created.
+
+
+ @retval NULL If failed to create the menu.
+ @return The menu.
+
+**/
+BM_MENU_ENTRY *
+BOpt_CreateMenuEntry (
+ UINTN MenuType
+ );
+
+/**
+ Free up all resource allocated for a BM_MENU_ENTRY.
+
+ @param MenuEntry A pointer to BM_MENU_ENTRY.
+
+**/
+VOID
+BOpt_DestroyMenuEntry (
+ BM_MENU_ENTRY *MenuEntry
+ );
+
+/**
+ Get the Menu Entry from the list in Menu Entry List.
+
+ If MenuNumber is great or equal to the number of Menu
+ Entry in the list, then ASSERT.
+
+ @param MenuOption The Menu Entry List to read the menu entry.
+ @param MenuNumber The index of Menu Entry.
+
+ @return The Menu Entry.
+
+**/
+BM_MENU_ENTRY *
+BOpt_GetMenuEntry (
+ BM_MENU_OPTION *MenuOption,
+ UINTN MenuNumber
+ );
+
+//
+// Locate all serial io devices for console
+//
+/**
+ Build a list containing all serial devices.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_UNSUPPORTED No serial ports present.
+
+**/
+EFI_STATUS
+LocateSerialIo (
+ VOID
+ );
+
+//
+// Initializing Console menu
+//
+/**
+ Build up ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
+
+ @retval EFI_SUCCESS The function always complete successfully.
+
+**/
+EFI_STATUS
+GetAllConsoles(
+ VOID
+ );
+
+//
+// Get current mode information
+//
+/**
+ Get mode number according to column and row
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetConsoleOutMode (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+//
+// Cleaning up console menu
+//
+/**
+ Free ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
+
+ @retval EFI_SUCCESS The function always complete successfully.
+**/
+EFI_STATUS
+FreeAllConsoles (
+ VOID
+ );
+
+/**
+ Update the device path that describing a terminal device
+ based on the new BaudRate, Data Bits, parity and Stop Bits
+ set.
+
+ @param DevicePath The devicepath protocol instance wanted to be updated.
+
+**/
+VOID
+ChangeVariableDevicePath (
+ IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ );
+
+/**
+ Update the multi-instance device path of Terminal Device based on
+ the global TerminalMenu. If ChangeTernimal is TRUE, the terminal
+ device path in the Terminal Device in TerminalMenu is also updated.
+
+ @param DevicePath The multi-instance device path.
+ @param ChangeTerminal TRUE, then device path in the Terminal Device
+ in TerminalMenu is also updated; FALSE, no update.
+
+ @return EFI_SUCCESS The function completes successfully.
+
+**/
+EFI_STATUS
+ChangeTerminalDevicePath (
+ IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath,
+ IN BOOLEAN ChangeTerminal
+ );
+
+//
+// Variable operation by menu selection
+//
+/**
+ This function create a currently loaded Boot Option from
+ the BMM. It then appends this Boot Option to the end of
+ the "BootOrder" list. It also append this Boot Opotion to the end
+ of BootOptionMenu.
+
+ @param CallbackData The BMM context data.
+ @param NvRamMap The file explorer formset internal state.
+
+ @retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
+ @retval EFI_SUCCESS If function completes successfully.
+
+**/
+EFI_STATUS
+Var_UpdateBootOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN FILE_EXPLORER_NV_DATA *NvRamMap
+ );
+
+/**
+ Delete Boot Option that represent a Deleted state in BootOptionMenu.
+ After deleting this boot option, call Var_ChangeBootOrder to
+ make sure BootOrder is in valid state.
+
+ @retval EFI_SUCCESS If all boot load option EFI Variables corresponding to
+ BM_LOAD_CONTEXT marked for deletion is deleted
+ @return Others If failed to update the "BootOrder" variable after deletion.
+
+**/
+EFI_STATUS
+Var_DelBootOption (
+ VOID
+ );
+
+/**
+ After any operation on Boot####, there will be a discrepancy in BootOrder.
+ Since some are missing but in BootOrder, while some are present but are
+ not reflected by BootOrder. Then a function rebuild BootOrder from
+ scratch by content from BootOptionMenu is needed.
+
+ @retval EFI_SUCCESS The boot order is updated successfully.
+ @return other than EFI_SUCCESS if failed to change the "BootOrder" EFI Variable.
+
+**/
+EFI_STATUS
+Var_ChangeBootOrder (
+ VOID
+ );
+
+/**
+ This function create a currently loaded Drive Option from
+ the BMM. It then appends this Driver Option to the end of
+ the "DriverOrder" list. It append this Driver Opotion to the end
+ of DriverOptionMenu.
+
+ @param CallbackData The BMM context data.
+ @param HiiHandle The HII handle associated with the BMM formset.
+ @param DescriptionData The description of this driver option.
+ @param OptionalData The optional load option.
+ @param ForceReconnect If to force reconnect.
+
+ @retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
+ @retval EFI_SUCCESS If function completes successfully.
+
+**/
+EFI_STATUS
+Var_UpdateDriverOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_HII_HANDLE HiiHandle,
+ IN UINT16 *DescriptionData,
+ IN UINT16 *OptionalData,
+ IN UINT8 ForceReconnect
+ );
+
+/**
+ Delete Load Option that represent a Deleted state in BootOptionMenu.
+ After deleting this Driver option, call Var_ChangeDriverOrder to
+ make sure DriverOrder is in valid state.
+
+ @retval EFI_SUCCESS Load Option is successfully updated.
+ @return Other value than EFI_SUCCESS if failed to update "Driver Order" EFI
+ Variable.
+
+**/
+EFI_STATUS
+Var_DelDriverOption (
+ VOID
+ );
+
+/**
+ After any operation on Driver####, there will be a discrepancy in
+ DriverOrder. Since some are missing but in DriverOrder, while some
+ are present but are not reflected by DriverOrder. Then a function
+ rebuild DriverOrder from scratch by content from DriverOptionMenu is
+ needed.
+
+ @retval EFI_SUCCESS The driver order is updated successfully.
+ @return other than EFI_SUCCESS if failed to set the "DriverOrder" EFI Variable.
+
+**/
+EFI_STATUS
+Var_ChangeDriverOrder (
+ VOID
+ );
+
+/**
+ This function delete and build multi-instance device path ConIn
+ console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateConsoleInpOption (
+ VOID
+ );
+
+/**
+ This function delete and build multi-instance device path ConOut console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateConsoleOutOption (
+ VOID
+ );
+
+/**
+ This function delete and build multi-instance device path ErrOut console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateErrorOutOption (
+ VOID
+ );
+
+/**
+ Update the device path of "ConOut", "ConIn" and "ErrOut" based on the new BaudRate, Data Bits,
+ parity and stop Bits set.
+
+**/
+VOID
+Var_UpdateAllConsoleOption (
+ VOID
+ );
+
+/**
+ This function update the "BootNext" EFI Variable. If there is no "BootNex" specified in BMM,
+ this EFI Variable is deleted.
+ It also update the BMM context data specified the "BootNext" value.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateBootNext (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ This function update the "BootOrder" EFI Variable based on BMM Formset's NV map. It then refresh
+ BootOptionMenu with the new "BootOrder" list.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
+ @return not The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateBootOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ This function update the "DriverOrder" EFI Variable based on
+ BMM Formset's NV map. It then refresh DriverOptionMenu
+ with the new "DriverOrder" list.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateDriverOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Update the legacy BBS boot option. VAR_LEGACY_DEV_ORDER and gEfiLegacyDevOrderVariableGuid EFI Variable
+ is udpated with the new Legacy Boot order. The EFI Variable of "Boot####" and gEfiGlobalVariableGuid
+ is also updated.
+
+ @param CallbackData The context data for BMM.
+ @param FormId The form id.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @retval EFI_NOT_FOUND If VAR_LEGACY_DEV_ORDER and gEfiLegacyDevOrderVariableGuid EFI Variable can not be found.
+
+**/
+EFI_STATUS
+Var_UpdateBBSOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_FORM_ID FormId
+ );
+
+/**
+ Update the Text Mode of Console.
+
+ @param CallbackData The context data for BMM.
+
+ @retval EFI_SUCCSS If the Text Mode of Console is updated.
+ @return Other value if the Text Mode of Console is not updated.
+
+**/
+EFI_STATUS
+Var_UpdateConMode (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+//
+// Following are page create and refresh functions
+//
+/**
+ Refresh the global UpdateData structure.
+
+**/
+VOID
+RefreshUpdateData (
+ VOID
+ );
+
+/**
+ Clean up the dynamic opcode at label and form specified by
+ both LabelId.
+
+ @param LabelId It is both the Form ID and Label ID for
+ opcode deletion.
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+CleanUpPage (
+ IN UINT16 LabelId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create a lit of boot option from global BootOptionMenu. It
+ allow user to delete the boot option.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateBootDelPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create a lit of driver option from global DriverMenu.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateDrvAddHandlePage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create a lit of driver option from global DriverOptionMenu. It
+ allow user to delete the driver option.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateDrvDelPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Prepare the page to allow user to add description for a Driver Option.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateDriverAddHandleDescPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Dispatch the correct update page function to call based on the UpdatePageId.
+
+ @param UpdatePageId The form ID.
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdatePageBody (
+ IN UINT16 UpdatePageId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create the dynamic page to allow user to set the "BootNext" vaule.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateBootNextPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create the dynamic page to allow user to set the "TimeOut" vaule.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateTimeOutPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create the dynamic page which allows user to set the property such as Baud Rate, Data Bits,
+ Parity, Stop Bits, Terminal Type.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateTerminalPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Refresh the text mode page
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateConModePage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create a list of Goto Opcode for all terminal devices logged
+ by TerminaMenu. This list will be inserted to form FORM_CON_COM_SETUP_ID.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateConCOMPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Create a dynamic page so that Legacy Device boot order
+ can be set for specified device type.
+
+ @param UpdatePageId The form ID. It also spefies the legacy device type.
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateSetLegacyDeviceOrderPage (
+ IN UINT16 UpdatePageId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+
+/**
+ Function opens and returns a file handle to the root directory of a volume.
+
+ @param DeviceHandle A handle for a device
+ @return A valid file handle or NULL is returned
+**/
+EFI_FILE_HANDLE
+EfiLibOpenRoot (
+ IN EFI_HANDLE DeviceHandle
+ );
+
+/**
+ Function gets the file system information from an open file descriptor,
+ and stores it in a buffer allocated from pool.
+
+ @param FHand The file handle.
+
+ @return A pointer to a buffer with file information.
+ NULL is returned if failed to get Vaolume Label Info.
+**/
+EFI_FILE_SYSTEM_VOLUME_LABEL *
+EfiLibFileSystemVolumeLabelInfo (
+ IN EFI_FILE_HANDLE FHand
+ );
+
+/**
+
+ Function gets the file information from an open file descriptor, and stores it
+ in a buffer allocated from pool.
+
+ @param FHand File Handle.
+
+ @return A pointer to a buffer with file information or NULL is returned
+
+**/
+EFI_FILE_INFO *
+EfiLibFileInfo (
+ IN EFI_FILE_HANDLE FHand
+ );
+
+/**
+ Adjusts the size of a previously allocated buffer.
+
+ @param OldPool A pointer to the buffer whose size is being adjusted.
+ @param OldSize The size of the current buffer.
+ @param NewSize The size of the new buffer.
+
+ @return The newly allocated buffer. if NULL, allocation failed.
+
+**/
+VOID*
+EfiReallocatePool (
+ IN VOID *OldPool,
+ IN UINTN OldSize,
+ IN UINTN NewSize
+ );
+
+/**
+ Function deletes the variable specified by VarName and VarGuid.
+
+
+ @param VarName A Null-terminated Unicode string that is
+ the name of the vendor's variable.
+
+ @param VarGuid A unique identifier for the vendor.
+
+ @retval EFI_SUCCESS The variable was found and removed
+ @retval EFI_UNSUPPORTED The variable store was inaccessible
+ @retval EFI_OUT_OF_RESOURCES The temporary buffer was not available
+ @retval EFI_NOT_FOUND The variable was not found
+
+**/
+EFI_STATUS
+EfiLibDeleteVariable (
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VarGuid
+ );
+
+/**
+ Duplicate a string.
+
+ @param Src The source.
+
+ @return A new string which is duplicated copy of the source.
+ @retval NULL If there is not enough memory.
+
+**/
+CHAR16 *
+EfiStrDuplicate (
+ IN CHAR16 *Src
+ );
+
+/**
+ Function is used to determine the number of device path instances
+ that exist in a device path.
+
+
+ @param DevicePath A pointer to a device path data structure.
+
+ @return This function counts and returns the number of device path instances
+ in DevicePath.
+
+**/
+UINTN
+EfiDevicePathInstanceCount (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ );
+
+/**
+ Create string tokens for a menu from its help strings and display strings
+
+
+ @param CallbackData The BMM context data.
+ @param HiiHandle Hii Handle of the package to be updated.
+ @param MenuOption The Menu whose string tokens need to be created
+
+ @retval EFI_SUCCESS string tokens created successfully
+ @retval others contain some errors
+
+**/
+EFI_STATUS
+CreateMenuStringToken (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_HII_HANDLE HiiHandle,
+ IN BM_MENU_OPTION *MenuOption
+ );
+
+/**
+ Get a string from the Data Hub record based on
+ a device path.
+
+ @param DevPath The device Path.
+
+ @return A string located from the Data Hub records based on
+ the device path.
+ @retval NULL If failed to get the String from Data Hub.
+
+**/
+UINT16 *
+EfiLibStrFromDatahub (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevPath
+ );
+
+/**
+ Initialize the Boot Maintenance Utitliy.
+
+ @retval EFI_SUCCESS utility ended successfully.
+ @retval others contain some errors.
+
+**/
+EFI_STATUS
+InitializeBM (
+ VOID
+ );
+
+/**
+ Start boot maintenance manager
+
+ @retval EFI_SUCCESS If BMM is invoked successfully.
+ @return Other value if BMM return unsuccessfully.
+
+**/
+EFI_STATUS
+BdsStartBootMaint (
+ VOID
+ );
+
+/**
+ Intialize all the string depositories.
+
+**/
+VOID
+InitializeStringDepository (
+ VOID
+ );
+
+/**
+ Fetch a usable string node from the string depository and return the string token.
+
+
+ @param CallbackData The BMM context data.
+ @param StringDepository Pointer of the string depository.
+
+ @retval EFI_STRING_ID String token.
+
+**/
+EFI_STRING_ID
+GetStringTokenFromDepository (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN STRING_DEPOSITORY *StringDepository
+ );
+
+/**
+ Reclaim string depositories by moving the current node pointer to list head..
+**/
+VOID
+ReclaimStringDepository (
+ VOID
+ );
+
+/**
+ Release resource for all the string depositories.
+
+**/
+VOID
+CleanUpStringDepository (
+ VOID
+ );
+
+/**
+ Function handling request to apply changes for BMM pages.
+
+ @param Private Pointer to callback data buffer.
+ @param CurrentFakeNVMap Pointer to buffer holding data of various values used by BMM
+ @param FormId ID of the form which has sent the request to apply change.
+
+ @retval EFI_SUCCESS Change successfully applied.
+ @retval Other Error occurs while trying to apply changes.
+
+**/
+EFI_STATUS
+ApplyChangeHandler (
+ IN BMM_CALLBACK_DATA *Private,
+ IN BMM_FAKE_NV_DATA *CurrentFakeNVMap,
+ IN EFI_FORM_ID FormId
+ );
+
+/**
+ Discard all changes done to the BMM pages such as Boot Order change,
+ Driver order change.
+
+ @param Private The BMM context data.
+ @param CurrentFakeNVMap The current Fack NV Map.
+
+**/
+VOID
+DiscardChangeHandler (
+ IN BMM_CALLBACK_DATA *Private,
+ IN BMM_FAKE_NV_DATA *CurrentFakeNVMap
+ );
+
+/**
+ Dispatch the display to the next page based on NewPageId.
+
+ @param Private The BMM context data.
+ @param NewPageId The original page ID.
+
+**/
+VOID
+UpdatePageId (
+ BMM_CALLBACK_DATA *Private,
+ UINT16 NewPageId
+ );
+
+/**
+ Boot a file selected by user at File Expoloer of BMM.
+
+ @param FileContext The file context data, which contains the device path
+ of the file to be boot from.
+
+ @retval EFI_SUCCESS The function completed successfull.
+ @return Other value if the boot from the file fails.
+
+**/
+EFI_STATUS
+BootThisFile (
+ IN BM_FILE_CONTEXT *FileContext
+ );
+
+/**
+ Update the file explower page with the refershed file system.
+
+
+ @param CallbackData BMM context data
+ @param KeyValue Key value to identify the type of data to expect.
+
+ @retval TRUE Inform the caller to create a callback packet to exit file explorer.
+ @retval FALSE Indicate that there is no need to exit file explorer.
+
+**/
+BOOLEAN
+UpdateFileExplorer (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN UINT16 KeyValue
+ );
+
+/**
+ This function processes the results of changes in configuration.
+ When user select a interactive opcode, this callback will be triggered.
+ Based on the Question(QuestionId) that triggers the callback, the corresponding
+ actions is performed. It handles:
+
+ 1) the addition of boot option.
+ 2) the addition of driver option.
+ 3) exit from file browser
+ 4) update of file content if a dir is selected.
+ 5) boot the file if a file is selected in "boot from file"
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be saved.
+ @retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
+
+**/
+EFI_STATUS
+EFIAPI
+FileExplorerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ );
+
+/**
+ This function applies changes in a driver's configuration.
+ Input is a Configuration, which has the routing data for this
+ driver followed by name / value configuration pairs. The driver
+ must apply those pairs to its configurable storage. If the
+ driver's configuration is stored in a linear block of data
+ and the driver's name / value pairs are in <BlockConfig>
+ format, it may use the ConfigToBlock helper function (above) to
+ simplify the job. Currently not implemented.
+
+ @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param[in] Configuration A null-terminated Unicode string in
+ <ConfigString> format.
+ @param[out] Progress A pointer to a string filled in with the
+ offset of the most recent '&' before the
+ first failing name / value pair (or the
+ beginn ing of the string if the failure
+ is in the first name / value pair) or
+ the terminating NULL if all was
+ successful.
+
+ @retval EFI_SUCCESS The results have been distributed or are
+ awaiting distribution.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the
+ parts of the results that must be
+ stored awaiting possible future
+ protocols.
+ @retval EFI_INVALID_PARAMETERS Passing in a NULL for the
+ Results parameter would result
+ in this type of error.
+ @retval EFI_NOT_FOUND Target for the specified routing data
+ was not found.
+**/
+EFI_STATUS
+EFIAPI
+FileExplorerRouteConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Configuration,
+ OUT EFI_STRING *Progress
+ );
+
+/**
+ Dispatch BMM formset and FileExplorer formset.
+
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS If function complete successfully.
+ @return Other value if the Setup Browser process BMM's pages and
+ return unsuccessfully.
+
+**/
+EFI_STATUS
+FormSetDispatcher (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Function returns the value of the specified variable.
+
+ @param Name A Null-terminated Unicode string that is
+ the name of the vendor's variable.
+ @param VendorGuid A unique identifier for the vendor.
+
+ @return The payload of the variable.
+ @retval NULL If the variable can't be read.
+
+**/
+VOID *
+EfiLibGetVariable (
+ IN CHAR16 *Name,
+ IN EFI_GUID *VendorGuid
+ );
+
+/**
+ Get option number according to Boot#### and BootOrder variable.
+ The value is saved as #### + 1.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetBootOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Get driver option order from globalc DriverOptionMenu.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetDriverOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+ Intall BootMaint and FileExplorer HiiPackages.
+
+**/
+EFI_STATUS
+InitBMPackage (
+ VOID
+ );
+
+/**
+ Remvoe the intalled BootMaint and FileExplorer HiiPackages.
+
+**/
+VOID
+FreeBMPackage (
+ VOID
+ );
+
+/**
+ According to LegacyDevOrder variable to get legacy FD\HD\CD\NET\BEV
+ devices list .
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetLegacyDeviceOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Initialize console input device check box to ConsoleInCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleInCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Initialize console output device check box to ConsoleOutCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleOutCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Initialize standard error output device check box to ConsoleErrCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleErrCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Initialize terminal attributes (baudrate, data rate, stop bits, parity and terminal type)
+ to BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetTerminalAttribute (
+ IN BMM_CALLBACK_DATA *CallbackData
+ );
+
+/**
+
+ Find the first instance of this Protocol
+ in the system and return it's interface.
+
+
+ @param ProtocolGuid Provides the protocol to search for
+ @param Interface On return, a pointer to the first interface
+ that matches ProtocolGuid
+
+ @retval EFI_SUCCESS A protocol instance matching ProtocolGuid was found
+ @retval EFI_NOT_FOUND No protocol instances were found that match ProtocolGuid
+
+**/
+EFI_STATUS
+EfiLibLocateProtocol (
+ IN EFI_GUID *ProtocolGuid,
+ OUT VOID **Interface
+ );
+
+//
+// Global variable in this program (defined in data.c)
+//
+extern BM_MENU_OPTION BootOptionMenu;
+extern BM_MENU_OPTION DriverOptionMenu;
+extern BM_MENU_OPTION FsOptionMenu;
+extern BM_MENU_OPTION ConsoleInpMenu;
+extern BM_MENU_OPTION ConsoleOutMenu;
+extern BM_MENU_OPTION ConsoleErrMenu;
+extern BM_MENU_OPTION DirectoryMenu;
+extern BM_MENU_OPTION DriverMenu;
+extern BM_MENU_OPTION TerminalMenu;
+extern BM_MENU_OPTION LegacyFDMenu;
+extern BM_MENU_OPTION LegacyHDMenu;
+extern BM_MENU_OPTION LegacyCDMenu;
+extern BM_MENU_OPTION LegacyNETMenu;
+extern BM_MENU_OPTION LegacyBEVMenu;
+extern UINT16 TerminalType[];
+extern COM_ATTR BaudRateList[19];
+extern COM_ATTR DataBitsList[4];
+extern COM_ATTR ParityList[5];
+extern COM_ATTR StopBitsList[3];
+extern EFI_GUID TerminalTypeGuid[4];
+extern STRING_DEPOSITORY *FileOptionStrDepository;
+extern STRING_DEPOSITORY *ConsoleOptionStrDepository;
+extern STRING_DEPOSITORY *BootOptionStrDepository;
+extern STRING_DEPOSITORY *BootOptionHelpStrDepository;
+extern STRING_DEPOSITORY *DriverOptionStrDepository;
+extern STRING_DEPOSITORY *DriverOptionHelpStrDepository;
+extern STRING_DEPOSITORY *TerminalStrDepository;
+extern EFI_DEVICE_PATH_PROTOCOL EndDevicePath[];
+extern UINT16 mFlowControlType[2];
+extern UINT32 mFlowControlValue[2];
+//
+// Shared IFR form update data
+//
+extern VOID *mStartOpCodeHandle;
+extern VOID *mEndOpCodeHandle;
+extern EFI_IFR_GUID_LABEL *mStartLabel;
+extern EFI_IFR_GUID_LABEL *mEndLabel;
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
new file mode 100644
index 0000000000..6233a1145a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
@@ -0,0 +1,1823 @@
+/** @file
+ Provide boot option support for Application "BootMaint"
+
+ Include file system navigation, system handle selection
+
+ Boot option manipulation
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BootMaint.h"
+#include "BBSsupport.h"
+
+/**
+ Create a menu entry by given menu type.
+
+ @param MenuType The Menu type to be created.
+
+ @retval NULL If failed to create the menu.
+ @return the new menu entry.
+
+**/
+BM_MENU_ENTRY *
+BOpt_CreateMenuEntry (
+ UINTN MenuType
+ )
+{
+ BM_MENU_ENTRY *MenuEntry;
+ UINTN ContextSize;
+
+ //
+ // Get context size according to menu type
+ //
+ switch (MenuType) {
+ case BM_LOAD_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_LOAD_CONTEXT);
+ break;
+
+ case BM_FILE_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_FILE_CONTEXT);
+ break;
+
+ case BM_CONSOLE_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_CONSOLE_CONTEXT);
+ break;
+
+ case BM_TERMINAL_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_TERMINAL_CONTEXT);
+ break;
+
+ case BM_HANDLE_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_HANDLE_CONTEXT);
+ break;
+
+ case BM_LEGACY_DEV_CONTEXT_SELECT:
+ ContextSize = sizeof (BM_LEGACY_DEVICE_CONTEXT);
+ break;
+
+ default:
+ ContextSize = 0;
+ break;
+ }
+
+ if (ContextSize == 0) {
+ return NULL;
+ }
+
+ //
+ // Create new menu entry
+ //
+ MenuEntry = AllocateZeroPool (sizeof (BM_MENU_ENTRY));
+ if (MenuEntry == NULL) {
+ return NULL;
+ }
+
+ MenuEntry->VariableContext = AllocateZeroPool (ContextSize);
+ if (MenuEntry->VariableContext == NULL) {
+ FreePool (MenuEntry);
+ return NULL;
+ }
+
+ MenuEntry->Signature = BM_MENU_ENTRY_SIGNATURE;
+ MenuEntry->ContextSelection = MenuType;
+ return MenuEntry;
+}
+
+/**
+ Free up all resource allocated for a BM_MENU_ENTRY.
+
+ @param MenuEntry A pointer to BM_MENU_ENTRY.
+
+**/
+VOID
+BOpt_DestroyMenuEntry (
+ BM_MENU_ENTRY *MenuEntry
+ )
+{
+ BM_LOAD_CONTEXT *LoadContext;
+ BM_FILE_CONTEXT *FileContext;
+ BM_CONSOLE_CONTEXT *ConsoleContext;
+ BM_TERMINAL_CONTEXT *TerminalContext;
+ BM_HANDLE_CONTEXT *HandleContext;
+ BM_LEGACY_DEVICE_CONTEXT *LegacyDevContext;
+
+ //
+ // Select by the type in Menu entry for current context type
+ //
+ switch (MenuEntry->ContextSelection) {
+ case BM_LOAD_CONTEXT_SELECT:
+ LoadContext = (BM_LOAD_CONTEXT *) MenuEntry->VariableContext;
+ FreePool (LoadContext->FilePathList);
+ FreePool (LoadContext->LoadOption);
+ if (LoadContext->OptionalData != NULL) {
+ FreePool (LoadContext->OptionalData);
+ }
+ FreePool (LoadContext);
+ break;
+
+ case BM_FILE_CONTEXT_SELECT:
+ FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext;
+
+ if (!FileContext->IsRoot) {
+ FreePool (FileContext->DevicePath);
+ } else {
+ if (FileContext->FHandle != NULL) {
+ FileContext->FHandle->Close (FileContext->FHandle);
+ }
+ }
+
+ if (FileContext->FileName != NULL) {
+ FreePool (FileContext->FileName);
+ }
+ if (FileContext->Info != NULL) {
+ FreePool (FileContext->Info);
+ }
+ FreePool (FileContext);
+ break;
+
+ case BM_CONSOLE_CONTEXT_SELECT:
+ ConsoleContext = (BM_CONSOLE_CONTEXT *) MenuEntry->VariableContext;
+ FreePool (ConsoleContext->DevicePath);
+ FreePool (ConsoleContext);
+ break;
+
+ case BM_TERMINAL_CONTEXT_SELECT:
+ TerminalContext = (BM_TERMINAL_CONTEXT *) MenuEntry->VariableContext;
+ FreePool (TerminalContext->DevicePath);
+ FreePool (TerminalContext);
+ break;
+
+ case BM_HANDLE_CONTEXT_SELECT:
+ HandleContext = (BM_HANDLE_CONTEXT *) MenuEntry->VariableContext;
+ FreePool (HandleContext);
+ break;
+
+ case BM_LEGACY_DEV_CONTEXT_SELECT:
+ LegacyDevContext = (BM_LEGACY_DEVICE_CONTEXT *) MenuEntry->VariableContext;
+ FreePool (LegacyDevContext);
+
+ default:
+ break;
+ }
+
+ FreePool (MenuEntry->DisplayString);
+ if (MenuEntry->HelpString != NULL) {
+ FreePool (MenuEntry->HelpString);
+ }
+
+ FreePool (MenuEntry);
+}
+
+/**
+ Get the Menu Entry from the list in Menu Entry List.
+
+ If MenuNumber is great or equal to the number of Menu
+ Entry in the list, then ASSERT.
+
+ @param MenuOption The Menu Entry List to read the menu entry.
+ @param MenuNumber The index of Menu Entry.
+
+ @return The Menu Entry.
+
+**/
+BM_MENU_ENTRY *
+BOpt_GetMenuEntry (
+ BM_MENU_OPTION *MenuOption,
+ UINTN MenuNumber
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINTN Index;
+ LIST_ENTRY *List;
+
+ ASSERT (MenuNumber < MenuOption->MenuNumber);
+
+ List = MenuOption->Head.ForwardLink;
+ for (Index = 0; Index < MenuNumber; Index++) {
+ List = List->ForwardLink;
+ }
+
+ NewMenuEntry = CR (List, BM_MENU_ENTRY, Link, BM_MENU_ENTRY_SIGNATURE);
+
+ return NewMenuEntry;
+}
+
+/**
+ This function build the FsOptionMenu list which records all
+ available file system in the system. They includes all instances
+ of EFI_SIMPLE_FILE_SYSTEM_PROTOCOL, all instances of EFI_LOAD_FILE_SYSTEM
+ and all type of legacy boot device.
+
+ @param CallbackData BMM context data
+
+ @retval EFI_SUCCESS Success find the file system
+ @retval EFI_OUT_OF_RESOURCES Can not create menu entry
+
+**/
+EFI_STATUS
+BOpt_FindFileSystem (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN NoBlkIoHandles;
+ UINTN NoSimpleFsHandles;
+ UINTN NoLoadFileHandles;
+ EFI_HANDLE *BlkIoHandle;
+ EFI_HANDLE *SimpleFsHandle;
+ EFI_HANDLE *LoadFileHandle;
+ UINT16 *VolumeLabel;
+ EFI_BLOCK_IO_PROTOCOL *BlkIo;
+ UINTN Index;
+ EFI_STATUS Status;
+ BM_MENU_ENTRY *MenuEntry;
+ BM_FILE_CONTEXT *FileContext;
+ UINT16 *TempStr;
+ UINTN OptionNumber;
+ VOID *Buffer;
+ EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
+ UINT16 DeviceType;
+ BBS_BBS_DEVICE_PATH BbsDevicePathNode;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ BOOLEAN RemovableMedia;
+
+
+ NoSimpleFsHandles = 0;
+ NoLoadFileHandles = 0;
+ OptionNumber = 0;
+ InitializeListHead (&FsOptionMenu.Head);
+
+ //
+ // Locate Handles that support BlockIo protocol
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiBlockIoProtocolGuid,
+ NULL,
+ &NoBlkIoHandles,
+ &BlkIoHandle
+ );
+ if (!EFI_ERROR (Status)) {
+
+ for (Index = 0; Index < NoBlkIoHandles; Index++) {
+ Status = gBS->HandleProtocol (
+ BlkIoHandle[Index],
+ &gEfiBlockIoProtocolGuid,
+ (VOID **) &BlkIo
+ );
+
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ //
+ // Issue a dummy read to trigger reinstall of BlockIo protocol for removable media
+ //
+ if (BlkIo->Media->RemovableMedia) {
+ Buffer = AllocateZeroPool (BlkIo->Media->BlockSize);
+ if (NULL == Buffer) {
+ FreePool (BlkIoHandle);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ BlkIo->ReadBlocks (
+ BlkIo,
+ BlkIo->Media->MediaId,
+ 0,
+ BlkIo->Media->BlockSize,
+ Buffer
+ );
+ FreePool (Buffer);
+ }
+ }
+ FreePool (BlkIoHandle);
+ }
+
+ //
+ // Locate Handles that support Simple File System protocol
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiSimpleFileSystemProtocolGuid,
+ NULL,
+ &NoSimpleFsHandles,
+ &SimpleFsHandle
+ );
+ if (!EFI_ERROR (Status)) {
+ //
+ // Find all the instances of the File System prototocol
+ //
+ for (Index = 0; Index < NoSimpleFsHandles; Index++) {
+ Status = gBS->HandleProtocol (
+ SimpleFsHandle[Index],
+ &gEfiBlockIoProtocolGuid,
+ (VOID **) &BlkIo
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // If no block IO exists assume it's NOT a removable media
+ //
+ RemovableMedia = FALSE;
+ } else {
+ //
+ // If block IO exists check to see if it's remobable media
+ //
+ RemovableMedia = BlkIo->Media->RemovableMedia;
+ }
+
+ //
+ // Allocate pool for this load option
+ //
+ MenuEntry = BOpt_CreateMenuEntry (BM_FILE_CONTEXT_SELECT);
+ if (NULL == MenuEntry) {
+ FreePool (SimpleFsHandle);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext;
+
+ FileContext->Handle = SimpleFsHandle[Index];
+ MenuEntry->OptionNumber = Index;
+ FileContext->FHandle = EfiLibOpenRoot (FileContext->Handle);
+ if (FileContext->FHandle == NULL) {
+ BOpt_DestroyMenuEntry (MenuEntry);
+ continue;
+ }
+
+ MenuEntry->HelpString = DevicePathToStr (DevicePathFromHandle (FileContext->Handle));
+ FileContext->Info = EfiLibFileSystemVolumeLabelInfo (FileContext->FHandle);
+ FileContext->FileName = EfiStrDuplicate (L"\\");
+ FileContext->DevicePath = FileDevicePath (
+ FileContext->Handle,
+ FileContext->FileName
+ );
+ FileContext->IsDir = TRUE;
+ FileContext->IsRoot = TRUE;
+ FileContext->IsRemovableMedia = RemovableMedia;
+ FileContext->IsLoadFile = FALSE;
+
+ //
+ // Get current file system's Volume Label
+ //
+ if (FileContext->Info == NULL) {
+ VolumeLabel = L"NO FILE SYSTEM INFO";
+ } else {
+ VolumeLabel = FileContext->Info->VolumeLabel;
+ if (*VolumeLabel == 0x0000) {
+ VolumeLabel = L"NO VOLUME LABEL";
+ }
+ }
+
+ TempStr = MenuEntry->HelpString;
+ MenuEntry->DisplayString = AllocateZeroPool (MAX_CHAR);
+ ASSERT (MenuEntry->DisplayString != NULL);
+ UnicodeSPrint (
+ MenuEntry->DisplayString,
+ MAX_CHAR,
+ L"%s, [%s]",
+ VolumeLabel,
+ TempStr
+ );
+ OptionNumber++;
+ InsertTailList (&FsOptionMenu.Head, &MenuEntry->Link);
+ }
+ }
+
+ if (NoSimpleFsHandles != 0) {
+ FreePool (SimpleFsHandle);
+ }
+ //
+ // Searching for handles that support Load File protocol
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiLoadFileProtocolGuid,
+ NULL,
+ &NoLoadFileHandles,
+ &LoadFileHandle
+ );
+
+ if (!EFI_ERROR (Status)) {
+ for (Index = 0; Index < NoLoadFileHandles; Index++) {
+ MenuEntry = BOpt_CreateMenuEntry (BM_FILE_CONTEXT_SELECT);
+ if (NULL == MenuEntry) {
+ FreePool (LoadFileHandle);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext;
+ FileContext->IsRemovableMedia = FALSE;
+ FileContext->IsLoadFile = TRUE;
+ FileContext->Handle = LoadFileHandle[Index];
+ FileContext->IsRoot = TRUE;
+
+ FileContext->DevicePath = DevicePathFromHandle (FileContext->Handle);
+ FileContext->FileName = DevicePathToStr (FileContext->DevicePath);
+
+ MenuEntry->HelpString = DevicePathToStr (FileContext->DevicePath);
+
+ TempStr = MenuEntry->HelpString;
+ MenuEntry->DisplayString = AllocateZeroPool (MAX_CHAR);
+ ASSERT (MenuEntry->DisplayString != NULL);
+ UnicodeSPrint (
+ MenuEntry->DisplayString,
+ MAX_CHAR,
+ L"Load File [%s]",
+ TempStr
+ );
+
+ MenuEntry->OptionNumber = OptionNumber;
+ OptionNumber++;
+ InsertTailList (&FsOptionMenu.Head, &MenuEntry->Link);
+ }
+ }
+
+ if (NoLoadFileHandles != 0) {
+ FreePool (LoadFileHandle);
+ }
+
+ //
+ // Add Legacy Boot Option Support Here
+ //
+ Status = gBS->LocateProtocol (
+ &gEfiLegacyBiosProtocolGuid,
+ NULL,
+ (VOID **) &LegacyBios
+ );
+ if (!EFI_ERROR (Status)) {
+
+ for (Index = BBS_TYPE_FLOPPY; Index <= BBS_TYPE_EMBEDDED_NETWORK; Index++) {
+ MenuEntry = BOpt_CreateMenuEntry (BM_FILE_CONTEXT_SELECT);
+ if (NULL == MenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext;
+
+ FileContext->IsRemovableMedia = FALSE;
+ FileContext->IsLoadFile = TRUE;
+ FileContext->IsBootLegacy = TRUE;
+ DeviceType = (UINT16) Index;
+ BbsDevicePathNode.Header.Type = BBS_DEVICE_PATH;
+ BbsDevicePathNode.Header.SubType = BBS_BBS_DP;
+ SetDevicePathNodeLength (
+ &BbsDevicePathNode.Header,
+ sizeof (BBS_BBS_DEVICE_PATH)
+ );
+ BbsDevicePathNode.DeviceType = DeviceType;
+ BbsDevicePathNode.StatusFlag = 0;
+ BbsDevicePathNode.String[0] = 0;
+ DevicePath = AppendDevicePathNode (
+ EndDevicePath,
+ (EFI_DEVICE_PATH_PROTOCOL *) &BbsDevicePathNode
+ );
+
+ FileContext->DevicePath = DevicePath;
+ MenuEntry->HelpString = DevicePathToStr (FileContext->DevicePath);
+
+ TempStr = MenuEntry->HelpString;
+ MenuEntry->DisplayString = AllocateZeroPool (MAX_CHAR);
+ ASSERT (MenuEntry->DisplayString != NULL);
+ UnicodeSPrint (
+ MenuEntry->DisplayString,
+ MAX_CHAR,
+ L"Boot Legacy [%s]",
+ TempStr
+ );
+ MenuEntry->OptionNumber = OptionNumber;
+ OptionNumber++;
+ InsertTailList (&FsOptionMenu.Head, &MenuEntry->Link);
+ }
+ }
+ //
+ // Remember how many file system options are here
+ //
+ FsOptionMenu.MenuNumber = OptionNumber;
+ return EFI_SUCCESS;
+}
+
+/**
+ Free resources allocated in Allocate Rountine.
+
+ @param FreeMenu Menu to be freed
+**/
+VOID
+BOpt_FreeMenu (
+ BM_MENU_OPTION *FreeMenu
+ )
+{
+ BM_MENU_ENTRY *MenuEntry;
+ while (!IsListEmpty (&FreeMenu->Head)) {
+ MenuEntry = CR (
+ FreeMenu->Head.ForwardLink,
+ BM_MENU_ENTRY,
+ Link,
+ BM_MENU_ENTRY_SIGNATURE
+ );
+ RemoveEntryList (&MenuEntry->Link);
+ BOpt_DestroyMenuEntry (MenuEntry);
+ }
+ FreeMenu->MenuNumber = 0;
+}
+
+/**
+ Find files under current directory
+ All files and sub-directories in current directory
+ will be stored in DirectoryMenu for future use.
+
+ @param CallbackData The BMM context data.
+ @param MenuEntry The Menu Entry.
+
+ @retval EFI_SUCCESS Get files from current dir successfully.
+ @return Other value if can't get files from current dir.
+
+**/
+EFI_STATUS
+BOpt_FindFiles (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN BM_MENU_ENTRY *MenuEntry
+ )
+{
+ EFI_FILE_HANDLE NewDir;
+ EFI_FILE_HANDLE Dir;
+ EFI_FILE_INFO *DirInfo;
+ UINTN BufferSize;
+ UINTN DirBufferSize;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_FILE_CONTEXT *FileContext;
+ BM_FILE_CONTEXT *NewFileContext;
+ UINTN Pass;
+ EFI_STATUS Status;
+ UINTN OptionNumber;
+
+ FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext;
+ Dir = FileContext->FHandle;
+ OptionNumber = 0;
+ //
+ // Open current directory to get files from it
+ //
+ Status = Dir->Open (
+ Dir,
+ &NewDir,
+ FileContext->FileName,
+ EFI_FILE_READ_ONLY,
+ 0
+ );
+ if (!FileContext->IsRoot) {
+ Dir->Close (Dir);
+ }
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ DirInfo = EfiLibFileInfo (NewDir);
+ if (DirInfo == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ if ((DirInfo->Attribute & EFI_FILE_DIRECTORY) == 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FileContext->DevicePath = FileDevicePath (
+ FileContext->Handle,
+ FileContext->FileName
+ );
+
+ DirBufferSize = sizeof (EFI_FILE_INFO) + 1024;
+ DirInfo = AllocateZeroPool (DirBufferSize);
+ if (DirInfo == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Get all files in current directory
+ // Pass 1 to get Directories
+ // Pass 2 to get files that are EFI images
+ //
+ for (Pass = 1; Pass <= 2; Pass++) {
+ NewDir->SetPosition (NewDir, 0);
+ for (;;) {
+ BufferSize = DirBufferSize;
+ Status = NewDir->Read (NewDir, &BufferSize, DirInfo);
+ if (EFI_ERROR (Status) || BufferSize == 0) {
+ break;
+ }
+
+ if (((DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0 && Pass == 2) ||
+ ((DirInfo->Attribute & EFI_FILE_DIRECTORY) == 0 && Pass == 1)
+ ) {
+ //
+ // Pass 1 is for Directories
+ // Pass 2 is for file names
+ //
+ continue;
+ }
+
+ if (!(BOpt_IsEfiImageName (DirInfo->FileName) || (DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0)) {
+ //
+ // Slip file unless it is a directory entry or a .EFI file
+ //
+ continue;
+ }
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_FILE_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileContext = (BM_FILE_CONTEXT *) NewMenuEntry->VariableContext;
+ NewFileContext->Handle = FileContext->Handle;
+ NewFileContext->FileName = BOpt_AppendFileName (
+ FileContext->FileName,
+ DirInfo->FileName
+ );
+ NewFileContext->FHandle = NewDir;
+ NewFileContext->DevicePath = FileDevicePath (
+ NewFileContext->Handle,
+ NewFileContext->FileName
+ );
+ NewMenuEntry->HelpString = NULL;
+
+ MenuEntry->DisplayStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ FileOptionStrDepository
+ );
+
+ NewFileContext->IsDir = (BOOLEAN) ((DirInfo->Attribute & EFI_FILE_DIRECTORY) == EFI_FILE_DIRECTORY);
+
+ if (NewFileContext->IsDir) {
+ BufferSize = StrLen (DirInfo->FileName) * 2 + 6;
+ NewMenuEntry->DisplayString = AllocateZeroPool (BufferSize);
+
+ UnicodeSPrint (
+ NewMenuEntry->DisplayString,
+ BufferSize,
+ L"<%s>",
+ DirInfo->FileName
+ );
+
+ } else {
+ NewMenuEntry->DisplayString = EfiStrDuplicate (DirInfo->FileName);
+ }
+
+ NewFileContext->IsRoot = FALSE;
+ NewFileContext->IsLoadFile = FALSE;
+ NewFileContext->IsRemovableMedia = FALSE;
+
+ NewMenuEntry->OptionNumber = OptionNumber;
+ OptionNumber++;
+ InsertTailList (&DirectoryMenu.Head, &NewMenuEntry->Link);
+ }
+ }
+
+ DirectoryMenu.MenuNumber = OptionNumber;
+ FreePool (DirInfo);
+ return EFI_SUCCESS;
+}
+
+/**
+ Build the LegacyFDMenu LegacyHDMenu LegacyCDMenu according to LegacyBios.GetBbsInfo().
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to complete this function.
+
+**/
+EFI_STATUS
+BOpt_GetLegacyOptions (
+ VOID
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LEGACY_DEVICE_CONTEXT *NewLegacyDevContext;
+ EFI_STATUS Status;
+ EFI_LEGACY_BIOS_PROTOCOL *LegacyBios;
+ UINT16 HddCount;
+ HDD_INFO *HddInfo;
+ UINT16 BbsCount;
+ BBS_TABLE *BbsTable;
+ UINT16 Index;
+ CHAR16 DescString[100];
+ UINTN FDNum;
+ UINTN HDNum;
+ UINTN CDNum;
+ UINTN NETNum;
+ UINTN BEVNum;
+
+ NewMenuEntry = NULL;
+ HddInfo = NULL;
+ BbsTable = NULL;
+ BbsCount = 0;
+
+ //
+ // Initialize Bbs Table Context from BBS info data
+ //
+ InitializeListHead (&LegacyFDMenu.Head);
+ InitializeListHead (&LegacyHDMenu.Head);
+ InitializeListHead (&LegacyCDMenu.Head);
+ InitializeListHead (&LegacyNETMenu.Head);
+ InitializeListHead (&LegacyBEVMenu.Head);
+
+ Status = gBS->LocateProtocol (
+ &gEfiLegacyBiosProtocolGuid,
+ NULL,
+ (VOID **) &LegacyBios
+ );
+ if (!EFI_ERROR (Status)) {
+ Status = LegacyBios->GetBbsInfo (
+ LegacyBios,
+ &HddCount,
+ &HddInfo,
+ &BbsCount,
+ &BbsTable
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ FDNum = 0;
+ HDNum = 0;
+ CDNum = 0;
+ NETNum = 0;
+ BEVNum = 0;
+
+ for (Index = 0; Index < BbsCount; Index++) {
+ if ((BBS_IGNORE_ENTRY == BbsTable[Index].BootPriority) ||
+ (BBS_DO_NOT_BOOT_FROM == BbsTable[Index].BootPriority)
+ ) {
+ continue;
+ }
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_LEGACY_DEV_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ break;
+ }
+
+ NewLegacyDevContext = (BM_LEGACY_DEVICE_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLegacyDevContext->BbsEntry = &BbsTable[Index];
+ NewLegacyDevContext->BbsIndex = Index;
+ NewLegacyDevContext->BbsCount = BbsCount;
+ BdsBuildLegacyDevNameString (
+ &BbsTable[Index],
+ Index,
+ sizeof (DescString),
+ DescString
+ );
+ NewLegacyDevContext->Description = AllocateCopyPool (StrSize (DescString), DescString);
+ if (NULL == NewLegacyDevContext->Description) {
+ break;
+ }
+
+ NewMenuEntry->DisplayString = NewLegacyDevContext->Description;
+ NewMenuEntry->HelpString = NULL;
+
+ switch (BbsTable[Index].DeviceType) {
+ case BBS_FLOPPY:
+ InsertTailList (&LegacyFDMenu.Head, &NewMenuEntry->Link);
+ FDNum++;
+ break;
+
+ case BBS_HARDDISK:
+ InsertTailList (&LegacyHDMenu.Head, &NewMenuEntry->Link);
+ HDNum++;
+ break;
+
+ case BBS_CDROM:
+ InsertTailList (&LegacyCDMenu.Head, &NewMenuEntry->Link);
+ CDNum++;
+ break;
+
+ case BBS_EMBED_NETWORK:
+ InsertTailList (&LegacyNETMenu.Head, &NewMenuEntry->Link);
+ NETNum++;
+ break;
+
+ case BBS_BEV_DEVICE:
+ InsertTailList (&LegacyBEVMenu.Head, &NewMenuEntry->Link);
+ BEVNum++;
+ break;
+ }
+ }
+
+ if (Index != BbsCount) {
+ BOpt_FreeLegacyOptions ();
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ LegacyFDMenu.MenuNumber = FDNum;
+ LegacyHDMenu.MenuNumber = HDNum;
+ LegacyCDMenu.MenuNumber = CDNum;
+ LegacyNETMenu.MenuNumber = NETNum;
+ LegacyBEVMenu.MenuNumber = BEVNum;
+ return EFI_SUCCESS;
+}
+
+/**
+ Free out resouce allocated from Legacy Boot Options.
+
+**/
+VOID
+BOpt_FreeLegacyOptions (
+ VOID
+ )
+{
+ BOpt_FreeMenu (&LegacyFDMenu);
+ BOpt_FreeMenu (&LegacyHDMenu);
+ BOpt_FreeMenu (&LegacyCDMenu);
+ BOpt_FreeMenu (&LegacyNETMenu);
+ BOpt_FreeMenu (&LegacyBEVMenu);
+}
+
+/**
+
+ Build the BootOptionMenu according to BootOrder Variable.
+ This Routine will access the Boot#### to get EFI_LOAD_OPTION.
+
+ @param CallbackData The BMM context data.
+
+ @return EFI_NOT_FOUND Fail to find "BootOrder" variable.
+ @return EFI_SUCESS Success build boot option menu.
+
+**/
+EFI_STATUS
+BOpt_GetBootOptions (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN Index;
+ UINT16 BootString[10];
+ UINT8 *LoadOptionFromVar;
+ UINT8 *LoadOption;
+ UINTN BootOptionSize;
+ BOOLEAN BootNextFlag;
+ UINT16 *BootOrderList;
+ UINTN BootOrderListSize;
+ UINT16 *BootNext;
+ UINTN BootNextSize;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT8 *LoadOptionPtr;
+ UINTN StringSize;
+ UINTN OptionalDataSize;
+ UINT8 *LoadOptionEnd;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ UINTN MenuCount;
+ UINT8 *Ptr;
+
+ MenuCount = 0;
+ BootOrderListSize = 0;
+ BootNextSize = 0;
+ BootOrderList = NULL;
+ BootNext = NULL;
+ LoadOptionFromVar = NULL;
+ BOpt_FreeMenu (&BootOptionMenu);
+ InitializeListHead (&BootOptionMenu.Head);
+
+ //
+ // Get the BootOrder from the Var
+ //
+ BootOrderList = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderListSize
+ );
+ if (BootOrderList == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Get the BootNext from the Var
+ //
+ BootNext = BdsLibGetVariableAndSize (
+ L"BootNext",
+ &gEfiGlobalVariableGuid,
+ &BootNextSize
+ );
+
+ if (BootNext != NULL) {
+ if (BootNextSize != sizeof (UINT16)) {
+ FreePool (BootNext);
+ BootNext = NULL;
+ }
+ }
+
+ for (Index = 0; Index < BootOrderListSize / sizeof (UINT16); Index++) {
+ UnicodeSPrint (BootString, sizeof (BootString), L"Boot%04x", BootOrderList[Index]);
+ //
+ // Get all loadoptions from the VAR
+ //
+ LoadOptionFromVar = BdsLibGetVariableAndSize (
+ BootString,
+ &gEfiGlobalVariableGuid,
+ &BootOptionSize
+ );
+ if (LoadOptionFromVar == NULL) {
+ continue;
+ }
+
+ LoadOption = AllocateZeroPool (BootOptionSize);
+ if (LoadOption == NULL) {
+ continue;
+ }
+
+ CopyMem (LoadOption, LoadOptionFromVar, BootOptionSize);
+ FreePool (LoadOptionFromVar);
+
+ if (BootNext != NULL) {
+ BootNextFlag = (BOOLEAN) (*BootNext == BootOrderList[Index]);
+ } else {
+ BootNextFlag = FALSE;
+ }
+
+ if (0 == (*((UINT32 *) LoadOption) & LOAD_OPTION_ACTIVE)) {
+ FreePool (LoadOption);
+ continue;
+ }
+ //
+ // BUGBUG: could not return EFI_OUT_OF_RESOURCES here directly.
+ // the buffer allocated already should be freed before returning.
+ //
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+
+ LoadOptionPtr = LoadOption;
+ LoadOptionEnd = LoadOption + BootOptionSize;
+
+ NewMenuEntry->OptionNumber = BootOrderList[Index];
+ NewLoadContext->LoadOptionModified = FALSE;
+ NewLoadContext->Deleted = FALSE;
+ NewLoadContext->IsBootNext = BootNextFlag;
+
+ //
+ // Is a Legacy Device?
+ //
+ Ptr = (UINT8 *) LoadOption;
+
+ //
+ // Attribute = *(UINT32 *)Ptr;
+ //
+ Ptr += sizeof (UINT32);
+
+ //
+ // FilePathSize = *(UINT16 *)Ptr;
+ //
+ Ptr += sizeof (UINT16);
+
+ //
+ // Description = (CHAR16 *)Ptr;
+ //
+ Ptr += StrSize ((CHAR16 *) Ptr);
+
+ //
+ // Now Ptr point to Device Path
+ //
+ DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Ptr;
+ if ((BBS_DEVICE_PATH == DevicePath->Type) && (BBS_BBS_DP == DevicePath->SubType)) {
+ NewLoadContext->IsLegacy = TRUE;
+ } else {
+ NewLoadContext->IsLegacy = FALSE;
+ }
+ //
+ // LoadOption is a pointer type of UINT8
+ // for easy use with following LOAD_OPTION
+ // embedded in this struct
+ //
+ NewLoadContext->LoadOption = LoadOption;
+ NewLoadContext->LoadOptionSize = BootOptionSize;
+
+ NewLoadContext->Attributes = *(UINT32 *) LoadOptionPtr;
+ NewLoadContext->IsActive = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_ACTIVE);
+
+ NewLoadContext->ForceReconnect = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_FORCE_RECONNECT);
+
+ LoadOptionPtr += sizeof (UINT32);
+
+ NewLoadContext->FilePathListLength = *(UINT16 *) LoadOptionPtr;
+ LoadOptionPtr += sizeof (UINT16);
+
+ StringSize = StrSize((UINT16*)LoadOptionPtr);
+
+ NewLoadContext->Description = AllocateCopyPool (StrSize((UINT16*)LoadOptionPtr), LoadOptionPtr);
+ ASSERT (NewLoadContext->Description != NULL);
+
+ NewMenuEntry->DisplayString = NewLoadContext->Description;
+
+ LoadOptionPtr += StringSize;
+
+ NewLoadContext->FilePathList = AllocateZeroPool (NewLoadContext->FilePathListLength);
+ ASSERT (NewLoadContext->FilePathList != NULL);
+ CopyMem (
+ NewLoadContext->FilePathList,
+ (EFI_DEVICE_PATH_PROTOCOL *) LoadOptionPtr,
+ NewLoadContext->FilePathListLength
+ );
+
+ NewMenuEntry->HelpString = DevicePathToStr (NewLoadContext->FilePathList);
+ NewMenuEntry->DisplayStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ BootOptionStrDepository
+ );
+ NewMenuEntry->HelpStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ BootOptionHelpStrDepository
+ );
+ LoadOptionPtr += NewLoadContext->FilePathListLength;
+
+ if (LoadOptionPtr < LoadOptionEnd) {
+ OptionalDataSize = BootOptionSize -
+ sizeof (UINT32) -
+ sizeof (UINT16) -
+ StringSize -
+ NewLoadContext->FilePathListLength;
+
+ NewLoadContext->OptionalData = AllocateZeroPool (OptionalDataSize);
+ ASSERT (NewLoadContext->OptionalData != NULL);
+ CopyMem (
+ NewLoadContext->OptionalData,
+ LoadOptionPtr,
+ OptionalDataSize
+ );
+
+ NewLoadContext->OptionalDataSize = OptionalDataSize;
+ }
+
+ InsertTailList (&BootOptionMenu.Head, &NewMenuEntry->Link);
+ MenuCount++;
+ }
+
+ if (BootNext != NULL) {
+ FreePool (BootNext);
+ }
+ if (BootOrderList != NULL) {
+ FreePool (BootOrderList);
+ }
+ BootOptionMenu.MenuNumber = MenuCount;
+ return EFI_SUCCESS;
+}
+
+/**
+
+ Append file name to existing file name.
+
+ @param Str1 The existing file name
+ @param Str2 The file name to be appended
+
+ @return Allocate a new string to hold the appended result.
+ Caller is responsible to free the returned string.
+
+**/
+CHAR16 *
+BOpt_AppendFileName (
+ IN CHAR16 *Str1,
+ IN CHAR16 *Str2
+ )
+{
+ UINTN Size1;
+ UINTN Size2;
+ UINTN MaxLen;
+ CHAR16 *Str;
+ CHAR16 *TmpStr;
+ CHAR16 *Ptr;
+ CHAR16 *LastSlash;
+
+ Size1 = StrSize (Str1);
+ Size2 = StrSize (Str2);
+ MaxLen = (Size1 + Size2 + sizeof (CHAR16)) / sizeof (CHAR16);
+ Str = AllocateZeroPool (MaxLen * sizeof (CHAR16));
+ ASSERT (Str != NULL);
+
+ TmpStr = AllocateZeroPool (MaxLen * sizeof (CHAR16));
+ ASSERT (TmpStr != NULL);
+
+ StrCatS (Str, MaxLen, Str1);
+ if (!((*Str == '\\') && (*(Str + 1) == 0))) {
+ StrCatS (Str, MaxLen, L"\\");
+ }
+
+ StrCatS (Str, MaxLen, Str2);
+
+ Ptr = Str;
+ LastSlash = Str;
+ while (*Ptr != 0) {
+ if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '.' && *(Ptr + 3) == L'\\') {
+ //
+ // Convert "\Name\..\" to "\"
+ // DO NOT convert the .. if it is at the end of the string. This will
+ // break the .. behavior in changing directories.
+ //
+
+ //
+ // Use TmpStr as a backup, as StrCpyS in BaseLib does not handle copy of two strings
+ // that overlap.
+ //
+ StrCpyS (TmpStr, MaxLen, Ptr + 3);
+ StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / sizeof (CHAR16), TmpStr);
+ Ptr = LastSlash;
+ } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') {
+ //
+ // Convert a "\.\" to a "\"
+ //
+
+ //
+ // Use TmpStr as a backup, as StrCpyS in BaseLib does not handle copy of two strings
+ // that overlap.
+ //
+ StrCpyS (TmpStr, MaxLen, Ptr + 2);
+ StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof (CHAR16), TmpStr);
+ Ptr = LastSlash;
+ } else if (*Ptr == '\\') {
+ LastSlash = Ptr;
+ }
+
+ Ptr++;
+ }
+
+ FreePool (TmpStr);
+
+ return Str;
+}
+
+/**
+
+ Check whether current FileName point to a valid
+ Efi Image File.
+
+ @param FileName File need to be checked.
+
+ @retval TRUE Is Efi Image
+ @retval FALSE Not a valid Efi Image
+
+**/
+BOOLEAN
+BOpt_IsEfiImageName (
+ IN UINT16 *FileName
+ )
+{
+ //
+ // Search for ".efi" extension
+ //
+ while (*FileName != L'\0') {
+ if (FileName[0] == '.') {
+ if (FileName[1] == 'e' || FileName[1] == 'E') {
+ if (FileName[2] == 'f' || FileName[2] == 'F') {
+ if (FileName[3] == 'i' || FileName[3] == 'I') {
+ return TRUE;
+ } else if (FileName[3] == 0x0000) {
+ return FALSE;
+ }
+ } else if (FileName[2] == 0x0000) {
+ return FALSE;
+ }
+ } else if (FileName[1] == 0x0000) {
+ return FALSE;
+ }
+ }
+
+ FileName += 1;
+ }
+
+ return FALSE;
+}
+
+/**
+
+ Check whether current FileName point to a valid Efi Application
+
+ @param Dir Pointer to current Directory
+ @param FileName Pointer to current File name.
+
+ @retval TRUE Is a valid Efi Application
+ @retval FALSE not a valid Efi Application
+
+**/
+BOOLEAN
+BOpt_IsEfiApp (
+ IN EFI_FILE_HANDLE Dir,
+ IN UINT16 *FileName
+ )
+{
+ UINTN BufferSize;
+ EFI_IMAGE_DOS_HEADER DosHdr;
+ UINT16 Subsystem;
+ EFI_FILE_HANDLE File;
+ EFI_STATUS Status;
+ EFI_IMAGE_OPTIONAL_HEADER_UNION PeHdr;
+
+ Status = Dir->Open (Dir, &File, FileName, EFI_FILE_MODE_READ, 0);
+
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ BufferSize = sizeof (EFI_IMAGE_DOS_HEADER);
+ File->Read (File, &BufferSize, &DosHdr);
+ if (DosHdr.e_magic != EFI_IMAGE_DOS_SIGNATURE) {
+ File->Close (File);
+ return FALSE;
+ }
+
+ File->SetPosition (File, DosHdr.e_lfanew);
+ BufferSize = sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION);
+ File->Read (File, &BufferSize, &PeHdr);
+ if (PeHdr.Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
+ File->Close (File);
+ return FALSE;
+ }
+ //
+ // Determine PE type and read subsytem
+ //
+ if (PeHdr.Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ Subsystem = PeHdr.Pe32.OptionalHeader.Subsystem;
+ } else if (PeHdr.Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
+ Subsystem = PeHdr.Pe32Plus.OptionalHeader.Subsystem;
+ } else {
+ return FALSE;
+ }
+
+ if (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
+ File->Close (File);
+ return TRUE;
+ } else {
+ File->Close (File);
+ return FALSE;
+ }
+}
+
+/**
+
+ Find drivers that will be added as Driver#### variables from handles
+ in current system environment
+ All valid handles in the system except those consume SimpleFs, LoadFile
+ are stored in DriverMenu for future use.
+
+ @retval EFI_SUCCESS The function complets successfully.
+ @return Other value if failed to build the DriverMenu.
+
+**/
+EFI_STATUS
+BOpt_FindDrivers (
+ VOID
+ )
+{
+ UINTN NoDevicePathHandles;
+ EFI_HANDLE *DevicePathHandle;
+ UINTN Index;
+ EFI_STATUS Status;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_HANDLE_CONTEXT *NewHandleContext;
+ EFI_HANDLE CurHandle;
+ UINTN OptionNumber;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *SimpleFs;
+ EFI_LOAD_FILE_PROTOCOL *LoadFile;
+
+ SimpleFs = NULL;
+ LoadFile = NULL;
+
+ InitializeListHead (&DriverMenu.Head);
+
+ //
+ // At first, get all handles that support Device Path
+ // protocol which is the basic requirement for
+ // Driver####
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiDevicePathProtocolGuid,
+ NULL,
+ &NoDevicePathHandles,
+ &DevicePathHandle
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ OptionNumber = 0;
+ for (Index = 0; Index < NoDevicePathHandles; Index++) {
+ CurHandle = DevicePathHandle[Index];
+
+ Status = gBS->HandleProtocol (
+ CurHandle,
+ &gEfiSimpleFileSystemProtocolGuid,
+ (VOID **) &SimpleFs
+ );
+ if (Status == EFI_SUCCESS) {
+ continue;
+ }
+
+ Status = gBS->HandleProtocol (
+ CurHandle,
+ &gEfiLoadFileProtocolGuid,
+ (VOID **) &LoadFile
+ );
+ if (Status == EFI_SUCCESS) {
+ continue;
+ }
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_HANDLE_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ FreePool (DevicePathHandle);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewHandleContext = (BM_HANDLE_CONTEXT *) NewMenuEntry->VariableContext;
+ NewHandleContext->Handle = CurHandle;
+ NewHandleContext->DevicePath = DevicePathFromHandle (CurHandle);
+ NewMenuEntry->DisplayString = DevicePathToStr (NewHandleContext->DevicePath);
+ NewMenuEntry->HelpString = NULL;
+ NewMenuEntry->OptionNumber = OptionNumber;
+ OptionNumber++;
+ InsertTailList (&DriverMenu.Head, &NewMenuEntry->Link);
+
+ }
+
+ if (DevicePathHandle != NULL) {
+ FreePool (DevicePathHandle);
+ }
+
+ DriverMenu.MenuNumber = OptionNumber;
+ return EFI_SUCCESS;
+}
+
+/**
+
+ Get the Option Number that has not been allocated for use.
+
+ @param Type The type of Option.
+
+ @return The available Option Number.
+
+**/
+UINT16
+BOpt_GetOptionNumber (
+ CHAR16 *Type
+ )
+{
+ UINT16 *OrderList;
+ UINTN OrderListSize;
+ UINTN Index;
+ CHAR16 StrTemp[20];
+ UINT16 *OptionBuffer;
+ UINT16 OptionNumber;
+ UINTN OptionSize;
+
+ OrderListSize = 0;
+ OrderList = NULL;
+ OptionNumber = 0;
+ Index = 0;
+
+ UnicodeSPrint (StrTemp, sizeof (StrTemp), L"%sOrder", Type);
+
+ OrderList = BdsLibGetVariableAndSize (
+ StrTemp,
+ &gEfiGlobalVariableGuid,
+ &OrderListSize
+ );
+
+ for (OptionNumber = 0; ; OptionNumber++) {
+ if (OrderList != NULL) {
+ for (Index = 0; Index < OrderListSize / sizeof (UINT16); Index++) {
+ if (OptionNumber == OrderList[Index]) {
+ break;
+ }
+ }
+ }
+
+ if (Index < OrderListSize / sizeof (UINT16)) {
+ //
+ // The OptionNumber occurs in the OrderList, continue to use next one
+ //
+ continue;
+ }
+ UnicodeSPrint (StrTemp, sizeof (StrTemp), L"%s%04x", Type, (UINTN) OptionNumber);
+ DEBUG((EFI_D_ERROR,"Option = %s\n", StrTemp));
+ OptionBuffer = BdsLibGetVariableAndSize (
+ StrTemp,
+ &gEfiGlobalVariableGuid,
+ &OptionSize
+ );
+ if (NULL == OptionBuffer) {
+ //
+ // The Boot[OptionNumber] / Driver[OptionNumber] NOT occurs, we found it
+ //
+ break;
+ }
+ }
+
+ return OptionNumber;
+}
+
+/**
+
+ Get the Option Number for Boot#### that does not used.
+
+ @return The available Option Number.
+
+**/
+UINT16
+BOpt_GetBootOptionNumber (
+ VOID
+ )
+{
+ return BOpt_GetOptionNumber (L"Boot");
+}
+
+/**
+
+ Get the Option Number for Driver#### that does not used.
+
+ @return The unused Option Number.
+
+**/
+UINT16
+BOpt_GetDriverOptionNumber (
+ VOID
+ )
+{
+ return BOpt_GetOptionNumber (L"Driver");
+}
+
+/**
+
+ Build up all DriverOptionMenu
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCESS The functin completes successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to compete the operation.
+ @retval EFI_NOT_FOUND Fail to get "DriverOrder" variable.
+
+**/
+EFI_STATUS
+BOpt_GetDriverOptions (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN Index;
+ UINT16 DriverString[12];
+ UINT8 *LoadOptionFromVar;
+ UINT8 *LoadOption;
+ UINTN DriverOptionSize;
+
+ UINT16 *DriverOrderList;
+ UINTN DriverOrderListSize;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT8 *LoadOptionPtr;
+ UINTN StringSize;
+ UINTN OptionalDataSize;
+ UINT8 *LoadOptionEnd;
+
+ DriverOrderListSize = 0;
+ DriverOrderList = NULL;
+ DriverOptionSize = 0;
+ LoadOptionFromVar = NULL;
+ BOpt_FreeMenu (&DriverOptionMenu);
+ InitializeListHead (&DriverOptionMenu.Head);
+ //
+ // Get the DriverOrder from the Var
+ //
+ DriverOrderList = BdsLibGetVariableAndSize (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ &DriverOrderListSize
+ );
+ if (DriverOrderList == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ for (Index = 0; Index < DriverOrderListSize / sizeof (UINT16); Index++) {
+ UnicodeSPrint (
+ DriverString,
+ sizeof (DriverString),
+ L"Driver%04x",
+ DriverOrderList[Index]
+ );
+ //
+ // Get all loadoptions from the VAR
+ //
+ LoadOptionFromVar = BdsLibGetVariableAndSize (
+ DriverString,
+ &gEfiGlobalVariableGuid,
+ &DriverOptionSize
+ );
+ if (LoadOptionFromVar == NULL) {
+ continue;
+ }
+
+ LoadOption = AllocateZeroPool (DriverOptionSize);
+ if (LoadOption == NULL) {
+ continue;
+ }
+
+ CopyMem (LoadOption, LoadOptionFromVar, DriverOptionSize);
+ FreePool (LoadOptionFromVar);
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ LoadOptionPtr = LoadOption;
+ LoadOptionEnd = LoadOption + DriverOptionSize;
+ NewMenuEntry->OptionNumber = DriverOrderList[Index];
+ NewLoadContext->LoadOptionModified = FALSE;
+ NewLoadContext->Deleted = FALSE;
+ NewLoadContext->IsLegacy = FALSE;
+
+ //
+ // LoadOption is a pointer type of UINT8
+ // for easy use with following LOAD_OPTION
+ // embedded in this struct
+ //
+ NewLoadContext->LoadOption = LoadOption;
+ NewLoadContext->LoadOptionSize = DriverOptionSize;
+
+ NewLoadContext->Attributes = *(UINT32 *) LoadOptionPtr;
+ NewLoadContext->IsActive = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_ACTIVE);
+
+ NewLoadContext->ForceReconnect = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_FORCE_RECONNECT);
+
+ LoadOptionPtr += sizeof (UINT32);
+
+ NewLoadContext->FilePathListLength = *(UINT16 *) LoadOptionPtr;
+ LoadOptionPtr += sizeof (UINT16);
+
+ StringSize = StrSize ((UINT16 *) LoadOptionPtr);
+ NewLoadContext->Description = AllocateZeroPool (StringSize);
+ ASSERT (NewLoadContext->Description != NULL);
+ CopyMem (
+ NewLoadContext->Description,
+ (UINT16 *) LoadOptionPtr,
+ StringSize
+ );
+ NewMenuEntry->DisplayString = NewLoadContext->Description;
+
+ LoadOptionPtr += StringSize;
+
+ NewLoadContext->FilePathList = AllocateZeroPool (NewLoadContext->FilePathListLength);
+ ASSERT (NewLoadContext->FilePathList != NULL);
+ CopyMem (
+ NewLoadContext->FilePathList,
+ (EFI_DEVICE_PATH_PROTOCOL *) LoadOptionPtr,
+ NewLoadContext->FilePathListLength
+ );
+
+ NewMenuEntry->HelpString = DevicePathToStr (NewLoadContext->FilePathList);
+ NewMenuEntry->DisplayStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ DriverOptionStrDepository
+ );
+ NewMenuEntry->HelpStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ DriverOptionHelpStrDepository
+ );
+ LoadOptionPtr += NewLoadContext->FilePathListLength;
+
+ if (LoadOptionPtr < LoadOptionEnd) {
+ OptionalDataSize = DriverOptionSize -
+ sizeof (UINT32) -
+ sizeof (UINT16) -
+ StringSize -
+ NewLoadContext->FilePathListLength;
+
+ NewLoadContext->OptionalData = AllocateZeroPool (OptionalDataSize);
+ ASSERT (NewLoadContext->OptionalData != NULL);
+ CopyMem (
+ NewLoadContext->OptionalData,
+ LoadOptionPtr,
+ OptionalDataSize
+ );
+
+ NewLoadContext->OptionalDataSize = OptionalDataSize;
+ }
+
+ InsertTailList (&DriverOptionMenu.Head, &NewMenuEntry->Link);
+
+ }
+
+ if (DriverOrderList != NULL) {
+ FreePool (DriverOrderList);
+ }
+ DriverOptionMenu.MenuNumber = Index;
+ return EFI_SUCCESS;
+
+}
+
+/**
+ Get option number according to Boot#### and BootOrder variable.
+ The value is saved as #### + 1.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetBootOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BMM_FAKE_NV_DATA *BmmConfig;
+ UINT16 Index;
+ UINT16 OptionOrderIndex;
+ UINTN DeviceType;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+
+ ASSERT (CallbackData != NULL);
+
+ DeviceType = (UINTN) -1;
+ BmmConfig = &CallbackData->BmmFakeNvData;
+ ZeroMem (BmmConfig->BootOptionOrder, sizeof (BmmConfig->BootOptionOrder));
+
+ for (Index = 0, OptionOrderIndex = 0; ((Index < BootOptionMenu.MenuNumber) &&
+ (OptionOrderIndex < (sizeof (BmmConfig->BootOptionOrder) / sizeof (BmmConfig->BootOptionOrder[0]))));
+ Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewLoadContext->IsLegacy) {
+ if (((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType != DeviceType) {
+ DeviceType = ((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType;
+ } else {
+ //
+ // Only show one legacy boot option for the same device type
+ // assuming the boot options are grouped by the device type
+ //
+ continue;
+ }
+ }
+ BmmConfig->BootOptionOrder[OptionOrderIndex++] = (UINT32) (NewMenuEntry->OptionNumber + 1);
+ }
+}
+
+/**
+ According to LegacyDevOrder variable to get legacy FD\HD\CD\NET\BEV
+ devices list .
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetLegacyDeviceOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN Index;
+ UINTN OptionIndex;
+ UINT16 PageIdList[5];
+ UINTN PageNum;
+ UINTN VarSize;
+ UINT8 *VarData;
+ UINT8 *WorkingVarData;
+ LEGACY_DEV_ORDER_ENTRY *DevOrder;
+ UINT16 VarDevOrder;
+ UINT8 *DisMap;
+ BM_MENU_OPTION *OptionMenu;
+ BBS_TYPE BbsType;
+ UINT8 *LegacyOrder;
+ UINT8 *OldData;
+ UINTN Pos;
+ UINTN Bit;
+
+ ASSERT (CallbackData != NULL);
+
+ PageIdList[0] = FORM_SET_FD_ORDER_ID;
+ PageIdList[1] = FORM_SET_HD_ORDER_ID;
+ PageIdList[2] = FORM_SET_CD_ORDER_ID;
+ PageIdList[3] = FORM_SET_NET_ORDER_ID;
+ PageIdList[4] = FORM_SET_BEV_ORDER_ID;
+ OptionMenu = NULL;
+ BbsType = 0;
+ LegacyOrder = NULL;
+ OldData = NULL;
+ DisMap = ZeroMem (CallbackData->BmmFakeNvData.DisableMap, sizeof (CallbackData->BmmFakeNvData.DisableMap));
+ PageNum = ARRAY_SIZE (PageIdList);
+ VarData = BdsLibGetVariableAndSize (
+ VAR_LEGACY_DEV_ORDER,
+ &gEfiLegacyDevOrderVariableGuid,
+ &VarSize
+ );
+
+ for (Index = 0; Index < PageNum; Index++) {
+ switch (PageIdList[Index]) {
+
+ case FORM_SET_FD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyFDMenu;
+ BbsType = BBS_FLOPPY;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyFD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyFD;
+ break;
+
+ case FORM_SET_HD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyHDMenu;
+ BbsType = BBS_HARDDISK;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyHD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyHD;
+ break;
+
+ case FORM_SET_CD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyCDMenu;
+ BbsType = BBS_CDROM;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyCD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyCD;
+ break;
+
+ case FORM_SET_NET_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyNETMenu;
+ BbsType = BBS_EMBED_NETWORK;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyNET;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyNET;
+ break;
+
+ default:
+ ASSERT (PageIdList[Index] == FORM_SET_BEV_ORDER_ID);
+ OptionMenu = (BM_MENU_OPTION *) &LegacyBEVMenu;
+ BbsType = BBS_BEV_DEVICE;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyBEV;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyBEV;
+ break;
+ }
+
+ if (NULL != VarData) {
+ WorkingVarData = VarData;
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) WorkingVarData;
+ while (WorkingVarData < VarData + VarSize) {
+ if (DevOrder->BbsType == BbsType) {
+ break;
+ }
+
+ WorkingVarData = (UINT8 *)((UINTN)WorkingVarData + sizeof (BBS_TYPE));
+ WorkingVarData += *(UINT16 *) WorkingVarData;
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) WorkingVarData;
+ }
+ for (OptionIndex = 0; OptionIndex < OptionMenu->MenuNumber; OptionIndex++) {
+ VarDevOrder = *(UINT16 *) ((UINTN) DevOrder + sizeof (BBS_TYPE) + sizeof (UINT16) + OptionIndex * sizeof (UINT16));
+ if (0xFF00 == (VarDevOrder & 0xFF00)) {
+ LegacyOrder[OptionIndex] = 0xFF;
+ Pos = (VarDevOrder & 0xFF) / 8;
+ Bit = 7 - ((VarDevOrder & 0xFF) % 8);
+ DisMap[Pos] = (UINT8) (DisMap[Pos] | (UINT8) (1 << Bit));
+ } else {
+ LegacyOrder[OptionIndex] = (UINT8) (VarDevOrder & 0xFF);
+ }
+ }
+ CopyMem (OldData, LegacyOrder, 100);
+ }
+ }
+}
+
+/**
+ Get driver option order from globalc DriverOptionMenu.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetDriverOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BMM_FAKE_NV_DATA *BmmConfig;
+ UINT16 Index;
+ UINT16 OptionOrderIndex;
+ UINTN DeviceType;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+
+ ASSERT (CallbackData != NULL);
+
+ DeviceType = (UINTN) -1;
+ BmmConfig = &CallbackData->BmmFakeNvData;
+ ZeroMem (BmmConfig->DriverOptionOrder, sizeof (BmmConfig->DriverOptionOrder));
+
+ for (Index = 0, OptionOrderIndex = 0; ((Index < DriverOptionMenu.MenuNumber) &&
+ (OptionOrderIndex < (sizeof (BmmConfig->DriverOptionOrder) / sizeof (BmmConfig->DriverOptionOrder[0]))));
+ Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewLoadContext->IsLegacy) {
+ if (((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType != DeviceType) {
+ DeviceType = ((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType;
+ } else {
+ //
+ // Only show one legacy boot option for the same device type
+ // assuming the boot options are grouped by the device type
+ //
+ continue;
+ }
+ }
+ BmmConfig->DriverOptionOrder[OptionOrderIndex++] = (UINT32) (NewMenuEntry->OptionNumber + 1);
+ }
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/ConsoleOption.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/ConsoleOption.c
new file mode 100644
index 0000000000..126feeb9ae
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/ConsoleOption.c
@@ -0,0 +1,1198 @@
+/** @file
+ handles console redirection from boot manager
+
+Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "BootMaint.h"
+
+UART_FLOW_CONTROL_DEVICE_PATH mFlowControlDevicePath =
+{
+ {
+ MESSAGING_DEVICE_PATH,
+ MSG_VENDOR_DP,
+ {
+ (UINT8)(sizeof(UART_FLOW_CONTROL_DEVICE_PATH)),
+ (UINT8)((sizeof(UART_FLOW_CONTROL_DEVICE_PATH)) >> 8)
+ }
+ },
+ DEVICE_PATH_MESSAGING_UART_FLOW_CONTROL,
+ UART_FLOW_CONTROL_HARDWARE
+};
+
+/**
+ Check the device path node whether it's the Flow Control node or not.
+
+ @param[in] FlowControl The device path node to be checked.
+
+ @retval TRUE It's the Flow Control node.
+ @retval FALSE It's not.
+
+**/
+BOOLEAN
+IsUartFlowControlNode (
+ IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl
+ )
+{
+ return (BOOLEAN) (
+ (DevicePathType (FlowControl) == MESSAGING_DEVICE_PATH) &&
+ (DevicePathSubType (FlowControl) == MSG_VENDOR_DP) &&
+ (CompareGuid (&FlowControl->Guid, &gEfiUartDevicePathGuid))
+ );
+}
+
+/**
+ Check whether the device path node is ISA Serial Node.
+
+ @param Acpi Device path node to be checked
+
+ @retval TRUE It's ISA Serial Node.
+ @retval FALSE It's NOT ISA Serial Node.
+
+**/
+BOOLEAN
+IsIsaSerialNode (
+ IN ACPI_HID_DEVICE_PATH *Acpi
+ )
+{
+ return (BOOLEAN) (
+ (DevicePathType (Acpi) == ACPI_DEVICE_PATH) &&
+ (DevicePathSubType (Acpi) == ACPI_DP) &&
+ (ReadUnaligned32 (&Acpi->HID) == EISA_PNP_ID (0x0501))
+ );
+}
+
+/**
+ Update Com Ports attributes from DevicePath
+
+ @param DevicePath DevicePath that contains Com ports
+
+ @retval EFI_SUCCESS The update is successful.
+
+**/
+EFI_STATUS
+UpdateComAttributeFromVariable (
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ );
+
+/**
+ Update the multi-instance device path of Terminal Device based on
+ the global TerminalMenu. If ChangeTernimal is TRUE, the terminal
+ device path in the Terminal Device in TerminalMenu is also updated.
+
+ @param DevicePath The multi-instance device path.
+ @param ChangeTerminal TRUE, then device path in the Terminal Device
+ in TerminalMenu is also updated; FALSE, no update.
+
+ @return EFI_SUCCESS The function completes successfully.
+
+**/
+EFI_STATUS
+ChangeTerminalDevicePath (
+ IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath,
+ IN BOOLEAN ChangeTerminal
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ EFI_DEVICE_PATH_PROTOCOL *Node1;
+ ACPI_HID_DEVICE_PATH *Acpi;
+ UART_DEVICE_PATH *Uart;
+ UART_DEVICE_PATH *Uart1;
+ UINTN Com;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UART_FLOW_CONTROL_DEVICE_PATH *FlowControlNode;
+
+ Node = *DevicePath;
+ Node = NextDevicePathNode (Node);
+ Com = 0;
+ while (!IsDevicePathEnd (Node)) {
+ Acpi = (ACPI_HID_DEVICE_PATH *) Node;
+ if (IsIsaSerialNode (Acpi)) {
+ CopyMem (&Com, &Acpi->UID, sizeof (UINT32));
+ }
+
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Com);
+
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) {
+ Uart = (UART_DEVICE_PATH *) Node;
+ CopyMem (
+ &Uart->BaudRate,
+ &NewTerminalContext->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &Uart->DataBits,
+ &NewTerminalContext->DataBits,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart->Parity,
+ &NewTerminalContext->Parity,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart->StopBits,
+ &NewTerminalContext->StopBits,
+ sizeof (UINT8)
+ );
+
+ FlowControlNode = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Node);
+ if (IsUartFlowControlNode (FlowControlNode)) {
+ FlowControlNode->FlowControlMap = NewTerminalContext->FlowControl;
+ } else {
+ //
+ // Append the Flow control device node when user enable flow control.
+ //
+ if (NewTerminalContext->FlowControl != 0) {
+ mFlowControlDevicePath.FlowControlMap = NewTerminalContext->FlowControl;
+ *DevicePath = AppendDevicePathNode (
+ *DevicePath,
+ (EFI_DEVICE_PATH_PROTOCOL *) (&mFlowControlDevicePath)
+ );
+ }
+ }
+
+ //
+ // Change the device path in the ComPort
+ //
+ if (ChangeTerminal) {
+ Node1 = NewTerminalContext->DevicePath;
+ Node1 = NextDevicePathNode (Node1);
+ while (!IsDevicePathEnd (Node1)) {
+ if ((DevicePathType (Node1) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node1) == MSG_UART_DP)) {
+ Uart1 = (UART_DEVICE_PATH *) Node1;
+ CopyMem (
+ &Uart1->BaudRate,
+ &NewTerminalContext->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &Uart1->DataBits,
+ &NewTerminalContext->DataBits,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart1->Parity,
+ &NewTerminalContext->Parity,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart1->StopBits,
+ &NewTerminalContext->StopBits,
+ sizeof (UINT8)
+ );
+ break;
+ }
+ //
+ // end if
+ //
+ Node1 = NextDevicePathNode (Node1);
+ }
+ //
+ // end while
+ //
+ break;
+ }
+ }
+
+ Node = NextDevicePathNode (Node);
+ }
+
+ return EFI_SUCCESS;
+
+}
+
+/**
+ Update the device path that describing a terminal device
+ based on the new BaudRate, Data Bits, parity and Stop Bits
+ set.
+
+ @param DevicePath terminal device's path
+
+**/
+VOID
+ChangeVariableDevicePath (
+ IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ ACPI_HID_DEVICE_PATH *Acpi;
+ UART_DEVICE_PATH *Uart;
+ UINTN Com;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ BM_MENU_ENTRY *NewMenuEntry;
+
+ Node = DevicePath;
+ Node = NextDevicePathNode (Node);
+ Com = 0;
+ while (!IsDevicePathEnd (Node)) {
+ Acpi = (ACPI_HID_DEVICE_PATH *) Node;
+ if (IsIsaSerialNode (Acpi)) {
+ CopyMem (&Com, &Acpi->UID, sizeof (UINT32));
+ }
+
+ if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) {
+ NewMenuEntry = BOpt_GetMenuEntry (
+ &TerminalMenu,
+ Com
+ );
+ ASSERT (NewMenuEntry != NULL);
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ Uart = (UART_DEVICE_PATH *) Node;
+ CopyMem (
+ &Uart->BaudRate,
+ &NewTerminalContext->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &Uart->DataBits,
+ &NewTerminalContext->DataBits,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart->Parity,
+ &NewTerminalContext->Parity,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &Uart->StopBits,
+ &NewTerminalContext->StopBits,
+ sizeof (UINT8)
+ );
+ }
+
+ Node = NextDevicePathNode (Node);
+ }
+}
+
+/**
+ Retrieve ACPI UID of UART from device path
+
+ @param Handle The handle for the UART device.
+ @param AcpiUid The ACPI UID on output.
+
+ @retval TRUE Find valid UID from device path
+ @retval FALSE Can't find
+
+**/
+BOOLEAN
+RetrieveUartUid (
+ IN EFI_HANDLE Handle,
+ IN OUT UINT32 *AcpiUid
+ )
+{
+ EFI_STATUS Status;
+ ACPI_HID_DEVICE_PATH *Acpi;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+
+ Status = gBS->HandleProtocol (
+ Handle,
+ &gEfiDevicePathProtocolGuid,
+ (VOID **) &DevicePath
+ );
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ Acpi = NULL;
+ for (; !IsDevicePathEnd (DevicePath); DevicePath = NextDevicePathNode (DevicePath)) {
+ if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_UART_DP)) {
+ break;
+ }
+ //
+ // Acpi points to the node before the Uart node
+ //
+ Acpi = (ACPI_HID_DEVICE_PATH *) DevicePath;
+ }
+
+ if ((Acpi != NULL) && IsIsaSerialNode (Acpi)) {
+ if (AcpiUid != NULL) {
+ CopyMem (AcpiUid, &Acpi->UID, sizeof (UINT32));
+ }
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Sort Uart handles array with Acpi->UID from low to high.
+
+ @param Handles EFI_SERIAL_IO_PROTOCOL handle buffer
+ @param NoHandles EFI_SERIAL_IO_PROTOCOL handle count
+**/
+VOID
+SortedUartHandle (
+ IN EFI_HANDLE *Handles,
+ IN UINTN NoHandles
+ )
+{
+ UINTN Index1;
+ UINTN Index2;
+ UINTN Position;
+ UINT32 AcpiUid1;
+ UINT32 AcpiUid2;
+ UINT32 TempAcpiUid;
+ EFI_HANDLE TempHandle;
+
+ for (Index1 = 0; Index1 < NoHandles-1; Index1++) {
+ if (!RetrieveUartUid (Handles[Index1], &AcpiUid1)) {
+ continue;
+ }
+ TempHandle = Handles[Index1];
+ Position = Index1;
+ TempAcpiUid = AcpiUid1;
+
+ for (Index2 = Index1+1; Index2 < NoHandles; Index2++) {
+ if (!RetrieveUartUid (Handles[Index2], &AcpiUid2)) {
+ continue;
+ }
+ if (AcpiUid2 < TempAcpiUid) {
+ TempAcpiUid = AcpiUid2;
+ TempHandle = Handles[Index2];
+ Position = Index2;
+ }
+ }
+ Handles[Position] = Handles[Index1];
+ Handles[Index1] = TempHandle;
+ }
+}
+
+/**
+ Test whether DevicePath is a valid Terminal
+
+
+ @param DevicePath DevicePath to be checked
+ @param Termi If DevicePath is valid Terminal, terminal type is returned.
+ @param Com If DevicePath is valid Terminal, Com Port type is returned.
+
+ @retval TRUE If DevicePath point to a Terminal.
+ @retval FALSE If DevicePath does not point to a Terminal.
+
+**/
+BOOLEAN
+IsTerminalDevicePath (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
+ OUT TYPE_OF_TERMINAL *Termi,
+ OUT UINTN *Com
+ );
+
+/**
+ Build a list containing all serial devices.
+
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_UNSUPPORTED No serial ports present.
+
+**/
+EFI_STATUS
+LocateSerialIo (
+ VOID
+ )
+{
+ UINTN Index;
+ UINTN Index2;
+ UINTN NoHandles;
+ EFI_HANDLE *Handles;
+ EFI_STATUS Status;
+ ACPI_HID_DEVICE_PATH *Acpi;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ EFI_SERIAL_IO_PROTOCOL *SerialIo;
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ EFI_DEVICE_PATH_PROTOCOL *OutDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *InpDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *ErrDevicePath;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
+ VENDOR_DEVICE_PATH Vendor;
+ UINT32 FlowControl;
+ //
+ // Get all handles that have SerialIo protocol installed
+ //
+ InitializeListHead (&TerminalMenu.Head);
+ TerminalMenu.MenuNumber = 0;
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiSerialIoProtocolGuid,
+ NULL,
+ &NoHandles,
+ &Handles
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // No serial ports present
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ //
+ // Sort Uart handles array with Acpi->UID from low to high
+ // then Terminal menu can be built from low Acpi->UID to high Acpi->UID
+ //
+ SortedUartHandle (Handles, NoHandles);
+
+ for (Index = 0; Index < NoHandles; Index++) {
+ //
+ // Check to see whether the handle has DevicePath Protocol installed
+ //
+ gBS->HandleProtocol (
+ Handles[Index],
+ &gEfiDevicePathProtocolGuid,
+ (VOID **) &DevicePath
+ );
+
+ Acpi = NULL;
+ for (Node = DevicePath; !IsDevicePathEnd (Node); Node = NextDevicePathNode (Node)) {
+ if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) {
+ break;
+ }
+ //
+ // Acpi points to the node before Uart node
+ //
+ Acpi = (ACPI_HID_DEVICE_PATH *) Node;
+ }
+
+ if ((Acpi != NULL) && IsIsaSerialNode (Acpi)) {
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_TERMINAL_CONTEXT_SELECT);
+ if (NewMenuEntry == NULL) {
+ FreePool (Handles);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ CopyMem (&NewMenuEntry->OptionNumber, &Acpi->UID, sizeof (UINT32));
+ NewTerminalContext->DevicePath = DuplicateDevicePath (DevicePath);
+ //
+ // BugBug: I have no choice, calling EfiLibStrFromDatahub will hang the system!
+ // coz' the misc data for each platform is not correct, actually it's the device path stored in
+ // datahub which is not completed, so a searching for end of device path will enter a
+ // dead-loop.
+ //
+ NewMenuEntry->DisplayString = EfiLibStrFromDatahub (DevicePath);
+ if (NULL == NewMenuEntry->DisplayString) {
+ NewMenuEntry->DisplayString = DevicePathToStr (DevicePath);
+ }
+
+ NewMenuEntry->HelpString = NULL;
+
+ gBS->HandleProtocol (
+ Handles[Index],
+ &gEfiSerialIoProtocolGuid,
+ (VOID **) &SerialIo
+ );
+
+ CopyMem (
+ &NewTerminalContext->BaudRate,
+ &SerialIo->Mode->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &NewTerminalContext->DataBits,
+ &SerialIo->Mode->DataBits,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &NewTerminalContext->Parity,
+ &SerialIo->Mode->Parity,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &NewTerminalContext->StopBits,
+ &SerialIo->Mode->StopBits,
+ sizeof (UINT8)
+ );
+
+ NewTerminalContext->FlowControl = 0;
+ SerialIo->GetControl(SerialIo, &FlowControl);
+ if ((FlowControl & EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE) != 0) {
+ NewTerminalContext->FlowControl = UART_FLOW_CONTROL_HARDWARE;
+ }
+
+ InsertTailList (&TerminalMenu.Head, &NewMenuEntry->Link);
+ TerminalMenu.MenuNumber++;
+ }
+ }
+ if (Handles != NULL) {
+ FreePool (Handles);
+ }
+
+ //
+ // Get L"ConOut", L"ConIn" and L"ErrOut" from the Var
+ //
+ OutDevicePath = EfiLibGetVariable (L"ConOut", &gEfiGlobalVariableGuid);
+ InpDevicePath = EfiLibGetVariable (L"ConIn", &gEfiGlobalVariableGuid);
+ ErrDevicePath = EfiLibGetVariable (L"ErrOut", &gEfiGlobalVariableGuid);
+ if (OutDevicePath != NULL) {
+ UpdateComAttributeFromVariable (OutDevicePath);
+ }
+
+ if (InpDevicePath != NULL) {
+ UpdateComAttributeFromVariable (InpDevicePath);
+ }
+
+ if (ErrDevicePath != NULL) {
+ UpdateComAttributeFromVariable (ErrDevicePath);
+ }
+
+ for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index);
+ if (NULL == NewMenuEntry) {
+ return EFI_NOT_FOUND;
+ }
+
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+
+ NewTerminalContext->TerminalType = 0;
+ NewTerminalContext->IsConIn = FALSE;
+ NewTerminalContext->IsConOut = FALSE;
+ NewTerminalContext->IsStdErr = FALSE;
+
+ Vendor.Header.Type = MESSAGING_DEVICE_PATH;
+ Vendor.Header.SubType = MSG_VENDOR_DP;
+
+ for (Index2 = 0; Index2 < 4; Index2++) {
+ CopyMem (&Vendor.Guid, &TerminalTypeGuid[Index2], sizeof (EFI_GUID));
+ SetDevicePathNodeLength (&Vendor.Header, sizeof (VENDOR_DEVICE_PATH));
+ NewDevicePath = AppendDevicePathNode (
+ NewTerminalContext->DevicePath,
+ (EFI_DEVICE_PATH_PROTOCOL *) &Vendor
+ );
+ if (NewMenuEntry->HelpString != NULL) {
+ FreePool (NewMenuEntry->HelpString);
+ }
+ //
+ // NewMenuEntry->HelpString = DevicePathToStr (NewDevicePath);
+ // NewMenuEntry->DisplayString = NewMenuEntry->HelpString;
+ //
+ NewMenuEntry->HelpString = NULL;
+
+ if (BdsLibMatchDevicePaths (OutDevicePath, NewDevicePath)) {
+ NewTerminalContext->IsConOut = TRUE;
+ NewTerminalContext->TerminalType = (UINT8) Index2;
+ }
+
+ if (BdsLibMatchDevicePaths (InpDevicePath, NewDevicePath)) {
+ NewTerminalContext->IsConIn = TRUE;
+ NewTerminalContext->TerminalType = (UINT8) Index2;
+ }
+
+ if (BdsLibMatchDevicePaths (ErrDevicePath, NewDevicePath)) {
+ NewTerminalContext->IsStdErr = TRUE;
+ NewTerminalContext->TerminalType = (UINT8) Index2;
+ }
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Update Com Ports attributes from DevicePath
+
+ @param DevicePath DevicePath that contains Com ports
+
+ @retval EFI_SUCCESS The update is successful.
+ @retval EFI_NOT_FOUND Can not find specific menu entry
+**/
+EFI_STATUS
+UpdateComAttributeFromVariable (
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ EFI_DEVICE_PATH_PROTOCOL *SerialNode;
+ ACPI_HID_DEVICE_PATH *Acpi;
+ UART_DEVICE_PATH *Uart;
+ UART_DEVICE_PATH *Uart1;
+ UINTN TerminalNumber;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ UINTN Index;
+ UART_FLOW_CONTROL_DEVICE_PATH *FlowControlNode;
+ BOOLEAN HasFlowControlNode;
+
+ HasFlowControlNode = FALSE;
+ Node = DevicePath;
+ Node = NextDevicePathNode (Node);
+ TerminalNumber = 0;
+ for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) {
+ while (!IsDevicePathEnd (Node)) {
+ Acpi = (ACPI_HID_DEVICE_PATH *) Node;
+ if (IsIsaSerialNode (Acpi)) {
+ CopyMem (&TerminalNumber, &Acpi->UID, sizeof (UINT32));
+ }
+
+ if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) {
+ Uart = (UART_DEVICE_PATH *) Node;
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalNumber);
+ if (NULL == NewMenuEntry) {
+ return EFI_NOT_FOUND;
+ }
+
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ CopyMem (
+ &NewTerminalContext->BaudRate,
+ &Uart->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &NewTerminalContext->DataBits,
+ &Uart->DataBits,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &NewTerminalContext->Parity,
+ &Uart->Parity,
+ sizeof (UINT8)
+ );
+
+ CopyMem (
+ &NewTerminalContext->StopBits,
+ &Uart->StopBits,
+ sizeof (UINT8)
+ );
+
+ FlowControlNode = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Node);
+ if (IsUartFlowControlNode (FlowControlNode)) {
+ HasFlowControlNode = TRUE;
+ NewTerminalContext->FlowControl = (UINT8) ReadUnaligned32 (&FlowControlNode->FlowControlMap);
+ } else if (NewTerminalContext->FlowControl != 0) {
+ //
+ // No Flow Control device path node, assumption no Flow control
+ //
+ NewTerminalContext->FlowControl = 0;
+ }
+
+ SerialNode = NewTerminalContext->DevicePath;
+ SerialNode = NextDevicePathNode (SerialNode);
+ while (!IsDevicePathEnd (SerialNode)) {
+ if ((DevicePathType (SerialNode) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (SerialNode) == MSG_UART_DP)) {
+ //
+ // Update following device paths according to
+ // previous acquired uart attributes
+ //
+ Uart1 = (UART_DEVICE_PATH *) SerialNode;
+ CopyMem (
+ &Uart1->BaudRate,
+ &NewTerminalContext->BaudRate,
+ sizeof (UINT64)
+ );
+
+ CopyMem (
+ &Uart1->DataBits,
+ &NewTerminalContext->DataBits,
+ sizeof (UINT8)
+ );
+ CopyMem (
+ &Uart1->Parity,
+ &NewTerminalContext->Parity,
+ sizeof (UINT8)
+ );
+ CopyMem (
+ &Uart1->StopBits,
+ &NewTerminalContext->StopBits,
+ sizeof (UINT8)
+ );
+
+ FlowControlNode = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (SerialNode);
+ if (IsUartFlowControlNode (FlowControlNode)) {
+ FlowControlNode->FlowControlMap = NewTerminalContext->FlowControl;
+ } else {
+ if (HasFlowControlNode) {
+ mFlowControlDevicePath.FlowControlMap = NewTerminalContext->FlowControl;
+ NewTerminalContext->DevicePath = AppendDevicePathNode (
+ NewTerminalContext->DevicePath,
+ (EFI_DEVICE_PATH_PROTOCOL *) (&mFlowControlDevicePath)
+ );
+ }
+ }
+ break;
+ }
+
+ SerialNode = NextDevicePathNode (SerialNode);
+ }
+ //
+ // end while
+ //
+ }
+
+ Node = NextDevicePathNode (Node);
+ }
+ //
+ // end while
+ //
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Build up Console Menu based on types passed in. The type can
+ be BM_CONSOLE_IN_CONTEXT_SELECT, BM_CONSOLE_OUT_CONTEXT_SELECT
+ and BM_CONSOLE_ERR_CONTEXT_SELECT.
+
+ @param ConsoleMenuType Can be BM_CONSOLE_IN_CONTEXT_SELECT, BM_CONSOLE_OUT_CONTEXT_SELECT
+ and BM_CONSOLE_ERR_CONTEXT_SELECT.
+
+ @retval EFI_UNSUPPORTED The type passed in is not in the 3 types defined.
+ @retval EFI_NOT_FOUND If the EFI Variable defined in UEFI spec with name "ConOutDev",
+ "ConInDev" or "ConErrDev" doesn't exists.
+ @retval EFI_OUT_OF_RESOURCES Not enough resource to complete the operations.
+ @retval EFI_SUCCESS Function completes successfully.
+
+**/
+EFI_STATUS
+GetConsoleMenu (
+ IN UINTN ConsoleMenuType
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *AllDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *MultiDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePathInst;
+ UINTN Size;
+ UINTN AllCount;
+ UINTN Index;
+ UINTN Index2;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+ TYPE_OF_TERMINAL Terminal;
+ UINTN Com;
+ BM_MENU_OPTION *ConsoleMenu;
+
+ DevicePath = NULL;
+ AllDevicePath = NULL;
+ AllCount = 0;
+ switch (ConsoleMenuType) {
+ case BM_CONSOLE_IN_CONTEXT_SELECT:
+ ConsoleMenu = &ConsoleInpMenu;
+ DevicePath = EfiLibGetVariable (
+ L"ConIn",
+ &gEfiGlobalVariableGuid
+ );
+
+ AllDevicePath = EfiLibGetVariable (
+ L"ConInDev",
+ &gEfiGlobalVariableGuid
+ );
+ break;
+
+ case BM_CONSOLE_OUT_CONTEXT_SELECT:
+ ConsoleMenu = &ConsoleOutMenu;
+ DevicePath = EfiLibGetVariable (
+ L"ConOut",
+ &gEfiGlobalVariableGuid
+ );
+
+ AllDevicePath = EfiLibGetVariable (
+ L"ConOutDev",
+ &gEfiGlobalVariableGuid
+ );
+ break;
+
+ case BM_CONSOLE_ERR_CONTEXT_SELECT:
+ ConsoleMenu = &ConsoleErrMenu;
+ DevicePath = EfiLibGetVariable (
+ L"ErrOut",
+ &gEfiGlobalVariableGuid
+ );
+
+ AllDevicePath = EfiLibGetVariable (
+ L"ErrOutDev",
+ &gEfiGlobalVariableGuid
+ );
+ break;
+
+ default:
+ return EFI_UNSUPPORTED;
+ }
+
+ if (NULL == AllDevicePath) {
+ return EFI_NOT_FOUND;
+ }
+
+ InitializeListHead (&ConsoleMenu->Head);
+
+ AllCount = EfiDevicePathInstanceCount (AllDevicePath);
+ ConsoleMenu->MenuNumber = 0;
+ //
+ // Following is menu building up for Console Devices selected.
+ //
+ MultiDevicePath = AllDevicePath;
+ Index2 = 0;
+ for (Index = 0; Index < AllCount; Index++) {
+ DevicePathInst = GetNextDevicePathInstance (&MultiDevicePath, &Size);
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_CONSOLE_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ NewMenuEntry->OptionNumber = Index2;
+
+ NewConsoleContext->DevicePath = DuplicateDevicePath (DevicePathInst);
+ ASSERT (NewConsoleContext->DevicePath != NULL);
+ NewMenuEntry->DisplayString = EfiLibStrFromDatahub (NewConsoleContext->DevicePath);
+ if (NULL == NewMenuEntry->DisplayString) {
+ NewMenuEntry->DisplayString = DevicePathToStr (NewConsoleContext->DevicePath);
+ }
+
+ NewConsoleContext->IsTerminal = IsTerminalDevicePath (
+ NewConsoleContext->DevicePath,
+ &Terminal,
+ &Com
+ );
+
+ NewConsoleContext->IsActive = BdsLibMatchDevicePaths (
+ DevicePath,
+ NewConsoleContext->DevicePath
+ );
+
+ if (NewConsoleContext->IsTerminal) {
+ BOpt_DestroyMenuEntry (NewMenuEntry);
+ } else {
+ Index2++;
+ ConsoleMenu->MenuNumber++;
+ InsertTailList (&ConsoleMenu->Head, &NewMenuEntry->Link);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Build up ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
+
+ @retval EFI_SUCCESS The function always complete successfully.
+
+**/
+EFI_STATUS
+GetAllConsoles (
+ VOID
+ )
+{
+ GetConsoleMenu (BM_CONSOLE_IN_CONTEXT_SELECT);
+ GetConsoleMenu (BM_CONSOLE_OUT_CONTEXT_SELECT);
+ GetConsoleMenu (BM_CONSOLE_ERR_CONTEXT_SELECT);
+ return EFI_SUCCESS;
+}
+
+/**
+ Free ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
+
+ @retval EFI_SUCCESS The function always complete successfully.
+**/
+EFI_STATUS
+FreeAllConsoles (
+ VOID
+ )
+{
+ BOpt_FreeMenu (&ConsoleOutMenu);
+ BOpt_FreeMenu (&ConsoleInpMenu);
+ BOpt_FreeMenu (&ConsoleErrMenu);
+ BOpt_FreeMenu (&TerminalMenu);
+ return EFI_SUCCESS;
+}
+
+/**
+ Test whether DevicePath is a valid Terminal
+
+
+ @param DevicePath DevicePath to be checked
+ @param Termi If DevicePath is valid Terminal, terminal type is returned.
+ @param Com If DevicePath is valid Terminal, Com Port type is returned.
+
+ @retval TRUE If DevicePath point to a Terminal.
+ @retval FALSE If DevicePath does not point to a Terminal.
+
+**/
+BOOLEAN
+IsTerminalDevicePath (
+ IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
+ OUT TYPE_OF_TERMINAL *Termi,
+ OUT UINTN *Com
+ )
+{
+ BOOLEAN IsTerminal;
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ VENDOR_DEVICE_PATH *Vendor;
+ UART_DEVICE_PATH *Uart;
+ ACPI_HID_DEVICE_PATH *Acpi;
+
+ IsTerminal = FALSE;
+
+ Uart = NULL;
+ Vendor = NULL;
+ Acpi = NULL;
+ for (Node = DevicePath; !IsDevicePathEnd (Node); Node = NextDevicePathNode (Node)) {
+ //
+ // Vendor points to the node before the End node
+ //
+ Vendor = (VENDOR_DEVICE_PATH *) Node;
+
+ if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) {
+ Uart = (UART_DEVICE_PATH *) Node;
+ }
+
+ if (Uart == NULL) {
+ //
+ // Acpi points to the node before the UART node
+ //
+ Acpi = (ACPI_HID_DEVICE_PATH *) Node;
+ }
+ }
+
+ if (Vendor == NULL ||
+ DevicePathType (Vendor) != MESSAGING_DEVICE_PATH ||
+ DevicePathSubType (Vendor) != MSG_VENDOR_DP ||
+ Uart == NULL) {
+ return FALSE;
+ }
+
+ //
+ // There are four kinds of Terminal types
+ // check to see whether this devicepath
+ // is one of that type
+ //
+ if (CompareGuid (&Vendor->Guid, &TerminalTypeGuid[0])) {
+ *Termi = TerminalTypePcAnsi;
+ IsTerminal = TRUE;
+ } else {
+ if (CompareGuid (&Vendor->Guid, &TerminalTypeGuid[1])) {
+ *Termi = TerminalTypeVt100;
+ IsTerminal = TRUE;
+ } else {
+ if (CompareGuid (&Vendor->Guid, &TerminalTypeGuid[2])) {
+ *Termi = TerminalTypeVt100Plus;
+ IsTerminal = TRUE;
+ } else {
+ if (CompareGuid (&Vendor->Guid, &TerminalTypeGuid[3])) {
+ *Termi = TerminalTypeVtUtf8;
+ IsTerminal = TRUE;
+ } else {
+ IsTerminal = FALSE;
+ }
+ }
+ }
+ }
+
+ if (!IsTerminal) {
+ return FALSE;
+ }
+
+ if ((Acpi != NULL) && IsIsaSerialNode (Acpi)) {
+ CopyMem (Com, &Acpi->UID, sizeof (UINT32));
+ } else {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/**
+ Get mode number according to column and row
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+GetConsoleOutMode (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN Col;
+ UINTN Row;
+ UINTN CurrentCol;
+ UINTN CurrentRow;
+ UINTN Mode;
+ UINTN MaxMode;
+ EFI_STATUS Status;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut;
+
+ ConOut = gST->ConOut;
+ MaxMode = (UINTN) (ConOut->Mode->MaxMode);
+
+ CurrentCol = PcdGet32 (PcdSetupConOutColumn);
+ CurrentRow = PcdGet32 (PcdSetupConOutRow);
+ for (Mode = 0; Mode < MaxMode; Mode++) {
+ Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row);
+ if (!EFI_ERROR(Status)) {
+ if (CurrentCol == Col && CurrentRow == Row) {
+ CallbackData->BmmFakeNvData.ConsoleOutMode = (UINT16) Mode;
+ break;
+ }
+ }
+ }
+}
+
+/**
+
+ Initialize console input device check box to ConsoleInCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleInCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINT16 Index;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT8 *ConInCheck;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+
+ ASSERT (CallbackData != NULL);
+
+ ConInCheck = &CallbackData->BmmFakeNvData.ConsoleInCheck[0];
+ for (Index = 0; ((Index < ConsoleInpMenu.MenuNumber) && \
+ (Index < MAX_MENU_NUMBER)) ; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleInpMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ConInCheck[Index] = NewConsoleContext->IsActive;
+ }
+}
+
+/**
+
+ Initialize console output device check box to ConsoleOutCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleOutCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINT16 Index;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT8 *ConOutCheck;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+
+ ASSERT (CallbackData != NULL);
+ ConOutCheck = &CallbackData->BmmFakeNvData.ConsoleOutCheck[0];
+ for (Index = 0; ((Index < ConsoleOutMenu.MenuNumber) && \
+ (Index < MAX_MENU_NUMBER)) ; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleOutMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ConOutCheck[Index] = NewConsoleContext->IsActive;
+ }
+}
+
+/**
+
+ Initialize standard error output device check box to ConsoleErrCheck[MAX_MENU_NUMBER]
+ in BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetConsoleErrCheck (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINT16 Index;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT8 *ConErrCheck;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+
+ ASSERT (CallbackData != NULL);
+ ConErrCheck = &CallbackData->BmmFakeNvData.ConsoleErrCheck[0];
+ for (Index = 0; ((Index < ConsoleErrMenu.MenuNumber) && \
+ (Index < MAX_MENU_NUMBER)) ; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&ConsoleErrMenu, Index);
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ ConErrCheck[Index] = NewConsoleContext->IsActive;
+ }
+}
+
+/**
+
+ Initialize terminal attributes (baudrate, data rate, stop bits, parity and terminal type)
+ to BMM_FAKE_NV_DATA structure.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+GetTerminalAttribute (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BMM_FAKE_NV_DATA *CurrentFakeNVMap;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ UINT16 TerminalIndex;
+ UINT8 AttributeIndex;
+
+ ASSERT (CallbackData != NULL);
+
+ CurrentFakeNVMap = &CallbackData->BmmFakeNvData;
+ for (TerminalIndex = 0; ((TerminalIndex < TerminalMenu.MenuNumber) && \
+ (TerminalIndex < MAX_MENU_NUMBER)); TerminalIndex++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalIndex);
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ for (AttributeIndex = 0; AttributeIndex < sizeof (BaudRateList) / sizeof (BaudRateList [0]); AttributeIndex++) {
+ if (NewTerminalContext->BaudRate == (UINT64) (BaudRateList[AttributeIndex].Value)) {
+ NewTerminalContext->BaudRateIndex = AttributeIndex;
+ break;
+ }
+ }
+ for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (DataBitsList); AttributeIndex++) {
+ if (NewTerminalContext->DataBits == (UINT64) (DataBitsList[AttributeIndex].Value)) {
+ NewTerminalContext->DataBitsIndex = AttributeIndex;
+ break;
+ }
+ }
+
+ for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (ParityList); AttributeIndex++) {
+ if (NewTerminalContext->Parity == (UINT64) (ParityList[AttributeIndex].Value)) {
+ NewTerminalContext->ParityIndex = AttributeIndex;
+ break;
+ }
+ }
+
+ for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (StopBitsList); AttributeIndex++) {
+ if (NewTerminalContext->StopBits == (UINT64) (StopBitsList[AttributeIndex].Value)) {
+ NewTerminalContext->StopBitsIndex = AttributeIndex;
+ break;
+ }
+ }
+ CurrentFakeNVMap->COMBaudRate[TerminalIndex] = NewTerminalContext->BaudRateIndex;
+ CurrentFakeNVMap->COMDataRate[TerminalIndex] = NewTerminalContext->DataBitsIndex;
+ CurrentFakeNVMap->COMStopBits[TerminalIndex] = NewTerminalContext->StopBitsIndex;
+ CurrentFakeNVMap->COMParity[TerminalIndex] = NewTerminalContext->ParityIndex;
+ CurrentFakeNVMap->COMTerminalType[TerminalIndex] = NewTerminalContext->TerminalType;
+ CurrentFakeNVMap->COMFlowControl[TerminalIndex] = NewTerminalContext->FlowControl;
+ }
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Data.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Data.c
new file mode 100644
index 0000000000..0a3ffbcc30
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Data.c
@@ -0,0 +1,332 @@
+/** @file
+ Define some data used for Boot Maint
+
+Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "BootMaint.h"
+
+VOID *mStartOpCodeHandle = NULL;
+VOID *mEndOpCodeHandle = NULL;
+EFI_IFR_GUID_LABEL *mStartLabel = NULL;
+EFI_IFR_GUID_LABEL *mEndLabel = NULL;
+
+STRING_DEPOSITORY *FileOptionStrDepository;
+STRING_DEPOSITORY *ConsoleOptionStrDepository;
+STRING_DEPOSITORY *BootOptionStrDepository;
+STRING_DEPOSITORY *BootOptionHelpStrDepository;
+STRING_DEPOSITORY *DriverOptionStrDepository;
+STRING_DEPOSITORY *DriverOptionHelpStrDepository;
+STRING_DEPOSITORY *TerminalStrDepository;
+
+///
+/// Terminal type string token storage
+///
+UINT16 TerminalType[] = {
+ STRING_TOKEN(STR_COM_TYPE_0),
+ STRING_TOKEN(STR_COM_TYPE_1),
+ STRING_TOKEN(STR_COM_TYPE_2),
+ STRING_TOKEN(STR_COM_TYPE_3),
+};
+
+///
+/// Flow Control type string token storage
+///
+UINT16 mFlowControlType[2] = {
+ STRING_TOKEN(STR_NONE_FLOW_CONTROL),
+ STRING_TOKEN(STR_HARDWARE_FLOW_CONTROL)
+};
+
+UINT32 mFlowControlValue[2] = {
+ 0,
+ UART_FLOW_CONTROL_HARDWARE
+};
+
+///
+/// File system selection menu
+///
+BM_MENU_OPTION FsOptionMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Console Input Device Selection Menu
+///
+BM_MENU_OPTION ConsoleInpMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Console Output Device Selection Menu
+///
+BM_MENU_OPTION ConsoleOutMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Error Output Device Selection Menu
+///
+BM_MENU_OPTION ConsoleErrMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Boot Option from variable Menu
+///
+BM_MENU_OPTION BootOptionMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Driver Option from variable menu
+///
+BM_MENU_OPTION DriverOptionMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Legacy FD Info from LegacyBios.GetBbsInfo()
+///
+BM_MENU_OPTION LegacyFDMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Legacy HD Info from LegacyBios.GetBbsInfo()
+///
+BM_MENU_OPTION LegacyHDMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Legacy CD Info from LegacyBios.GetBbsInfo()
+///
+BM_MENU_OPTION LegacyCDMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Legacy NET Info from LegacyBios.GetBbsInfo()
+///
+BM_MENU_OPTION LegacyNETMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Legacy NET Info from LegacyBios.GetBbsInfo()
+///
+BM_MENU_OPTION LegacyBEVMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Files and sub-directories in current directory menu
+///
+BM_MENU_OPTION DirectoryMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Handles in current system selection menu
+///
+BM_MENU_OPTION DriverMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+BM_MENU_OPTION TerminalMenu = {
+ BM_MENU_OPTION_SIGNATURE,
+ {NULL},
+ 0
+};
+
+///
+/// Value and string token correspondency for BaudRate
+///
+COM_ATTR BaudRateList[19] = {
+ {
+ 115200,
+ STRING_TOKEN(STR_COM_BAUD_RATE_0)
+ },
+ {
+ 57600,
+ STRING_TOKEN(STR_COM_BAUD_RATE_1)
+ },
+ {
+ 38400,
+ STRING_TOKEN(STR_COM_BAUD_RATE_2)
+ },
+ {
+ 19200,
+ STRING_TOKEN(STR_COM_BAUD_RATE_3)
+ },
+ {
+ 9600,
+ STRING_TOKEN(STR_COM_BAUD_RATE_4)
+ },
+ {
+ 7200,
+ STRING_TOKEN(STR_COM_BAUD_RATE_5)
+ },
+ {
+ 4800,
+ STRING_TOKEN(STR_COM_BAUD_RATE_6)
+ },
+ {
+ 3600,
+ STRING_TOKEN(STR_COM_BAUD_RATE_7)
+ },
+ {
+ 2400,
+ STRING_TOKEN(STR_COM_BAUD_RATE_8)
+ },
+ {
+ 2000,
+ STRING_TOKEN(STR_COM_BAUD_RATE_9)
+ },
+ {
+ 1800,
+ STRING_TOKEN(STR_COM_BAUD_RATE_10)
+ },
+ {
+ 1200,
+ STRING_TOKEN(STR_COM_BAUD_RATE_11)
+ },
+ {
+ 600,
+ STRING_TOKEN(STR_COM_BAUD_RATE_12)
+ },
+ {
+ 300,
+ STRING_TOKEN(STR_COM_BAUD_RATE_13)
+ },
+ {
+ 150,
+ STRING_TOKEN(STR_COM_BAUD_RATE_14)
+ },
+ {
+ 134,
+ STRING_TOKEN(STR_COM_BAUD_RATE_15)
+ },
+ {
+ 110,
+ STRING_TOKEN(STR_COM_BAUD_RATE_16)
+ },
+ {
+ 75,
+ STRING_TOKEN(STR_COM_BAUD_RATE_17)
+ },
+ {
+ 50,
+ STRING_TOKEN(STR_COM_BAUD_RATE_18)
+ }
+};
+
+///
+/// Value and string token correspondency for DataBits
+///
+COM_ATTR DataBitsList[4] = {
+ {
+ 5,
+ STRING_TOKEN(STR_COM_DATA_BITS_0)
+ },
+ {
+ 6,
+ STRING_TOKEN(STR_COM_DATA_BITS_1)
+ },
+ {
+ 7,
+ STRING_TOKEN(STR_COM_DATA_BITS_2)
+ },
+ {
+ 8,
+ STRING_TOKEN(STR_COM_DATA_BITS_3)
+ }
+};
+
+///
+/// Value and string token correspondency for Parity
+///
+COM_ATTR ParityList[5] = {
+ {
+ NoParity,
+ STRING_TOKEN(STR_COM_PAR_0)
+ },
+ {
+ EvenParity,
+ STRING_TOKEN(STR_COM_PAR_1)
+ },
+ {
+ OddParity,
+ STRING_TOKEN(STR_COM_PAR_2)
+ },
+ {
+ MarkParity,
+ STRING_TOKEN(STR_COM_PAR_3)
+ },
+ {
+ SpaceParity,
+ STRING_TOKEN(STR_COM_PAR_4)
+ }
+};
+
+///
+/// Value and string token correspondency for Baudreate
+///
+COM_ATTR StopBitsList[3] = {
+ {
+ OneStopBit,
+ STRING_TOKEN(STR_COM_STOP_BITS_0)
+ },
+ {
+ OneFiveStopBits,
+ STRING_TOKEN(STR_COM_STOP_BITS_1)
+ },
+ {
+ TwoStopBits,
+ STRING_TOKEN(STR_COM_STOP_BITS_2)
+ }
+};
+
+///
+/// Guid for messaging path, used in Serial port setting.
+///
+EFI_GUID TerminalTypeGuid[4] = {
+ DEVICE_PATH_MESSAGING_PC_ANSI,
+ DEVICE_PATH_MESSAGING_VT_100,
+ DEVICE_PATH_MESSAGING_VT_100_PLUS,
+ DEVICE_PATH_MESSAGING_VT_UTF8
+};
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FE.vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FE.vfr
new file mode 100644
index 0000000000..056694ebef
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FE.vfr
@@ -0,0 +1,127 @@
+///** @file
+//
+// File Explorer Formset
+//
+// Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+#include "FormGuid.h"
+
+formset
+ guid = FILE_EXPLORE_FORMSET_GUID,
+ title = STRING_TOKEN(STR_FILE_EXPLORER_TITLE),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ classguid = FILE_EXPLORE_FORMSET_GUID,
+
+ varstore FILE_EXPLORER_NV_DATA,
+ varid = VARSTORE_ID_BOOT_MAINT,
+ name = FeData,
+ guid = FILE_EXPLORE_FORMSET_GUID;
+
+ form formid = FORM_FILE_EXPLORER_ID,
+ title = STRING_TOKEN(STR_FILE_EXPLORER_TITLE);
+
+ label FORM_FILE_EXPLORER_ID;
+ label LABEL_END;
+ endform;
+
+ form formid = FORM_BOOT_ADD_DESCRIPTION_ID,
+ title = STRING_TOKEN(STR_FORM_BOOT_ADD_DESC_TITLE);
+
+ label FORM_BOOT_ADD_DESCRIPTION_ID;
+ label LABEL_END;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ string varid = FeData.BootDescriptionData,
+ questionid = KEY_VALUE_BOOT_DESCRIPTION,
+ prompt = STRING_TOKEN(STR_LOAD_OPTION_DESC),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ flags = INTERACTIVE,
+ minsize = 6,
+ maxsize = 75,
+ endstring;
+
+ string varid = FeData.BootOptionalData,
+ questionid = KEY_VALUE_BOOT_OPTION,
+ prompt = STRING_TOKEN(STR_OPTIONAL_DATA),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ flags = INTERACTIVE,
+ minsize = 0,
+ maxsize = 120,
+ endstring;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ text
+ help = STRING_TOKEN(STR_SAVE_AND_EXIT),
+ text = STRING_TOKEN(STR_SAVE_AND_EXIT),
+ flags = INTERACTIVE,
+ key = KEY_VALUE_SAVE_AND_EXIT_BOOT;
+
+ text
+ help = STRING_TOKEN(STR_NO_SAVE_AND_EXIT),
+ text = STRING_TOKEN(STR_NO_SAVE_AND_EXIT),
+ flags = INTERACTIVE,
+ key = KEY_VALUE_NO_SAVE_AND_EXIT_BOOT;
+
+ endform;
+
+ form formid = FORM_DRIVER_ADD_FILE_DESCRIPTION_ID,
+ title = STRING_TOKEN(STR_FORM_DRV_ADD_DESC_TITLE);
+
+ label FORM_DRIVER_ADD_FILE_DESCRIPTION_ID;
+ label LABEL_END;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ string varid = FeData.DriverDescriptionData,
+ questionid = KEY_VALUE_DRIVER_DESCRIPTION,
+ prompt = STRING_TOKEN(STR_LOAD_OPTION_DESC),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ flags = INTERACTIVE,
+ minsize = 6,
+ maxsize = 75,
+ endstring;
+
+ string varid = FeData.DriverOptionalData,
+ questionid = KEY_VALUE_DRIVER_OPTION,
+ prompt = STRING_TOKEN(STR_OPTIONAL_DATA),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ flags = INTERACTIVE,
+ minsize = 0,
+ maxsize = 120,
+ endstring;
+
+ checkbox varid = FeData.ForceReconnect,
+ prompt = STRING_TOKEN(STR_LOAD_OPTION_FORCE_RECON),
+ help = STRING_TOKEN(STR_LOAD_OPTION_FORCE_RECON),
+ flags = CHECKBOX_DEFAULT,
+ key = 0,
+ endcheckbox;
+
+ subtitle text = STRING_TOKEN(STR_NULL_STRING);
+
+ text
+ help = STRING_TOKEN(STR_SAVE_AND_EXIT),
+ text = STRING_TOKEN(STR_SAVE_AND_EXIT),
+ flags = INTERACTIVE,
+ key = KEY_VALUE_SAVE_AND_EXIT_DRIVER; //BUGBUB: allow duplicate key in one formset???
+
+ text
+ help = STRING_TOKEN(STR_NO_SAVE_AND_EXIT),
+ text = STRING_TOKEN(STR_NO_SAVE_AND_EXIT),
+ flags = INTERACTIVE,
+ key = KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER;
+
+ endform;
+
+endformset; \ No newline at end of file
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FileExplorer.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FileExplorer.c
new file mode 100644
index 0000000000..910edf6b8d
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FileExplorer.c
@@ -0,0 +1,469 @@
+/** @file
+ File explorer related functions.
+
+Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "BootMaint.h"
+
+/**
+ Update the File Explore page.
+
+ @param CallbackData The BMM context data.
+ @param MenuOption Pointer to menu options to display.
+
+**/
+VOID
+UpdateFileExplorePage (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ BM_MENU_OPTION *MenuOption
+ )
+{
+ UINTN Index;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_FILE_CONTEXT *NewFileContext;
+ EFI_FORM_ID FormId;
+
+ NewMenuEntry = NULL;
+ NewFileContext = NULL;
+ FormId = 0;
+
+ RefreshUpdateData ();
+ mStartLabel->Number = FORM_FILE_EXPLORER_ID;
+
+ for (Index = 0; Index < MenuOption->MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (MenuOption, Index);
+ NewFileContext = (BM_FILE_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewFileContext->IsBootLegacy) {
+ continue;
+ }
+
+ if ((NewFileContext->IsDir) || (FileExplorerStateBootFromFile == CallbackData->FeCurrentState)) {
+ //
+ // Create Text opcode for directory, also create Text opcode for file in FileExplorerStateBootFromFile.
+ //
+ HiiCreateActionOpCode (
+ mStartOpCodeHandle,
+ (UINT16) (FILE_OPTION_OFFSET + Index),
+ NewMenuEntry->DisplayStringToken,
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+ } else {
+ //
+ // Create Goto opcode for file in FileExplorerStateAddBootOption or FileExplorerStateAddDriverOptionState.
+ //
+ if (FileExplorerStateAddBootOption == CallbackData->FeCurrentState) {
+ FormId = FORM_BOOT_ADD_DESCRIPTION_ID;
+ } else if (FileExplorerStateAddDriverOptionState == CallbackData->FeCurrentState) {
+ FormId = FORM_DRIVER_ADD_FILE_DESCRIPTION_ID;
+ }
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FormId,
+ NewMenuEntry->DisplayStringToken,
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ (UINT16) (FILE_OPTION_GOTO_OFFSET + Index)
+ );
+ }
+ }
+
+ HiiUpdateForm (
+ CallbackData->FeHiiHandle,
+ &gFileExploreFormSetGuid,
+ FORM_FILE_EXPLORER_ID,
+ mStartOpCodeHandle, // Label FORM_FILE_EXPLORER_ID
+ mEndOpCodeHandle // LABEL_END
+ );
+}
+
+/**
+ Update the file explower page with the refershed file system.
+
+
+ @param CallbackData BMM context data
+ @param KeyValue Key value to identify the type of data to expect.
+
+ @retval TRUE Inform the caller to create a callback packet to exit file explorer.
+ @retval FALSE Indicate that there is no need to exit file explorer.
+
+**/
+BOOLEAN
+UpdateFileExplorer (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN UINT16 KeyValue
+ )
+{
+ UINT16 FileOptionMask;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_FILE_CONTEXT *NewFileContext;
+ EFI_FORM_ID FormId;
+ BOOLEAN ExitFileExplorer;
+ EFI_STATUS Status;
+
+ NewMenuEntry = NULL;
+ NewFileContext = NULL;
+ ExitFileExplorer = FALSE;
+
+ FileOptionMask = (UINT16) (FILE_OPTION_MASK & KeyValue);
+
+ if (FileExplorerDisplayUnknown == CallbackData->FeDisplayContext) {
+ //
+ // First in, display file system.
+ //
+ BOpt_FreeMenu (&FsOptionMenu);
+ BOpt_FindFileSystem (CallbackData);
+ CreateMenuStringToken (CallbackData, CallbackData->FeHiiHandle, &FsOptionMenu);
+
+ UpdateFileExplorePage (CallbackData, &FsOptionMenu);
+
+ CallbackData->FeDisplayContext = FileExplorerDisplayFileSystem;
+ } else {
+ if (FileExplorerDisplayFileSystem == CallbackData->FeDisplayContext) {
+ NewMenuEntry = BOpt_GetMenuEntry (&FsOptionMenu, FileOptionMask);
+ } else if (FileExplorerDisplayDirectory == CallbackData->FeDisplayContext) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DirectoryMenu, FileOptionMask);
+ }
+
+ NewFileContext = (BM_FILE_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewFileContext->IsDir ) {
+ CallbackData->FeDisplayContext = FileExplorerDisplayDirectory;
+
+ RemoveEntryList (&NewMenuEntry->Link);
+ BOpt_FreeMenu (&DirectoryMenu);
+ Status = BOpt_FindFiles (CallbackData, NewMenuEntry);
+ if (EFI_ERROR (Status)) {
+ ExitFileExplorer = TRUE;
+ goto exit;
+ }
+ CreateMenuStringToken (CallbackData, CallbackData->FeHiiHandle, &DirectoryMenu);
+ BOpt_DestroyMenuEntry (NewMenuEntry);
+
+ UpdateFileExplorePage (CallbackData, &DirectoryMenu);
+
+ } else {
+ switch (CallbackData->FeCurrentState) {
+ case FileExplorerStateBootFromFile:
+ //
+ // Restore to original mode before launching boot option.
+ //
+ BdsSetConsoleMode (FALSE);
+
+ //
+ // Here boot from file
+ //
+ BootThisFile (NewFileContext);
+ //
+ // Set proper video resolution and text mode for setup.
+ //
+ BdsSetConsoleMode (TRUE);
+ ExitFileExplorer = TRUE;
+ break;
+
+ case FileExplorerStateAddBootOption:
+ case FileExplorerStateAddDriverOptionState:
+ if (FileExplorerStateAddBootOption == CallbackData->FeCurrentState) {
+ FormId = FORM_BOOT_ADD_DESCRIPTION_ID;
+ if (!CallbackData->FeFakeNvData.BootOptionChanged) {
+ ZeroMem (CallbackData->FeFakeNvData.BootOptionalData, sizeof (CallbackData->FeFakeNvData.BootOptionalData));
+ ZeroMem (CallbackData->FeFakeNvData.BootDescriptionData, sizeof (CallbackData->FeFakeNvData.BootDescriptionData));
+ }
+ } else {
+ FormId = FORM_DRIVER_ADD_FILE_DESCRIPTION_ID;
+ if (!CallbackData->FeFakeNvData.DriverOptionChanged) {
+ ZeroMem (CallbackData->FeFakeNvData.DriverOptionalData, sizeof (CallbackData->FeFakeNvData.DriverOptionalData));
+ ZeroMem (CallbackData->FeFakeNvData.DriverDescriptionData, sizeof (CallbackData->FeFakeNvData.DriverDescriptionData));
+ }
+ }
+
+ CallbackData->MenuEntry = NewMenuEntry;
+ CallbackData->LoadContext->FilePathList = ((BM_FILE_CONTEXT *) (CallbackData->MenuEntry->VariableContext))->DevicePath;
+
+ //
+ // Create Subtitle op-code for the display string of the option.
+ //
+ RefreshUpdateData ();
+ mStartLabel->Number = FormId;
+
+ HiiCreateSubTitleOpCode (
+ mStartOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ 0,
+ 0,
+ 0
+ );
+
+ HiiUpdateForm (
+ CallbackData->FeHiiHandle,
+ &gFileExploreFormSetGuid,
+ FormId,
+ mStartOpCodeHandle, // Label FormId
+ mEndOpCodeHandle // LABEL_END
+ );
+ break;
+
+ default:
+ break;
+ }
+ }
+ }
+ exit:
+ return ExitFileExplorer;
+}
+
+/**
+ This function applies changes in a driver's configuration.
+ Input is a Configuration, which has the routing data for this
+ driver followed by name / value configuration pairs. The driver
+ must apply those pairs to its configurable storage. If the
+ driver's configuration is stored in a linear block of data
+ and the driver's name / value pairs are in <BlockConfig>
+ format, it may use the ConfigToBlock helper function (above) to
+ simplify the job. Currently not implemented.
+
+ @param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param[in] Configuration A null-terminated Unicode string in
+ <ConfigString> format.
+ @param[out] Progress A pointer to a string filled in with the
+ offset of the most recent '&' before the
+ first failing name / value pair (or the
+ beginn ing of the string if the failure
+ is in the first name / value pair) or
+ the terminating NULL if all was
+ successful.
+
+ @retval EFI_SUCCESS The results have been distributed or are
+ awaiting distribution.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the
+ parts of the results that must be
+ stored awaiting possible future
+ protocols.
+ @retval EFI_INVALID_PARAMETERS Passing in a NULL for the
+ Results parameter would result
+ in this type of error.
+ @retval EFI_NOT_FOUND Target for the specified routing data
+ was not found.
+**/
+EFI_STATUS
+EFIAPI
+FileExplorerRouteConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Configuration,
+ OUT EFI_STRING *Progress
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting;
+ FILE_EXPLORER_NV_DATA *FeData;
+ BMM_CALLBACK_DATA *Private;
+
+ if (Progress == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ *Progress = Configuration;
+
+ if (Configuration == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Check routing data in <ConfigHdr>.
+ // Note: there is no name for Name/Value storage, only GUID will be checked
+ //
+ if (!HiiIsConfigHdrMatch (Configuration, &gFileExploreFormSetGuid, mFileExplorerStorageName)) {
+ return EFI_NOT_FOUND;
+ }
+
+ Status = gBS->LocateProtocol (
+ &gEfiHiiConfigRoutingProtocolGuid,
+ NULL,
+ (VOID**) &ConfigRouting
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Private = FE_CALLBACK_DATA_FROM_THIS (This);
+ //
+ // Get Buffer Storage data from EFI variable
+ //
+ BufferSize = sizeof (FILE_EXPLORER_NV_DATA );
+ FeData = &Private->FeFakeNvData;
+
+ //
+ // Convert <ConfigResp> to buffer data by helper function ConfigToBlock()
+ //
+ Status = ConfigRouting->ConfigToBlock (
+ ConfigRouting,
+ Configuration,
+ (UINT8 *) FeData,
+ &BufferSize,
+ Progress
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ if (FeData->BootDescriptionData[0] != 0x00 || FeData->BootOptionalData[0] != 0x00) {
+ Status = Var_UpdateBootOption (Private, FeData);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ BOpt_GetBootOptions (Private);
+ CreateMenuStringToken (Private, Private->FeHiiHandle, &BootOptionMenu);
+ }
+
+ if (FeData->DriverDescriptionData[0] != 0x00 || FeData->DriverOptionalData[0] != 0x00) {
+ Status = Var_UpdateDriverOption (
+ Private,
+ Private->FeHiiHandle,
+ FeData->DriverDescriptionData,
+ FeData->DriverOptionalData,
+ FeData->ForceReconnect
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ BOpt_GetDriverOptions (Private);
+ CreateMenuStringToken (Private, Private->FeHiiHandle, &DriverOptionMenu);
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function processes the results of changes in configuration.
+ When user select a interactive opcode, this callback will be triggered.
+ Based on the Question(QuestionId) that triggers the callback, the corresponding
+ actions is performed. It handles:
+
+ 1) the addition of boot option.
+ 2) the addition of driver option.
+ 3) exit from file browser
+ 4) update of file content if a dir is selected.
+ 5) boot the file if a file is selected in "boot from file"
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be saved.
+ @retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
+ @retval EFI_INVALID_PARAMETER If parameter Value or ActionRequest is NULL.
+**/
+EFI_STATUS
+EFIAPI
+FileExplorerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ BMM_CALLBACK_DATA *Private;
+ FILE_EXPLORER_NV_DATA *NvRamMap;
+ EFI_STATUS Status;
+
+ if (Action != EFI_BROWSER_ACTION_CHANGING && Action != EFI_BROWSER_ACTION_CHANGED) {
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ Status = EFI_SUCCESS;
+ Private = FE_CALLBACK_DATA_FROM_THIS (This);
+
+ //
+ // Retrieve uncommitted data from Form Browser
+ //
+ NvRamMap = &Private->FeFakeNvData;
+ HiiGetBrowserData (&gFileExploreFormSetGuid, mFileExplorerStorageName, sizeof (FILE_EXPLORER_NV_DATA), (UINT8 *) NvRamMap);
+
+ if (Action == EFI_BROWSER_ACTION_CHANGED) {
+ if ((Value == NULL) || (ActionRequest == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (QuestionId == KEY_VALUE_SAVE_AND_EXIT_BOOT) {
+ NvRamMap->BootOptionChanged = FALSE;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
+ } else if (QuestionId == KEY_VALUE_SAVE_AND_EXIT_DRIVER) {
+ NvRamMap->DriverOptionChanged = FALSE;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
+ } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER) {
+ //
+ // Discard changes and exit formset
+ //
+ NvRamMap->DriverOptionalData[0] = 0x0000;
+ NvRamMap->DriverDescriptionData[0] = 0x0000;
+ NvRamMap->DriverOptionChanged = FALSE;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT_BOOT) {
+ //
+ // Discard changes and exit formset
+ //
+ NvRamMap->BootOptionalData[0] = 0x0000;
+ NvRamMap->BootDescriptionData[0] = 0x0000;
+ NvRamMap->BootOptionChanged = FALSE;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ } else if (QuestionId == KEY_VALUE_BOOT_DESCRIPTION || QuestionId == KEY_VALUE_BOOT_OPTION) {
+ NvRamMap->BootOptionChanged = TRUE;
+ } else if (QuestionId == KEY_VALUE_DRIVER_DESCRIPTION || QuestionId == KEY_VALUE_DRIVER_OPTION) {
+ NvRamMap->DriverOptionChanged = TRUE;
+ } else if (QuestionId < FILE_OPTION_OFFSET) {
+ //
+ // Exit File Explorer formset
+ //
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ } else if (QuestionId >= FILE_OPTION_OFFSET && QuestionId < FILE_OPTION_GOTO_OFFSET) {
+ //
+ // Update forms may return TRUE or FALSE, need to check here.
+ //
+ if (UpdateFileExplorer (Private, QuestionId)) {
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ }
+ }
+ } else if (Action == EFI_BROWSER_ACTION_CHANGING) {
+ if (Value == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (QuestionId >= FILE_OPTION_GOTO_OFFSET) {
+ //
+ // function will always return FALSE, no need to check here.
+ //
+ UpdateFileExplorer (Private, QuestionId);
+ }
+ }
+
+ //
+ // Pass changed uncommitted data back to Form Browser
+ //
+ HiiSetBrowserData (&gFileExploreFormSetGuid, mFileExplorerStorageName, sizeof (FILE_EXPLORER_NV_DATA), (UINT8 *) NvRamMap, NULL);
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FormGuid.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FormGuid.h
new file mode 100644
index 0000000000..bf99999760
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/FormGuid.h
@@ -0,0 +1,243 @@
+/** @file
+ Formset guids, form id and VarStore data structure for Boot Maintenance Manager.
+
+Copyright (c) 2004 - 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 _FORM_GUID_H_
+#define _FORM_GUID_H_
+
+#include <Guid/BdsHii.h>
+
+#define FORM_MAIN_ID 0x1001
+#define FORM_BOOT_ADD_ID 0x1002
+#define FORM_BOOT_DEL_ID 0x1003
+#define FORM_BOOT_CHG_ID 0x1004
+#define FORM_DRV_ADD_ID 0x1005
+#define FORM_DRV_DEL_ID 0x1006
+#define FORM_DRV_CHG_ID 0x1007
+#define FORM_CON_MAIN_ID 0x1008
+#define FORM_CON_IN_ID 0x1009
+#define FORM_CON_OUT_ID 0x100A
+#define FORM_CON_ERR_ID 0x100B
+#define FORM_FILE_SEEK_ID 0x100C
+#define FORM_FILE_NEW_SEEK_ID 0x100D
+#define FORM_DRV_ADD_FILE_ID 0x100E
+#define FORM_DRV_ADD_HANDLE_ID 0x100F
+#define FORM_DRV_ADD_HANDLE_DESC_ID 0x1010
+#define FORM_BOOT_NEXT_ID 0x1011
+#define FORM_TIME_OUT_ID 0x1012
+#define FORM_RESET 0x1013
+#define FORM_BOOT_SETUP_ID 0x1014
+#define FORM_DRIVER_SETUP_ID 0x1015
+#define FORM_BOOT_LEGACY_DEVICE_ID 0x1016
+#define FORM_CON_COM_ID 0x1017
+#define FORM_CON_COM_SETUP_ID 0x1018
+#define FORM_SET_FD_ORDER_ID 0x1019
+#define FORM_SET_HD_ORDER_ID 0x101A
+#define FORM_SET_CD_ORDER_ID 0x101B
+#define FORM_SET_NET_ORDER_ID 0x101C
+#define FORM_SET_BEV_ORDER_ID 0x101D
+#define FORM_FILE_EXPLORER_ID 0x101E
+#define FORM_BOOT_ADD_DESCRIPTION_ID 0x101F
+#define FORM_DRIVER_ADD_FILE_DESCRIPTION_ID 0x1020
+#define FORM_CON_MODE_ID 0x1021
+#define FORM_BOOT_FROM_FILE_ID 0x1022
+
+#define MAXIMUM_FORM_ID 0x10FF
+
+#define KEY_VALUE_COM_SET_BAUD_RATE 0x1101
+#define KEY_VALUE_COM_SET_DATA_BITS 0x1102
+#define KEY_VALUE_COM_SET_STOP_BITS 0x1103
+#define KEY_VALUE_COM_SET_PARITY 0x1104
+#define KEY_VALUE_COM_SET_TERMI_TYPE 0x1105
+#define KEY_VALUE_MAIN_BOOT_NEXT 0x1106
+#define KEY_VALUE_BOOT_ADD_DESC_DATA 0x1107
+#define KEY_VALUE_BOOT_ADD_OPT_DATA 0x1108
+#define KEY_VALUE_DRIVER_ADD_DESC_DATA 0x1109
+#define KEY_VALUE_DRIVER_ADD_OPT_DATA 0x110A
+#define KEY_VALUE_SAVE_AND_EXIT 0x110B
+#define KEY_VALUE_NO_SAVE_AND_EXIT 0x110C
+#define KEY_VALUE_BOOT_FROM_FILE 0x110D
+#define KEY_VALUE_BOOT_DESCRIPTION 0x110E
+#define KEY_VALUE_BOOT_OPTION 0x110F
+#define KEY_VALUE_DRIVER_DESCRIPTION 0x1110
+#define KEY_VALUE_DRIVER_OPTION 0x1111
+
+#define MAXIMUM_NORMAL_KEY_VALUE 0x11FF
+
+//
+// Varstore ID defined for Buffer Storage
+//
+#define VARSTORE_ID_BOOT_MAINT 0x1000
+#define VARSTORE_ID_FILE_EXPLORER 0x1001
+
+//
+// End Label
+//
+#define LABEL_END 0xffff
+#define MAX_MENU_NUMBER 100
+
+///
+/// This is the structure that will be used to store the
+/// question's current value. Use it at initialize time to
+/// set default value for each question. When using at run
+/// time, this map is returned by the callback function,
+/// so dynamically changing the question's value will be
+/// possible through this mechanism
+///
+typedef struct {
+ //
+ // Three questions displayed at the main page
+ // for Timeout, BootNext Variables respectively
+ //
+ UINT16 BootTimeOut;
+ UINT16 BootNext;
+
+ //
+ // This is the COM1 Attributes value storage
+ //
+ UINT8 COM1BaudRate;
+ UINT8 COM1DataRate;
+ UINT8 COM1StopBits;
+ UINT8 COM1Parity;
+ UINT8 COM1TerminalType;
+
+ //
+ // This is the COM2 Attributes value storage
+ //
+ UINT8 COM2BaudRate;
+ UINT8 COM2DataRate;
+ UINT8 COM2StopBits;
+ UINT8 COM2Parity;
+ UINT8 COM2TerminalType;
+
+ //
+ // Driver Option Add Handle page storage
+ //
+ UINT16 DriverAddHandleDesc[MAX_MENU_NUMBER];
+ UINT16 DriverAddHandleOptionalData[MAX_MENU_NUMBER];
+ UINT8 DriverAddActive;
+ UINT8 DriverAddForceReconnect;
+
+ //
+ // Console Input/Output/Errorout using COM port check storage
+ //
+ UINT8 ConsoleInputCOM1;
+ UINT8 ConsoleInputCOM2;
+ UINT8 ConsoleOutputCOM1;
+ UINT8 ConsoleOutputCOM2;
+ UINT8 ConsoleErrorCOM1;
+ UINT8 ConsoleErrorCOM2;
+
+ //
+ // At most 100 input/output/errorout device for console storage
+ //
+ UINT8 ConsoleCheck[MAX_MENU_NUMBER];
+ //
+ // At most 100 input/output/errorout device for console storage
+ //
+ UINT8 ConsoleInCheck[MAX_MENU_NUMBER];
+ UINT8 ConsoleOutCheck[MAX_MENU_NUMBER];
+ UINT8 ConsoleErrCheck[MAX_MENU_NUMBER];
+
+ //
+ // Boot Option Order storage
+ // The value is the OptionNumber+1 because the order list value cannot be 0
+ // Use UINT32 to hold the potential value 0xFFFF+1=0x10000
+ //
+ UINT32 BootOptionOrder[MAX_MENU_NUMBER];
+
+ //
+ // Driver Option Order storage
+ // The value is the OptionNumber+1 because the order list value cannot be 0
+ // Use UINT32 to hold the potential value 0xFFFF+1=0x10000
+ //
+ UINT32 DriverOptionOrder[MAX_MENU_NUMBER];
+
+ //
+ // Boot Option Delete storage
+ //
+ BOOLEAN BootOptionDel[MAX_MENU_NUMBER];
+ BOOLEAN BootOptionDelMark[MAX_MENU_NUMBER];
+
+ //
+ // Driver Option Delete storage
+ //
+ BOOLEAN DriverOptionDel[MAX_MENU_NUMBER];
+ BOOLEAN DriverOptionDelMark[MAX_MENU_NUMBER];
+
+ //
+ // This is the Terminal Attributes value storage
+ //
+ UINT8 COMBaudRate[MAX_MENU_NUMBER];
+ UINT8 COMDataRate[MAX_MENU_NUMBER];
+ UINT8 COMStopBits[MAX_MENU_NUMBER];
+ UINT8 COMParity[MAX_MENU_NUMBER];
+ UINT8 COMTerminalType[MAX_MENU_NUMBER];
+ UINT8 COMFlowControl[MAX_MENU_NUMBER];
+
+ //
+ // Legacy Device Order Selection Storage
+ //
+ UINT8 LegacyFD[MAX_MENU_NUMBER];
+ UINT8 LegacyHD[MAX_MENU_NUMBER];
+ UINT8 LegacyCD[MAX_MENU_NUMBER];
+ UINT8 LegacyNET[MAX_MENU_NUMBER];
+ UINT8 LegacyBEV[MAX_MENU_NUMBER];
+
+ //
+ // We use DisableMap array to record the enable/disable state of each boot device
+ // It should be taken as a bit array, from left to right there are totally 256 bits
+ // the most left one stands for BBS table item 0, and the most right one stands for item 256
+ // If the bit is 1, it means the boot device has been disabled.
+ //
+ UINT8 DisableMap[32];
+
+ //
+ // Console Output Text Mode
+ //
+ UINT16 ConsoleOutMode;
+
+ //
+ // UINT16 PadArea[10];
+ //
+} BMM_FAKE_NV_DATA;
+
+//
+// Key used by File Explorer forms
+//
+#define KEY_VALUE_SAVE_AND_EXIT_BOOT 0x1000
+#define KEY_VALUE_NO_SAVE_AND_EXIT_BOOT 0x1001
+#define KEY_VALUE_SAVE_AND_EXIT_DRIVER 0x1002
+#define KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER 0x1003
+
+//
+// Description data and optional data size
+//
+#define DESCRIPTION_DATA_SIZE 75
+#define OPTIONAL_DATA_SIZE 127
+
+///
+/// This is the data structure used by File Explorer formset
+///
+typedef struct {
+ UINT16 BootDescriptionData[DESCRIPTION_DATA_SIZE];
+ UINT16 BootOptionalData[OPTIONAL_DATA_SIZE];
+ UINT16 DriverDescriptionData[DESCRIPTION_DATA_SIZE];
+ UINT16 DriverOptionalData[OPTIONAL_DATA_SIZE];
+ BOOLEAN BootOptionChanged;
+ BOOLEAN DriverOptionChanged;
+ UINT8 Active;
+ UINT8 ForceReconnect;
+} FILE_EXPLORER_NV_DATA;
+
+#endif
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/UpdatePage.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/UpdatePage.c
new file mode 100644
index 0000000000..bdf26141d8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/UpdatePage.c
@@ -0,0 +1,1413 @@
+/** @file
+Dynamically update the pages.
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BootMaint.h"
+
+/**
+ Refresh the global UpdateData structure.
+
+**/
+VOID
+RefreshUpdateData (
+ VOID
+ )
+{
+ //
+ // Free current updated date
+ //
+ if (mStartOpCodeHandle != NULL) {
+ HiiFreeOpCodeHandle (mStartOpCodeHandle);
+ }
+
+ //
+ // Create new OpCode Handle
+ //
+ mStartOpCodeHandle = HiiAllocateOpCodeHandle ();
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ mStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ mStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+
+}
+
+/**
+ Add a "Go back to main page" tag in front of the form when there are no
+ "Apply changes" and "Discard changes" tags in the end of the form.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdatePageStart (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ RefreshUpdateData ();
+ mStartLabel->Number = CallbackData->BmmCurrentPageId;
+
+ if (!(CallbackData->BmmAskSaveOrNot)) {
+ //
+ // Add a "Go back to main page" tag in front of the form when there are no
+ // "Apply changes" and "Discard changes" tags in the end of the form.
+ //
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_MAIN_ID,
+ STRING_TOKEN (STR_FORM_GOTO_MAIN),
+ STRING_TOKEN (STR_FORM_GOTO_MAIN),
+ 0,
+ FORM_MAIN_ID
+ );
+ }
+
+}
+
+/**
+ Create the "Apply changes" and "Discard changes" tags. And
+ ensure user can return to the main page.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdatePageEnd (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ //
+ // Create the "Apply changes" and "Discard changes" tags.
+ //
+ if (CallbackData->BmmAskSaveOrNot) {
+ HiiCreateSubTitleOpCode (
+ mStartOpCodeHandle,
+ STRING_TOKEN (STR_NULL_STRING),
+ 0,
+ 0,
+ 0
+ );
+
+ HiiCreateActionOpCode (
+ mStartOpCodeHandle,
+ KEY_VALUE_SAVE_AND_EXIT,
+ STRING_TOKEN (STR_SAVE_AND_EXIT),
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+ }
+
+ //
+ // Ensure user can return to the main page.
+ //
+ HiiCreateActionOpCode (
+ mStartOpCodeHandle,
+ KEY_VALUE_NO_SAVE_AND_EXIT,
+ STRING_TOKEN (STR_NO_SAVE_AND_EXIT),
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+
+ HiiUpdateForm (
+ CallbackData->BmmHiiHandle,
+ &gBootMaintFormSetGuid,
+ CallbackData->BmmCurrentPageId,
+ mStartOpCodeHandle, // Label CallbackData->BmmCurrentPageId
+ mEndOpCodeHandle // LABEL_END
+ );
+}
+
+/**
+ Clean up the dynamic opcode at label and form specified by both LabelId.
+
+ @param LabelId It is both the Form ID and Label ID for opcode deletion.
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+CleanUpPage (
+ IN UINT16 LabelId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ RefreshUpdateData ();
+
+ //
+ // Remove all op-codes from dynamic page
+ //
+ mStartLabel->Number = LabelId;
+ HiiUpdateForm (
+ CallbackData->BmmHiiHandle,
+ &gBootMaintFormSetGuid,
+ LabelId,
+ mStartOpCodeHandle, // Label LabelId
+ mEndOpCodeHandle // LABEL_END
+ );
+}
+
+/**
+ Boot a file selected by user at File Expoloer of BMM.
+
+ @param FileContext The file context data, which contains the device path
+ of the file to be boot from.
+
+ @retval EFI_SUCCESS The function completed successfull.
+ @return Other value if the boot from the file fails.
+
+**/
+EFI_STATUS
+BootThisFile (
+ IN BM_FILE_CONTEXT *FileContext
+ )
+{
+ EFI_STATUS Status;
+ UINTN ExitDataSize;
+ CHAR16 *ExitData;
+ BDS_COMMON_OPTION *Option;
+
+ Option = (BDS_COMMON_OPTION *) AllocatePool (sizeof (BDS_COMMON_OPTION));
+ ASSERT (Option != NULL);
+ Option->Description = (CHAR16 *) AllocateCopyPool (StrSize (FileContext->FileName), FileContext->FileName);
+ Option->DevicePath = FileContext->DevicePath;
+ Option->LoadOptionsSize = 0;
+ Option->LoadOptions = NULL;
+
+ //
+ // Since current no boot from removable media directly is allowed */
+ //
+ gST->ConOut->ClearScreen (gST->ConOut);
+
+ ExitDataSize = 0;
+
+ Status = BdsLibBootViaBootOption (Option, Option->DevicePath, &ExitDataSize, &ExitData);
+
+ return Status;
+
+}
+
+/**
+ Create a list of Goto Opcode for all terminal devices logged
+ by TerminaMenu. This list will be inserted to form FORM_CON_COM_SETUP_ID.
+
+ @param CallbackData The BMM context data.
+**/
+VOID
+UpdateConCOMPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 Index;
+
+ CallbackData->BmmAskSaveOrNot = FALSE;
+
+ UpdatePageStart (CallbackData);
+
+
+ for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index);
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_CON_COM_SETUP_ID,
+ NewMenuEntry->DisplayStringToken,
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ (UINT16) (TERMINAL_OPTION_OFFSET + Index)
+ );
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create a lit of boot option from global BootOptionMenu. It
+ allow user to delete the boot option.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateBootDelPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 Index;
+
+ CallbackData->BmmAskSaveOrNot = TRUE;
+
+ UpdatePageStart (CallbackData);
+ CreateMenuStringToken (CallbackData, CallbackData->BmmHiiHandle, &BootOptionMenu);
+
+ ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.BootOptionDel) / sizeof (CallbackData->BmmFakeNvData.BootOptionDel[0])));
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ if (NewLoadContext->IsLegacy) {
+ continue;
+ }
+
+ NewLoadContext->Deleted = FALSE;
+
+ if (CallbackData->BmmFakeNvData.BootOptionDel[Index] && !CallbackData->BmmFakeNvData.BootOptionDelMark[Index]) {
+ //
+ // CallbackData->BmmFakeNvData.BootOptionDel[Index] == TRUE means browser knows this boot option is selected
+ // CallbackData->BmmFakeNvData.BootOptionDelMark[Index] = FALSE means BDS knows the selected boot option has
+ // deleted, browser maintains old useless info. So clear this info here, and later update this info to browser
+ // through HiiSetBrowserData function.
+ //
+ CallbackData->BmmFakeNvData.BootOptionDel[Index] = FALSE;
+ }
+
+ HiiCreateCheckBoxOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (BOOT_OPTION_DEL_QUESTION_ID + Index),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (BOOT_OPTION_DEL_VAR_OFFSET + Index),
+ NewMenuEntry->DisplayStringToken,
+ NewMenuEntry->HelpStringToken,
+ EFI_IFR_FLAG_CALLBACK,
+ 0,
+ NULL
+ );
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create a lit of driver option from global DriverMenu.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateDrvAddHandlePage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 Index;
+
+ CallbackData->BmmAskSaveOrNot = FALSE;
+
+ UpdatePageStart (CallbackData);
+
+ for (Index = 0; Index < DriverMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverMenu, Index);
+
+ HiiCreateGotoOpCode (
+ mStartOpCodeHandle,
+ FORM_DRV_ADD_HANDLE_DESC_ID,
+ NewMenuEntry->DisplayStringToken,
+ STRING_TOKEN (STR_NULL_STRING),
+ EFI_IFR_FLAG_CALLBACK,
+ (UINT16) (HANDLE_OPTION_OFFSET + Index)
+ );
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create a lit of driver option from global DriverOptionMenu. It
+ allow user to delete the driver option.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateDrvDelPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 Index;
+
+ CallbackData->BmmAskSaveOrNot = TRUE;
+
+ UpdatePageStart (CallbackData);
+
+ CreateMenuStringToken (CallbackData, CallbackData->BmmHiiHandle, &DriverOptionMenu);
+
+ ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.DriverOptionDel) / sizeof (CallbackData->BmmFakeNvData.DriverOptionDel[0])));
+ for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index);
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->Deleted = FALSE;
+
+ if (CallbackData->BmmFakeNvData.DriverOptionDel[Index] && !CallbackData->BmmFakeNvData.DriverOptionDelMark[Index]) {
+ //
+ // CallbackData->BmmFakeNvData.BootOptionDel[Index] == TRUE means browser knows this boot option is selected
+ // CallbackData->BmmFakeNvData.BootOptionDelMark[Index] = FALSE means BDS knows the selected boot option has
+ // deleted, browser maintains old useless info. So clear this info here, and later update this info to browser
+ // through HiiSetBrowserData function.
+ //
+ CallbackData->BmmFakeNvData.DriverOptionDel[Index] = FALSE;
+ }
+
+ HiiCreateCheckBoxOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (DRIVER_OPTION_DEL_QUESTION_ID + Index),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (DRIVER_OPTION_DEL_VAR_OFFSET + Index),
+ NewMenuEntry->DisplayStringToken,
+ NewMenuEntry->HelpStringToken,
+ EFI_IFR_FLAG_CALLBACK,
+ 0,
+ NULL
+ );
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Prepare the page to allow user to add description for
+ a Driver Option.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateDriverAddHandleDescPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+
+ CallbackData->BmmFakeNvData.DriverAddActive = 0x01;
+ CallbackData->BmmFakeNvData.DriverAddForceReconnect = 0x00;
+ CallbackData->BmmAskSaveOrNot = TRUE;
+ NewMenuEntry = CallbackData->MenuEntry;
+
+ UpdatePageStart (CallbackData);
+
+ HiiCreateSubTitleOpCode (
+ mStartOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ 0,
+ 0,
+ 0
+ );
+
+ HiiCreateStringOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) DRV_ADD_HANDLE_DESC_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ DRV_ADD_HANDLE_DESC_VAR_OFFSET,
+ STRING_TOKEN (STR_LOAD_OPTION_DESC),
+ STRING_TOKEN (STR_NULL_STRING),
+ 0,
+ 0,
+ 6,
+ 75,
+ NULL
+ );
+
+ HiiCreateCheckBoxOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) DRV_ADD_RECON_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ DRV_ADD_RECON_VAR_OFFSET,
+ STRING_TOKEN (STR_LOAD_OPTION_FORCE_RECON),
+ STRING_TOKEN (STR_LOAD_OPTION_FORCE_RECON),
+ 0,
+ 0,
+ NULL
+ );
+
+ HiiCreateStringOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) DRIVER_ADD_OPTION_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ DRIVER_ADD_OPTION_VAR_OFFSET,
+ STRING_TOKEN (STR_OPTIONAL_DATA),
+ STRING_TOKEN (STR_NULL_STRING),
+ 0,
+ 0,
+ 6,
+ 75,
+ NULL
+ );
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Update console page.
+
+ @param UpdatePageId The form ID to be updated.
+ @param ConsoleMenu The console menu list.
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateConsolePage (
+ IN UINT16 UpdatePageId,
+ IN BM_MENU_OPTION *ConsoleMenu,
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 Index;
+ UINT8 CheckFlags;
+ UINT8 *ConsoleCheck;
+ EFI_QUESTION_ID QuestionIdBase;
+ UINT16 VariableOffsetBase;
+
+ UpdatePageStart (CallbackData);
+
+ ConsoleCheck = NULL;
+ QuestionIdBase = 0;
+ VariableOffsetBase = 0;
+
+ switch (UpdatePageId) {
+ case FORM_CON_IN_ID:
+ ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleInCheck[0];
+ QuestionIdBase = CON_IN_DEVICE_QUESTION_ID;
+ VariableOffsetBase = CON_IN_DEVICE_VAR_OFFSET;
+ break;
+
+ case FORM_CON_OUT_ID:
+ ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleOutCheck[0];
+ QuestionIdBase = CON_OUT_DEVICE_QUESTION_ID;
+ VariableOffsetBase = CON_OUT_DEVICE_VAR_OFFSET;
+ break;
+
+ case FORM_CON_ERR_ID:
+ ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleErrCheck[0];
+ QuestionIdBase = CON_ERR_DEVICE_QUESTION_ID;
+ VariableOffsetBase = CON_ERR_DEVICE_VAR_OFFSET;
+ break;
+ }
+ ASSERT (ConsoleCheck != NULL);
+
+ for (Index = 0; ((Index < ConsoleMenu->MenuNumber) && \
+ (Index < MAX_MENU_NUMBER)) ; Index++) {
+ CheckFlags = 0;
+ if (UpdatePageId != FORM_CON_ERR_ID) {
+ CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT;
+ }
+ NewMenuEntry = BOpt_GetMenuEntry (ConsoleMenu, Index);
+ HiiCreateCheckBoxOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (QuestionIdBase + Index),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (VariableOffsetBase + Index),
+ NewMenuEntry->DisplayStringToken,
+ NewMenuEntry->HelpStringToken,
+ 0,
+ CheckFlags,
+ NULL
+ );
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Update the page's NV Map if user has changed the order
+ a list. This list can be Boot Order or Driver Order.
+
+ @param UpdatePageId The form ID to be updated.
+ @param OptionMenu The new list.
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateOrderPage (
+ IN UINT16 UpdatePageId,
+ IN BM_MENU_OPTION *OptionMenu,
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 Index;
+ UINT16 OptionIndex;
+ VOID *OptionsOpCodeHandle;
+ BOOLEAN BootOptionFound;
+ UINT32 *OptionOrder;
+ EFI_QUESTION_ID QuestionId;
+ UINT16 VarOffset;
+
+
+ UpdatePageStart (CallbackData);
+
+ CreateMenuStringToken (CallbackData, CallbackData->BmmHiiHandle, OptionMenu);
+
+ OptionOrder = NULL;
+ QuestionId = 0;
+ VarOffset = 0;
+ switch (UpdatePageId) {
+
+ case FORM_BOOT_CHG_ID:
+ //
+ // If the BootOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData,
+ // means all Boot Options has been save in BootOptionMenu, we can get the date from the menu.
+ // else means browser maintains some uncommitted date which are not saved in BootOptionMenu,
+ // so we should not get the data from BootOptionMenu to show it.
+ //
+ if (CompareMem (CallbackData->BmmFakeNvData.BootOptionOrder, CallbackData->BmmOldFakeNVData.BootOptionOrder, sizeof (CallbackData->BmmFakeNvData.BootOptionOrder)) == 0) {
+ GetBootOrder (CallbackData);
+ }
+ OptionOrder = CallbackData->BmmFakeNvData.BootOptionOrder;
+ QuestionId = BOOT_OPTION_ORDER_QUESTION_ID;
+ VarOffset = BOOT_OPTION_ORDER_VAR_OFFSET;
+ break;
+
+ case FORM_DRV_CHG_ID:
+ //
+ // If the DriverOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData,
+ // means all Driver Options has been save in DriverOptionMenu, we can get the DriverOptionOrder from the menu.
+ // else means browser maintains some uncommitted date which are not saved in DriverOptionMenu,
+ // so we should not get the data from DriverOptionMenu to show it.
+ //
+ if (CompareMem (CallbackData->BmmFakeNvData.DriverOptionOrder, CallbackData->BmmOldFakeNVData.DriverOptionOrder, sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder)) == 0) {
+ GetDriverOrder (CallbackData);
+ }
+ OptionOrder = CallbackData->BmmFakeNvData.DriverOptionOrder;
+ QuestionId = DRIVER_OPTION_ORDER_QUESTION_ID;
+ VarOffset = DRIVER_OPTION_ORDER_VAR_OFFSET;
+ break;
+ }
+ ASSERT (OptionOrder != NULL);
+
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ NewMenuEntry = NULL;
+ for (OptionIndex = 0; (OptionIndex < MAX_MENU_NUMBER && OptionOrder[OptionIndex] != 0); OptionIndex++) {
+ BootOptionFound = FALSE;
+ for (Index = 0; Index < OptionMenu->MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (OptionMenu, Index);
+ if ((UINT32) (NewMenuEntry->OptionNumber + 1) == OptionOrder[OptionIndex]) {
+ BootOptionFound = TRUE;
+ break;
+ }
+ }
+ if (BootOptionFound) {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_32,
+ OptionOrder[OptionIndex]
+ );
+ }
+ }
+
+ if (OptionMenu->MenuNumber > 0) {
+ HiiCreateOrderedListOpCode (
+ mStartOpCodeHandle, // Container for dynamic created opcodes
+ QuestionId, // Question ID
+ VARSTORE_ID_BOOT_MAINT, // VarStore ID
+ VarOffset, // Offset in Buffer Storage
+ STRING_TOKEN (STR_CHANGE_ORDER), // Question prompt text
+ STRING_TOKEN (STR_CHANGE_ORDER), // Question help text
+ 0, // Question flag
+ 0, // Ordered list flag, e.g. EFI_IFR_UNIQUE_SET
+ EFI_IFR_TYPE_NUM_SIZE_32, // Data type of Question value
+ 100, // Maximum container
+ OptionsOpCodeHandle, // Option Opcode list
+ NULL // Default Opcode is NULL
+ );
+ }
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create the dynamic page to allow user to set
+ the "BootNext" value.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateBootNextPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINTN NumberOfOptions;
+ UINT16 Index;
+ VOID *OptionsOpCodeHandle;
+
+ NumberOfOptions = BootOptionMenu.MenuNumber;
+ CallbackData->BmmAskSaveOrNot = TRUE;
+
+ UpdatePageStart (CallbackData);
+ CreateMenuStringToken (CallbackData, CallbackData->BmmHiiHandle, &BootOptionMenu);
+
+ if (NumberOfOptions > 0) {
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ //CallbackData->BmmFakeNvData.BootNext = (UINT16) (BootOptionMenu.MenuNumber);
+
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+
+ if (NewLoadContext->IsBootNext) {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ EFI_IFR_OPTION_DEFAULT,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ Index
+ );
+ //CallbackData->BmmFakeNvData.BootNext = Index;
+ } else {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ Index
+ );
+ }
+ }
+
+ if (CallbackData->BmmFakeNvData.BootNext == Index) {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ STRING_TOKEN (STR_NONE),
+ EFI_IFR_OPTION_DEFAULT,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ Index
+ );
+ } else {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ STRING_TOKEN (STR_NONE),
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) BOOT_NEXT_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ BOOT_NEXT_VAR_OFFSET,
+ STRING_TOKEN (STR_BOOT_NEXT),
+ STRING_TOKEN (STR_BOOT_NEXT_HELP),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_2,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ }
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create the dynamic page to allow user to set the "TimeOut" value.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateTimeOutPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINT16 BootTimeOut;
+ VOID *DefaultOpCodeHandle;
+
+ CallbackData->BmmAskSaveOrNot = TRUE;
+
+ UpdatePageStart (CallbackData);
+
+ BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
+
+ DefaultOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (DefaultOpCodeHandle != NULL);
+ HiiCreateDefaultOpCode (DefaultOpCodeHandle, EFI_HII_DEFAULT_CLASS_STANDARD, EFI_IFR_TYPE_NUM_SIZE_16, BootTimeOut);
+
+ HiiCreateNumericOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) BOOT_TIME_OUT_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ BOOT_TIME_OUT_VAR_OFFSET,
+ STRING_TOKEN (STR_NUM_AUTO_BOOT),
+ STRING_TOKEN (STR_HLP_AUTO_BOOT),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_2 | EFI_IFR_DISPLAY_UINT_DEC,
+ 0,
+ 65535,
+ 0,
+ DefaultOpCodeHandle
+ );
+
+ HiiFreeOpCodeHandle (DefaultOpCodeHandle);
+
+ //CallbackData->BmmFakeNvData.BootTimeOut = BootTimeOut;
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Refresh the text mode page.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateConModePage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINTN Mode;
+ UINTN Index;
+ UINTN Col;
+ UINTN Row;
+ CHAR16 ModeString[50];
+ CHAR16 *PStr;
+ UINTN MaxMode;
+ UINTN ValidMode;
+ EFI_STRING_ID *ModeToken;
+ EFI_STATUS Status;
+ VOID *OptionsOpCodeHandle;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut;
+
+ ConOut = gST->ConOut;
+ Index = 0;
+ ValidMode = 0;
+ MaxMode = (UINTN) (ConOut->Mode->MaxMode);
+
+ CallbackData->BmmAskSaveOrNot = TRUE;
+
+ UpdatePageStart (CallbackData);
+
+ //
+ // Check valid mode
+ //
+ for (Mode = 0; Mode < MaxMode; Mode++) {
+ Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row);
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+ ValidMode++;
+ }
+
+ if (ValidMode == 0) {
+ return;
+ }
+
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ ModeToken = AllocateZeroPool (sizeof (EFI_STRING_ID) * ValidMode);
+ ASSERT(ModeToken != NULL);
+
+ //
+ // Determin which mode should be the first entry in menu
+ //
+ // GetConsoleOutMode (CallbackData);
+
+ //
+ // Build text mode options
+ //
+ for (Mode = 0; Mode < MaxMode; Mode++) {
+ Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row);
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ //
+ // Build mode string Column x Row
+ //
+ UnicodeValueToStringS (ModeString, sizeof (ModeString), 0, Col, 0);
+ PStr = &ModeString[0];
+ StrCatS (PStr, ARRAY_SIZE (ModeString), L" x ");
+ PStr = PStr + StrLen (PStr);
+ UnicodeValueToStringS (
+ PStr,
+ sizeof (ModeString) - ((UINTN)PStr - (UINTN)&ModeString[0]),
+ 0,
+ Row,
+ 0
+ );
+
+ ModeToken[Index] = HiiSetString (CallbackData->BmmHiiHandle, 0, ModeString, NULL);
+
+ if (Mode == CallbackData->BmmFakeNvData.ConsoleOutMode) {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ ModeToken[Index],
+ EFI_IFR_OPTION_DEFAULT,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ (UINT16) Mode
+ );
+ } else {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ ModeToken[Index],
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_16,
+ (UINT16) Mode
+ );
+ }
+ Index++;
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) CON_MODE_QUESTION_ID,
+ VARSTORE_ID_BOOT_MAINT,
+ CON_MODE_VAR_OFFSET,
+ STRING_TOKEN (STR_CON_MODE_SETUP),
+ STRING_TOKEN (STR_CON_MODE_SETUP),
+ EFI_IFR_FLAG_RESET_REQUIRED,
+ EFI_IFR_NUMERIC_SIZE_2,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ FreePool (ModeToken);
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Create the dynamic page which allows user to set the property such as Baud Rate, Data Bits,
+ Parity, Stop Bits, Terminal Type.
+
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdateTerminalPage (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ UINT8 Index;
+ UINT8 CheckFlags;
+ BM_MENU_ENTRY *NewMenuEntry;
+ VOID *OptionsOpCodeHandle;
+ UINTN CurrentTerminal;
+
+ UpdatePageStart (CallbackData);
+
+ CurrentTerminal = CallbackData->CurrentTerminal;
+ NewMenuEntry = BOpt_GetMenuEntry (
+ &TerminalMenu,
+ CurrentTerminal
+ );
+
+ if (NewMenuEntry == NULL) {
+ return ;
+ }
+
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < sizeof (BaudRateList) / sizeof (BaudRateList [0]); Index++) {
+ CheckFlags = 0;
+ if (BaudRateList[Index].Value == 115200) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ BaudRateList[Index].StringToken,
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_BAUD_RATE_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_BAUD_RATE_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_BAUD_RATE),
+ STRING_TOKEN (STR_COM_BAUD_RATE),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < ARRAY_SIZE (DataBitsList); Index++) {
+ CheckFlags = 0;
+
+ if (DataBitsList[Index].Value == 8) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ DataBitsList[Index].StringToken,
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_DATA_RATE_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_DATA_RATE_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_DATA_BITS),
+ STRING_TOKEN (STR_COM_DATA_BITS),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < ARRAY_SIZE (ParityList); Index++) {
+ CheckFlags = 0;
+ if (ParityList[Index].Value == NoParity) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ ParityList[Index].StringToken,
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_PARITY_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_PARITY_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_PARITY),
+ STRING_TOKEN (STR_COM_PARITY),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < ARRAY_SIZE (StopBitsList); Index++) {
+ CheckFlags = 0;
+ if (StopBitsList[Index].Value == OneStopBit) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ StopBitsList[Index].StringToken,
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_STOP_BITS_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_STOP_BITS_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_STOP_BITS),
+ STRING_TOKEN (STR_COM_STOP_BITS),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < 4; Index++) {
+ CheckFlags = 0;
+ if (Index == 0) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ (EFI_STRING_ID) TerminalType[Index],
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ Index
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_TERMINAL_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_TERMINAL_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_TERMI_TYPE),
+ STRING_TOKEN (STR_COM_TERMI_TYPE),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < ARRAY_SIZE (mFlowControlType); Index++) {
+ CheckFlags = 0;
+ if (Index == 0) {
+ CheckFlags |= EFI_IFR_OPTION_DEFAULT;
+ }
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ (EFI_STRING_ID) mFlowControlType[Index],
+ CheckFlags,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ mFlowControlValue[Index]
+ );
+ }
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (COM_FLOWCONTROL_QUESTION_ID + CurrentTerminal),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (COM_FLOWCONTROL_VAR_OFFSET + CurrentTerminal),
+ STRING_TOKEN (STR_COM_FLOW_CONTROL),
+ STRING_TOKEN (STR_COM_FLOW_CONTROL),
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+
+ UpdatePageEnd (CallbackData);
+}
+
+/**
+ Dispatch the correct update page function to call based on
+ the UpdatePageId.
+
+ @param UpdatePageId The form ID.
+ @param CallbackData The BMM context data.
+
+**/
+VOID
+UpdatePageBody (
+ IN UINT16 UpdatePageId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ CleanUpPage (UpdatePageId, CallbackData);
+ switch (UpdatePageId) {
+ case FORM_CON_IN_ID:
+ UpdateConsolePage (UpdatePageId, &ConsoleInpMenu, CallbackData);
+ break;
+
+ case FORM_CON_OUT_ID:
+ UpdateConsolePage (UpdatePageId, &ConsoleOutMenu, CallbackData);
+ break;
+
+ case FORM_CON_ERR_ID:
+ UpdateConsolePage (UpdatePageId, &ConsoleErrMenu, CallbackData);
+ break;
+
+ case FORM_BOOT_CHG_ID:
+ UpdateOrderPage (UpdatePageId, &BootOptionMenu, CallbackData);
+ break;
+
+ case FORM_DRV_CHG_ID:
+ UpdateOrderPage (UpdatePageId, &DriverOptionMenu, CallbackData);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ Create a dynamic page so that Legacy Device boot order
+ can be set for specified device type.
+
+ @param UpdatePageId The form ID. It also spefies the legacy device type.
+ @param CallbackData The BMM context data.
+
+
+**/
+VOID
+UpdateSetLegacyDeviceOrderPage (
+ IN UINT16 UpdatePageId,
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ LEGACY_DEV_ORDER_ENTRY *DevOrder;
+ BM_MENU_OPTION *OptionMenu;
+ BM_MENU_ENTRY *NewMenuEntry;
+ EFI_STRING_ID StrRef;
+ EFI_STRING_ID StrRefHelp;
+ BBS_TYPE BbsType;
+ UINTN VarSize;
+ UINTN Pos;
+ UINTN Bit;
+ UINT16 Index;
+ UINT16 Key;
+ CHAR16 String[100];
+ CHAR16 *TypeStr;
+ CHAR16 *TypeStrHelp;
+ UINT16 VarDevOrder;
+ UINT8 *VarData;
+ UINT8 *LegacyOrder;
+ UINT8 *OldData;
+ UINT8 *DisMap;
+ VOID *OptionsOpCodeHandle;
+
+ OptionMenu = NULL;
+ Key = 0;
+ StrRef = 0;
+ StrRefHelp = 0;
+ TypeStr = NULL;
+ TypeStrHelp = NULL;
+ BbsType = BBS_FLOPPY;
+ LegacyOrder = NULL;
+ OldData = NULL;
+ DisMap = NULL;
+
+ CallbackData->BmmAskSaveOrNot = TRUE;
+ UpdatePageStart (CallbackData);
+
+ DisMap = ZeroMem (CallbackData->BmmOldFakeNVData.DisableMap, sizeof (CallbackData->BmmOldFakeNVData.DisableMap));
+
+ //
+ // Create oneof option list
+ //
+ switch (UpdatePageId) {
+ case FORM_SET_FD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyFDMenu;
+ Key = (UINT16) LEGACY_FD_QUESTION_ID;
+ TypeStr = STR_FLOPPY;
+ TypeStrHelp = STR_FLOPPY_HELP;
+ BbsType = BBS_FLOPPY;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyFD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyFD;
+ break;
+
+ case FORM_SET_HD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyHDMenu;
+ Key = (UINT16) LEGACY_HD_QUESTION_ID;
+ TypeStr = STR_HARDDISK;
+ TypeStrHelp = STR_HARDDISK_HELP;
+ BbsType = BBS_HARDDISK;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyHD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyHD;
+ break;
+
+ case FORM_SET_CD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyCDMenu;
+ Key = (UINT16) LEGACY_CD_QUESTION_ID;
+ TypeStr = STR_CDROM;
+ TypeStrHelp = STR_CDROM_HELP;
+ BbsType = BBS_CDROM;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyCD;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyCD;
+ break;
+
+ case FORM_SET_NET_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyNETMenu;
+ Key = (UINT16) LEGACY_NET_QUESTION_ID;
+ TypeStr = STR_NET;
+ TypeStrHelp = STR_NET_HELP;
+ BbsType = BBS_EMBED_NETWORK;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyNET;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyNET;
+ break;
+
+ case FORM_SET_BEV_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyBEVMenu;
+ Key = (UINT16) LEGACY_BEV_QUESTION_ID;
+ TypeStr = STR_BEV;
+ TypeStrHelp = STR_BEV_HELP;
+ BbsType = BBS_BEV_DEVICE;
+ LegacyOrder = CallbackData->BmmFakeNvData.LegacyBEV;
+ OldData = CallbackData->BmmOldFakeNVData.LegacyBEV;
+ break;
+
+ default:
+ DEBUG ((EFI_D_ERROR, "Invalid command ID for updating page!\n"));
+ return;
+ }
+
+ CreateMenuStringToken (CallbackData, CallbackData->BmmHiiHandle, OptionMenu);
+
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+
+ for (Index = 0; Index < OptionMenu->MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (OptionMenu, Index);
+ //
+ // Create OneOf for each legacy device
+ //
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ NewMenuEntry->DisplayStringToken,
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ (UINT8) ((BM_LEGACY_DEVICE_CONTEXT *) NewMenuEntry->VariableContext)->BbsIndex
+ );
+ }
+
+ //
+ // Create OneOf for item "Disabled"
+ //
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ STRING_TOKEN (STR_DISABLE_LEGACY_DEVICE),
+ 0,
+ EFI_IFR_TYPE_NUM_SIZE_8,
+ 0xFF
+ );
+
+ //
+ // Get Device Order from variable
+ //
+ VarData = BdsLibGetVariableAndSize (
+ VAR_LEGACY_DEV_ORDER,
+ &gEfiLegacyDevOrderVariableGuid,
+ &VarSize
+ );
+
+ if (NULL != VarData) {
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) VarData;
+ while (VarData < VarData + VarSize) {
+ if (DevOrder->BbsType == BbsType) {
+ break;
+ }
+
+ VarData = (UINT8 *)((UINTN)VarData + sizeof (BBS_TYPE));
+ VarData += *(UINT16 *) VarData;
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) VarData;
+ }
+ //
+ // Create oneof tag here for FD/HD/CD #1 #2
+ //
+ for (Index = 0; Index < OptionMenu->MenuNumber; Index++) {
+ //
+ // Create the string for oneof tag
+ //
+ UnicodeSPrint (String, sizeof (String), TypeStr, Index);
+ StrRef = HiiSetString (CallbackData->BmmHiiHandle, 0, String, NULL);
+
+ UnicodeSPrint (String, sizeof (String), TypeStrHelp, Index);
+ StrRefHelp = HiiSetString (CallbackData->BmmHiiHandle, 0, String, NULL);
+
+ HiiCreateOneOfOpCode (
+ mStartOpCodeHandle,
+ (EFI_QUESTION_ID) (Key + Index),
+ VARSTORE_ID_BOOT_MAINT,
+ (UINT16) (Key + Index - CONFIG_OPTION_OFFSET),
+ StrRef,
+ StrRefHelp,
+ EFI_IFR_FLAG_CALLBACK,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ VarDevOrder = *(UINT16 *) ((UINTN) DevOrder + sizeof (BBS_TYPE) + sizeof (UINT16) + Index * sizeof (UINT16));
+
+ if (0xFF00 == (VarDevOrder & 0xFF00)) {
+ LegacyOrder[Index] = 0xFF;
+ Pos = (VarDevOrder & 0xFF) / 8;
+ Bit = 7 - ((VarDevOrder & 0xFF) % 8);
+ DisMap[Pos] = (UINT8) (DisMap[Pos] | (UINT8) (1 << Bit));
+ } else {
+ LegacyOrder[Index] = (UINT8) (VarDevOrder & 0xFF);
+ }
+ }
+ }
+
+ CopyMem (OldData, LegacyOrder, 100);
+
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+
+ UpdatePageEnd (CallbackData);
+}
+
+
+/**
+ Dispatch the display to the next page based on NewPageId.
+
+ @param Private The BMM context data.
+ @param NewPageId The original page ID.
+
+**/
+VOID
+UpdatePageId (
+ BMM_CALLBACK_DATA *Private,
+ UINT16 NewPageId
+ )
+{
+ //
+ // For the question don't impact the page update, just ignore it.
+ //
+ if (((NewPageId >= BOOT_OPTION_DEL_QUESTION_ID) && (NewPageId < BOOT_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER)) ||
+ ((NewPageId >= DRIVER_OPTION_DEL_QUESTION_ID) && (NewPageId < DRIVER_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER))) {
+ return;
+ }
+
+ if ((NewPageId < FILE_OPTION_OFFSET) && (NewPageId >= HANDLE_OPTION_OFFSET)) {
+ //
+ // If we select a handle to add driver option, advance to the add handle description page.
+ //
+ NewPageId = FORM_DRV_ADD_HANDLE_DESC_ID;
+ } else if ((NewPageId == KEY_VALUE_SAVE_AND_EXIT) || (NewPageId == KEY_VALUE_NO_SAVE_AND_EXIT)) {
+ //
+ // Return to main page after "Save Changes" or "Discard Changes".
+ //
+ NewPageId = FORM_MAIN_ID;
+ } else if ((NewPageId >= TERMINAL_OPTION_OFFSET) && (NewPageId < CONSOLE_OPTION_OFFSET)) {
+ NewPageId = FORM_CON_COM_SETUP_ID;
+ }
+
+ if ((NewPageId > 0) && (NewPageId < MAXIMUM_FORM_ID)) {
+ Private->BmmPreviousPageId = Private->BmmCurrentPageId;
+ Private->BmmCurrentPageId = NewPageId;
+ }
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Variable.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Variable.c
new file mode 100644
index 0000000000..414367cf23
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/Variable.c
@@ -0,0 +1,1380 @@
+/** @file
+ Variable operation that will be used by bootmaint
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BootMaint.h"
+
+/**
+ Delete Boot Option that represent a Deleted state in BootOptionMenu.
+ After deleting this boot option, call Var_ChangeBootOrder to
+ make sure BootOrder is in valid state.
+
+ @retval EFI_SUCCESS If all boot load option EFI Variables corresponding to
+ BM_LOAD_CONTEXT marked for deletion is deleted.
+ @retval EFI_NOT_FOUND If can not find the boot option want to be deleted.
+ @return Others If failed to update the "BootOrder" variable after deletion.
+
+**/
+EFI_STATUS
+Var_DelBootOption (
+ VOID
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 BootString[10];
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN Index2;
+
+ Status = EFI_SUCCESS;
+ Index2 = 0;
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, (Index - Index2));
+ if (NULL == NewMenuEntry) {
+ return EFI_NOT_FOUND;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ if (!NewLoadContext->Deleted) {
+ continue;
+ }
+
+ UnicodeSPrint (
+ BootString,
+ sizeof (BootString),
+ L"Boot%04x",
+ NewMenuEntry->OptionNumber
+ );
+
+ EfiLibDeleteVariable (BootString, &gEfiGlobalVariableGuid);
+ Index2++;
+ //
+ // If current Load Option is the same as BootNext,
+ // must delete BootNext in order to make sure
+ // there will be no panic on next boot
+ //
+ if (NewLoadContext->IsBootNext) {
+ EfiLibDeleteVariable (L"BootNext", &gEfiGlobalVariableGuid);
+ }
+
+ RemoveEntryList (&NewMenuEntry->Link);
+ BOpt_DestroyMenuEntry (NewMenuEntry);
+ NewMenuEntry = NULL;
+ }
+
+ BootOptionMenu.MenuNumber -= Index2;
+
+ Status = Var_ChangeBootOrder ();
+ return Status;
+}
+
+/**
+ After any operation on Boot####, there will be a discrepancy in BootOrder.
+ Since some are missing but in BootOrder, while some are present but are
+ not reflected by BootOrder. Then a function rebuild BootOrder from
+ scratch by content from BootOptionMenu is needed.
+
+
+
+
+ @retval EFI_SUCCESS The boot order is updated successfully.
+ @return EFI_STATUS other than EFI_SUCCESS if failed to
+ Set the "BootOrder" EFI Variable.
+
+**/
+EFI_STATUS
+Var_ChangeBootOrder (
+ VOID
+ )
+{
+
+ EFI_STATUS Status;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 *BootOrderList;
+ UINT16 *BootOrderListPtr;
+ UINTN BootOrderListSize;
+ UINTN Index;
+
+ BootOrderList = NULL;
+ BootOrderListSize = 0;
+
+ //
+ // First check whether BootOrder is present in current configuration
+ //
+ BootOrderList = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderListSize
+ );
+
+ //
+ // If exists, delete it to hold new BootOrder
+ //
+ if (BootOrderList != NULL) {
+ EfiLibDeleteVariable (L"BootOrder", &gEfiGlobalVariableGuid);
+ FreePool (BootOrderList);
+ BootOrderList = NULL;
+ }
+ //
+ // Maybe here should be some check method to ensure that
+ // no new added boot options will be added
+ // but the setup engine now will give only one callback
+ // that is to say, user are granted only one chance to
+ // decide whether the boot option will be added or not
+ // there should be no indictor to show whether this
+ // is a "new" boot option
+ //
+ BootOrderListSize = BootOptionMenu.MenuNumber;
+
+ if (BootOrderListSize > 0) {
+ BootOrderList = AllocateZeroPool (BootOrderListSize * sizeof (UINT16));
+ ASSERT (BootOrderList != NULL);
+ BootOrderListPtr = BootOrderList;
+
+ //
+ // Get all current used Boot#### from BootOptionMenu.
+ // OptionNumber in each BM_LOAD_OPTION is really its
+ // #### value.
+ //
+ for (Index = 0; Index < BootOrderListSize; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ *BootOrderList = (UINT16) NewMenuEntry->OptionNumber;
+ BootOrderList++;
+ }
+
+ BootOrderList = BootOrderListPtr;
+
+ //
+ // After building the BootOrderList, write it back
+ //
+ Status = gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BootOrderListSize * sizeof (UINT16),
+ BootOrderList
+ );
+ //
+ // Changing variable without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Delete Load Option that represent a Deleted state in BootOptionMenu.
+ After deleting this Driver option, call Var_ChangeDriverOrder to
+ make sure DriverOrder is in valid state.
+
+ @retval EFI_SUCCESS Load Option is successfully updated.
+ @retval EFI_NOT_FOUND Fail to find the driver option want to be deleted.
+ @return Other value than EFI_SUCCESS if failed to update "Driver Order" EFI
+ Variable.
+
+**/
+EFI_STATUS
+Var_DelDriverOption (
+ VOID
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ UINT16 DriverString[12];
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN Index2;
+
+ Status = EFI_SUCCESS;
+ Index2 = 0;
+ for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, (Index - Index2));
+ if (NULL == NewMenuEntry) {
+ return EFI_NOT_FOUND;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ if (!NewLoadContext->Deleted) {
+ continue;
+ }
+
+ UnicodeSPrint (
+ DriverString,
+ sizeof (DriverString),
+ L"Driver%04x",
+ NewMenuEntry->OptionNumber
+ );
+
+ EfiLibDeleteVariable (DriverString, &gEfiGlobalVariableGuid);
+ Index2++;
+
+ RemoveEntryList (&NewMenuEntry->Link);
+ BOpt_DestroyMenuEntry (NewMenuEntry);
+ NewMenuEntry = NULL;
+ }
+
+ DriverOptionMenu.MenuNumber -= Index2;
+
+ Status = Var_ChangeDriverOrder ();
+ return Status;
+}
+
+/**
+ After any operation on Driver####, there will be a discrepancy in
+ DriverOrder. Since some are missing but in DriverOrder, while some
+ are present but are not reflected by DriverOrder. Then a function
+ rebuild DriverOrder from scratch by content from DriverOptionMenu is
+ needed.
+
+ @retval EFI_SUCCESS The driver order is updated successfully.
+ @return Other status than EFI_SUCCESS if failed to set the "DriverOrder" EFI Variable.
+
+**/
+EFI_STATUS
+Var_ChangeDriverOrder (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ BM_MENU_ENTRY *NewMenuEntry;
+ UINT16 *DriverOrderList;
+ UINT16 *DriverOrderListPtr;
+ UINTN DriverOrderListSize;
+ UINTN Index;
+
+ DriverOrderList = NULL;
+ DriverOrderListSize = 0;
+
+ //
+ // First check whether DriverOrder is present in current configuration
+ //
+ DriverOrderList = BdsLibGetVariableAndSize (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ &DriverOrderListSize
+ );
+
+ //
+ // If exists, delete it to hold new DriverOrder
+ //
+ if (DriverOrderList != NULL) {
+ EfiLibDeleteVariable (L"DriverOrder", &gEfiGlobalVariableGuid);
+ FreePool (DriverOrderList);
+ DriverOrderList = NULL;
+ }
+
+ DriverOrderListSize = DriverOptionMenu.MenuNumber;
+
+ if (DriverOrderListSize > 0) {
+ DriverOrderList = AllocateZeroPool (DriverOrderListSize * sizeof (UINT16));
+ ASSERT (DriverOrderList != NULL);
+ DriverOrderListPtr = DriverOrderList;
+
+ //
+ // Get all current used Driver#### from DriverOptionMenu.
+ // OptionNumber in each BM_LOAD_OPTION is really its
+ // #### value.
+ //
+ for (Index = 0; Index < DriverOrderListSize; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index);
+ *DriverOrderList = (UINT16) NewMenuEntry->OptionNumber;
+ DriverOrderList++;
+ }
+
+ DriverOrderList = DriverOrderListPtr;
+
+ //
+ // After building the DriverOrderList, write it back
+ //
+ Status = gRT->SetVariable (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ DriverOrderListSize * sizeof (UINT16),
+ DriverOrderList
+ );
+ //
+ // Changing variable without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Update the device path of "ConOut", "ConIn" and "ErrOut"
+ based on the new BaudRate, Data Bits, parity and Stop Bits
+ set.
+
+**/
+VOID
+Var_UpdateAllConsoleOption (
+ VOID
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *OutDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *InpDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *ErrDevicePath;
+ EFI_STATUS Status;
+
+ OutDevicePath = EfiLibGetVariable (L"ConOut", &gEfiGlobalVariableGuid);
+ InpDevicePath = EfiLibGetVariable (L"ConIn", &gEfiGlobalVariableGuid);
+ ErrDevicePath = EfiLibGetVariable (L"ErrOut", &gEfiGlobalVariableGuid);
+ if (OutDevicePath != NULL) {
+ ChangeVariableDevicePath (OutDevicePath);
+ Status = gRT->SetVariable (
+ L"ConOut",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ GetDevicePathSize (OutDevicePath),
+ OutDevicePath
+ );
+ //
+ // Changing variable without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ if (InpDevicePath != NULL) {
+ ChangeVariableDevicePath (InpDevicePath);
+ Status = gRT->SetVariable (
+ L"ConIn",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ GetDevicePathSize (InpDevicePath),
+ InpDevicePath
+ );
+ //
+ // Changing variable without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ if (ErrDevicePath != NULL) {
+ ChangeVariableDevicePath (ErrDevicePath);
+ Status = gRT->SetVariable (
+ L"ErrOut",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ GetDevicePathSize (ErrDevicePath),
+ ErrDevicePath
+ );
+ //
+ // Changing variable without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+}
+
+/**
+ This function delete and build multi-instance device path for
+ specified type of console device.
+
+ This function clear the EFI variable defined by ConsoleName and
+ gEfiGlobalVariableGuid. It then build the multi-instance device
+ path by appending the device path of the Console (In/Out/Err) instance
+ in ConsoleMenu. Then it scan all corresponding console device by
+ scanning Terminal (built from device supporting Serial I/O instances)
+ devices in TerminalMenu. At last, it save a EFI variable specifed
+ by ConsoleName and gEfiGlobalVariableGuid.
+
+ @param ConsoleName The name for the console device type. They are
+ usually "ConIn", "ConOut" and "ErrOut".
+ @param ConsoleMenu The console memu which is a list of console devices.
+ @param UpdatePageId The flag specifying which type of console device
+ to be processed.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateConsoleOption (
+ IN UINT16 *ConsoleName,
+ IN BM_MENU_OPTION *ConsoleMenu,
+ IN UINT16 UpdatePageId
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *ConDevicePath;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_CONSOLE_CONTEXT *NewConsoleContext;
+ BM_TERMINAL_CONTEXT *NewTerminalContext;
+ EFI_STATUS Status;
+ VENDOR_DEVICE_PATH Vendor;
+ EFI_DEVICE_PATH_PROTOCOL *TerminalDevicePath;
+ UINTN Index;
+
+ ConDevicePath = EfiLibGetVariable (ConsoleName, &gEfiGlobalVariableGuid);
+ if (ConDevicePath != NULL) {
+ EfiLibDeleteVariable (ConsoleName, &gEfiGlobalVariableGuid);
+ FreePool (ConDevicePath);
+ ConDevicePath = NULL;
+ };
+
+ //
+ // First add all console input device from console input menu
+ //
+ for (Index = 0; Index < ConsoleMenu->MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (ConsoleMenu, Index);
+
+ NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext;
+ if (NewConsoleContext->IsActive) {
+ ConDevicePath = AppendDevicePathInstance (
+ ConDevicePath,
+ NewConsoleContext->DevicePath
+ );
+ }
+ }
+
+ for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index);
+
+ NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext;
+ if (((NewTerminalContext->IsConIn != 0) && (UpdatePageId == FORM_CON_IN_ID)) ||
+ ((NewTerminalContext->IsConOut != 0) && (UpdatePageId == FORM_CON_OUT_ID)) ||
+ ((NewTerminalContext->IsStdErr != 0) && (UpdatePageId == FORM_CON_ERR_ID))
+ ) {
+ Vendor.Header.Type = MESSAGING_DEVICE_PATH;
+ Vendor.Header.SubType = MSG_VENDOR_DP;
+
+ ASSERT (NewTerminalContext->TerminalType < (ARRAY_SIZE (TerminalTypeGuid)));
+ CopyMem (
+ &Vendor.Guid,
+ &TerminalTypeGuid[NewTerminalContext->TerminalType],
+ sizeof (EFI_GUID)
+ );
+ SetDevicePathNodeLength (&Vendor.Header, sizeof (VENDOR_DEVICE_PATH));
+ TerminalDevicePath = AppendDevicePathNode (
+ NewTerminalContext->DevicePath,
+ (EFI_DEVICE_PATH_PROTOCOL *) &Vendor
+ );
+ ASSERT (TerminalDevicePath != NULL);
+ ChangeTerminalDevicePath (&TerminalDevicePath, TRUE);
+ ConDevicePath = AppendDevicePathInstance (
+ ConDevicePath,
+ TerminalDevicePath
+ );
+ }
+ }
+
+ if (ConDevicePath != NULL) {
+ Status = gRT->SetVariable (
+ ConsoleName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ GetDevicePathSize (ConDevicePath),
+ ConDevicePath
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ return EFI_SUCCESS;
+
+}
+
+/**
+ This function delete and build multi-instance device path ConIn
+ console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateConsoleInpOption (
+ VOID
+ )
+{
+ return Var_UpdateConsoleOption (L"ConIn", &ConsoleInpMenu, FORM_CON_IN_ID);
+}
+
+/**
+ This function delete and build multi-instance device path ConOut
+ console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateConsoleOutOption (
+ VOID
+ )
+{
+ return Var_UpdateConsoleOption (L"ConOut", &ConsoleOutMenu, FORM_CON_OUT_ID);
+}
+
+/**
+ This function delete and build multi-instance device path ErrOut
+ console device.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+**/
+EFI_STATUS
+Var_UpdateErrorOutOption (
+ VOID
+ )
+{
+ return Var_UpdateConsoleOption (L"ErrOut", &ConsoleErrMenu, FORM_CON_ERR_ID);
+}
+
+/**
+ This function create a currently loaded Drive Option from
+ the BMM. It then appends this Driver Option to the end of
+ the "DriverOrder" list. It append this Driver Opotion to the end
+ of DriverOptionMenu.
+
+ @param CallbackData The BMM context data.
+ @param HiiHandle The HII handle associated with the BMM formset.
+ @param DescriptionData The description of this driver option.
+ @param OptionalData The optional load option.
+ @param ForceReconnect If to force reconnect.
+
+ @retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
+ @retval EFI_SUCCESS If function completes successfully.
+
+**/
+EFI_STATUS
+Var_UpdateDriverOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_HII_HANDLE HiiHandle,
+ IN UINT16 *DescriptionData,
+ IN UINT16 *OptionalData,
+ IN UINT8 ForceReconnect
+ )
+{
+ UINT16 Index;
+ UINT16 *DriverOrderList;
+ UINT16 *NewDriverOrderList;
+ UINT16 DriverString[12];
+ UINTN DriverOrderListSize;
+ VOID *Buffer;
+ UINTN BufferSize;
+ UINT8 *Ptr;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ BOOLEAN OptionalDataExist;
+ EFI_STATUS Status;
+
+ OptionalDataExist = FALSE;
+
+ Index = BOpt_GetDriverOptionNumber ();
+ UnicodeSPrint (
+ DriverString,
+ sizeof (DriverString),
+ L"Driver%04x",
+ Index
+ );
+
+ if (*DescriptionData == 0x0000) {
+ StrCpyS (DescriptionData, DESCRIPTION_DATA_SIZE, DriverString);
+ }
+
+ BufferSize = sizeof (UINT32) + sizeof (UINT16) + StrSize (DescriptionData);
+ BufferSize += GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+
+ if (*OptionalData != 0x0000) {
+ OptionalDataExist = TRUE;
+ BufferSize += StrSize (OptionalData);
+ }
+
+ Buffer = AllocateZeroPool (BufferSize);
+ if (NULL == Buffer) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ FreePool (Buffer);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->Deleted = FALSE;
+ NewLoadContext->LoadOptionSize = BufferSize;
+ Ptr = (UINT8 *) Buffer;
+ NewLoadContext->LoadOption = Ptr;
+ *((UINT32 *) Ptr) = LOAD_OPTION_ACTIVE | (ForceReconnect << 1);
+ NewLoadContext->Attributes = *((UINT32 *) Ptr);
+ NewLoadContext->IsActive = TRUE;
+ NewLoadContext->ForceReconnect = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_FORCE_RECONNECT);
+
+ Ptr += sizeof (UINT32);
+ *((UINT16 *) Ptr) = (UINT16) GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+ NewLoadContext->FilePathListLength = *((UINT16 *) Ptr);
+
+ Ptr += sizeof (UINT16);
+ CopyMem (
+ Ptr,
+ DescriptionData,
+ StrSize (DescriptionData)
+ );
+
+ NewLoadContext->Description = AllocateZeroPool (StrSize (DescriptionData));
+ ASSERT (NewLoadContext->Description != NULL);
+ NewMenuEntry->DisplayString = NewLoadContext->Description;
+ CopyMem (
+ NewLoadContext->Description,
+ (VOID *) Ptr,
+ StrSize (DescriptionData)
+ );
+
+ Ptr += StrSize (DescriptionData);
+ CopyMem (
+ Ptr,
+ CallbackData->LoadContext->FilePathList,
+ GetDevicePathSize (CallbackData->LoadContext->FilePathList)
+ );
+
+ NewLoadContext->FilePathList = AllocateZeroPool (GetDevicePathSize (CallbackData->LoadContext->FilePathList));
+ ASSERT (NewLoadContext->FilePathList != NULL);
+
+ CopyMem (
+ NewLoadContext->FilePathList,
+ (VOID *) Ptr,
+ GetDevicePathSize (CallbackData->LoadContext->FilePathList)
+ );
+
+ NewMenuEntry->HelpString = DevicePathToStr (NewLoadContext->FilePathList);
+ NewMenuEntry->OptionNumber = Index;
+ NewMenuEntry->DisplayStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ DriverOptionStrDepository
+ );
+ NewMenuEntry->DisplayStringToken = HiiSetString (HiiHandle, 0, NewMenuEntry->DisplayString, NULL);
+
+ NewMenuEntry->HelpStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ DriverOptionHelpStrDepository
+ );
+ NewMenuEntry->HelpStringToken = HiiSetString (HiiHandle, 0, NewMenuEntry->HelpString, NULL);
+
+ if (OptionalDataExist) {
+ Ptr += (UINT8) GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+
+ CopyMem (
+ Ptr,
+ OptionalData,
+ StrSize (OptionalData)
+ );
+ }
+
+ Status = gRT->SetVariable (
+ DriverString,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BufferSize,
+ Buffer
+ );
+ if (!EFI_ERROR (Status)) {
+ DriverOrderList = BdsLibGetVariableAndSize (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ &DriverOrderListSize
+ );
+ NewDriverOrderList = AllocateZeroPool (DriverOrderListSize + sizeof (UINT16));
+ ASSERT (NewDriverOrderList != NULL);
+ if (DriverOrderList != NULL) {
+ CopyMem (NewDriverOrderList, DriverOrderList, DriverOrderListSize);
+ EfiLibDeleteVariable (L"DriverOrder", &gEfiGlobalVariableGuid);
+ }
+ NewDriverOrderList[DriverOrderListSize / sizeof (UINT16)] = Index;
+
+ Status = gRT->SetVariable (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ DriverOrderListSize + sizeof (UINT16),
+ NewDriverOrderList
+ );
+ if (DriverOrderList != NULL) {
+ FreePool (DriverOrderList);
+ }
+ DriverOrderList = NULL;
+ FreePool (NewDriverOrderList);
+ if (!EFI_ERROR (Status)) {
+ InsertTailList (&DriverOptionMenu.Head, &NewMenuEntry->Link);
+ DriverOptionMenu.MenuNumber++;
+
+ //
+ // Update "change boot order" page used data, append the new add boot
+ // option at the end.
+ //
+ Index = 0;
+ while (CallbackData->BmmFakeNvData.DriverOptionOrder[Index] != 0) {
+ Index++;
+ }
+ CallbackData->BmmFakeNvData.DriverOptionOrder[Index] = (UINT32) (NewMenuEntry->OptionNumber + 1);
+
+ *DescriptionData = 0x0000;
+ *OptionalData = 0x0000;
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ This function create a currently loaded Boot Option from
+ the BMM. It then appends this Boot Option to the end of
+ the "BootOrder" list. It also append this Boot Opotion to the end
+ of BootOptionMenu.
+
+ @param CallbackData The BMM context data.
+ @param NvRamMap The file explorer formset internal state.
+
+ @retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
+ @retval EFI_SUCCESS If function completes successfully.
+
+**/
+EFI_STATUS
+Var_UpdateBootOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN FILE_EXPLORER_NV_DATA *NvRamMap
+ )
+{
+ UINT16 *BootOrderList;
+ UINT16 *NewBootOrderList;
+ UINTN BootOrderListSize;
+ UINT16 BootString[10];
+ VOID *Buffer;
+ UINTN BufferSize;
+ UINT8 *Ptr;
+ UINT16 Index;
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ BOOLEAN OptionalDataExist;
+ EFI_STATUS Status;
+
+ OptionalDataExist = FALSE;
+
+ Index = BOpt_GetBootOptionNumber () ;
+ UnicodeSPrint (BootString, sizeof (BootString), L"Boot%04x", Index);
+
+ if (NvRamMap->BootDescriptionData[0] == 0x0000) {
+ StrCpyS (
+ NvRamMap->BootDescriptionData,
+ sizeof (NvRamMap->BootDescriptionData) / sizeof (NvRamMap->BootDescriptionData[0]),
+ BootString
+ );
+ }
+
+ BufferSize = sizeof (UINT32) + sizeof (UINT16) + StrSize (NvRamMap->BootDescriptionData);
+ BufferSize += GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+
+ if (NvRamMap->BootOptionalData[0] != 0x0000) {
+ OptionalDataExist = TRUE;
+ BufferSize += StrSize (NvRamMap->BootOptionalData);
+ }
+
+ Buffer = AllocateZeroPool (BufferSize);
+ if (NULL == Buffer) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT);
+ if (NULL == NewMenuEntry) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->Deleted = FALSE;
+ NewLoadContext->LoadOptionSize = BufferSize;
+ Ptr = (UINT8 *) Buffer;
+ NewLoadContext->LoadOption = Ptr;
+ *((UINT32 *) Ptr) = LOAD_OPTION_ACTIVE;
+ NewLoadContext->Attributes = *((UINT32 *) Ptr);
+ NewLoadContext->IsActive = TRUE;
+ NewLoadContext->ForceReconnect = (BOOLEAN) (NewLoadContext->Attributes & LOAD_OPTION_FORCE_RECONNECT);
+
+ Ptr += sizeof (UINT32);
+ *((UINT16 *) Ptr) = (UINT16) GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+ NewLoadContext->FilePathListLength = *((UINT16 *) Ptr);
+ Ptr += sizeof (UINT16);
+
+ CopyMem (
+ Ptr,
+ NvRamMap->BootDescriptionData,
+ StrSize (NvRamMap->BootDescriptionData)
+ );
+
+ NewLoadContext->Description = AllocateZeroPool (StrSize (NvRamMap->BootDescriptionData));
+ ASSERT (NewLoadContext->Description != NULL);
+
+ NewMenuEntry->DisplayString = NewLoadContext->Description;
+ CopyMem (
+ NewLoadContext->Description,
+ (VOID *) Ptr,
+ StrSize (NvRamMap->BootDescriptionData)
+ );
+
+ Ptr += StrSize (NvRamMap->BootDescriptionData);
+ CopyMem (
+ Ptr,
+ CallbackData->LoadContext->FilePathList,
+ GetDevicePathSize (CallbackData->LoadContext->FilePathList)
+ );
+
+ NewLoadContext->FilePathList = AllocateZeroPool (GetDevicePathSize (CallbackData->LoadContext->FilePathList));
+ ASSERT (NewLoadContext->FilePathList != NULL);
+
+ CopyMem (
+ NewLoadContext->FilePathList,
+ (VOID *) Ptr,
+ GetDevicePathSize (CallbackData->LoadContext->FilePathList)
+ );
+
+ NewMenuEntry->HelpString = DevicePathToStr (NewLoadContext->FilePathList);
+ NewMenuEntry->OptionNumber = Index;
+ NewMenuEntry->DisplayStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ BootOptionStrDepository
+ );
+ NewMenuEntry->DisplayStringToken = HiiSetString (CallbackData->FeHiiHandle, 0, NewMenuEntry->DisplayString, NULL);
+
+ NewMenuEntry->HelpStringToken = GetStringTokenFromDepository (
+ CallbackData,
+ BootOptionHelpStrDepository
+ );
+ NewMenuEntry->HelpStringToken = HiiSetString (CallbackData->FeHiiHandle, 0, NewMenuEntry->HelpString, NULL);
+
+ if (OptionalDataExist) {
+ Ptr += (UINT8) GetDevicePathSize (CallbackData->LoadContext->FilePathList);
+
+ CopyMem (Ptr, NvRamMap->BootOptionalData, StrSize (NvRamMap->BootOptionalData));
+ }
+
+ Status = gRT->SetVariable (
+ BootString,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BufferSize,
+ Buffer
+ );
+ if (!EFI_ERROR (Status)) {
+
+ BootOrderList = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderListSize
+ );
+ ASSERT (BootOrderList != NULL);
+ NewBootOrderList = AllocateZeroPool (BootOrderListSize + sizeof (UINT16));
+ ASSERT (NewBootOrderList != NULL);
+ CopyMem (NewBootOrderList, BootOrderList, BootOrderListSize);
+ NewBootOrderList[BootOrderListSize / sizeof (UINT16)] = Index;
+
+ if (BootOrderList != NULL) {
+ FreePool (BootOrderList);
+ }
+
+ Status = gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BootOrderListSize + sizeof (UINT16),
+ NewBootOrderList
+ );
+ if (!EFI_ERROR (Status)) {
+
+ FreePool (NewBootOrderList);
+ NewBootOrderList = NULL;
+ InsertTailList (&BootOptionMenu.Head, &NewMenuEntry->Link);
+ BootOptionMenu.MenuNumber++;
+
+ //
+ // Update "change driver order" page used data, append the new add driver
+ // option at the end.
+ //
+ Index = 0;
+ while (CallbackData->BmmFakeNvData.BootOptionOrder[Index] != 0) {
+ Index++;
+ }
+ CallbackData->BmmFakeNvData.BootOptionOrder[Index] = (UINT32) (NewMenuEntry->OptionNumber + 1);
+
+ NvRamMap->BootDescriptionData[0] = 0x0000;
+ NvRamMap->BootOptionalData[0] = 0x0000;
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ This function update the "BootNext" EFI Variable. If there is
+ no "BootNext" specified in BMM, this EFI Variable is deleted.
+ It also update the BMM context data specified the "BootNext"
+ vaule.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @return The EFI variable can be saved. See gRT->SetVariable
+ for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateBootNext (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ BM_MENU_ENTRY *NewMenuEntry;
+ BM_LOAD_CONTEXT *NewLoadContext;
+ BMM_FAKE_NV_DATA *CurrentFakeNVMap;
+ UINT16 Index;
+ EFI_STATUS Status;
+
+ Status = EFI_SUCCESS;
+ CurrentFakeNVMap = &CallbackData->BmmFakeNvData;
+ for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) {
+ NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index);
+ ASSERT (NULL != NewMenuEntry);
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ NewLoadContext->IsBootNext = FALSE;
+ }
+
+ if (CurrentFakeNVMap->BootNext == BootOptionMenu.MenuNumber) {
+ EfiLibDeleteVariable (L"BootNext", &gEfiGlobalVariableGuid);
+ return EFI_SUCCESS;
+ }
+
+ NewMenuEntry = BOpt_GetMenuEntry (
+ &BootOptionMenu,
+ CurrentFakeNVMap->BootNext
+ );
+ ASSERT (NewMenuEntry != NULL);
+
+ NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext;
+ Status = gRT->SetVariable (
+ L"BootNext",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof (UINT16),
+ &NewMenuEntry->OptionNumber
+ );
+ NewLoadContext->IsBootNext = TRUE;
+ CallbackData->BmmOldFakeNVData.BootNext = CurrentFakeNVMap->BootNext;
+ return Status;
+}
+
+/**
+ This function update the "BootOrder" EFI Variable based on
+ BMM Formset's NV map. It then refresh BootOptionMenu
+ with the new "BootOrder" list.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateBootOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ EFI_STATUS Status;
+ UINT16 Index;
+ UINT16 OrderIndex;
+ UINT16 *BootOrderList;
+ UINTN BootOrderListSize;
+ UINT16 OptionNumber;
+
+ BootOrderList = NULL;
+ BootOrderListSize = 0;
+
+ //
+ // First check whether BootOrder is present in current configuration
+ //
+ BootOrderList = BdsLibGetVariableAndSize (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ &BootOrderListSize
+ );
+ if (BootOrderList == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.BootOptionOrder) / sizeof (CallbackData->BmmFakeNvData.BootOptionOrder[0])));
+
+ for (OrderIndex = 0; (OrderIndex < BootOptionMenu.MenuNumber) && (CallbackData->BmmFakeNvData.BootOptionOrder[OrderIndex] != 0); OrderIndex++) {
+ for (Index = OrderIndex; Index < BootOrderListSize / sizeof (UINT16); Index++) {
+ if ((BootOrderList[Index] == (UINT16) (CallbackData->BmmFakeNvData.BootOptionOrder[OrderIndex] - 1)) && (OrderIndex != Index)) {
+ OptionNumber = BootOrderList[Index];
+ CopyMem (&BootOrderList[OrderIndex + 1], &BootOrderList[OrderIndex], (Index - OrderIndex) * sizeof (UINT16));
+ BootOrderList[OrderIndex] = OptionNumber;
+ }
+ }
+ }
+
+ Status = gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ BootOrderListSize,
+ BootOrderList
+ );
+ //
+ // Changing the content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ FreePool (BootOrderList);
+
+ GroupMultipleLegacyBootOption4SameType ();
+
+ BOpt_FreeMenu (&BootOptionMenu);
+ BOpt_GetBootOptions (CallbackData);
+
+ return Status;
+
+}
+
+/**
+ This function update the "DriverOrder" EFI Variable based on
+ BMM Formset's NV map. It then refresh DriverOptionMenu
+ with the new "DriverOrder" list.
+
+ @param CallbackData The BMM context data.
+
+ @retval EFI_SUCCESS The function complete successfully.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
+ @return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
+
+**/
+EFI_STATUS
+Var_UpdateDriverOrder (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ EFI_STATUS Status;
+ UINT16 Index;
+ UINT16 *DriverOrderList;
+ UINT16 *NewDriverOrderList;
+ UINTN DriverOrderListSize;
+
+ DriverOrderList = NULL;
+ DriverOrderListSize = 0;
+
+ //
+ // First check whether DriverOrder is present in current configuration
+ //
+ DriverOrderList = BdsLibGetVariableAndSize (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ &DriverOrderListSize
+ );
+
+ NewDriverOrderList = AllocateZeroPool (DriverOrderListSize);
+
+ if (NewDriverOrderList == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // If exists, delete it to hold new DriverOrder
+ //
+ if (DriverOrderList != NULL) {
+ EfiLibDeleteVariable (L"DriverOrder", &gEfiGlobalVariableGuid);
+ FreePool (DriverOrderList);
+ }
+
+ ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder) / sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder[0])));
+ for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) {
+ NewDriverOrderList[Index] = (UINT16) (CallbackData->BmmFakeNvData.DriverOptionOrder[Index] - 1);
+ }
+
+ Status = gRT->SetVariable (
+ L"DriverOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ DriverOrderListSize,
+ NewDriverOrderList
+ );
+ //
+ // Changing the content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ BOpt_FreeMenu (&DriverOptionMenu);
+ BOpt_GetDriverOptions (CallbackData);
+ return EFI_SUCCESS;
+}
+
+/**
+ Update the legacy BBS boot option. VAR_LEGACY_DEV_ORDER and gEfiLegacyDevOrderVariableGuid EFI Variable
+ is udpated with the new Legacy Boot order. The EFI Variable of "Boot####" and gEfiGlobalVariableGuid
+ is also updated.
+
+ @param CallbackData The context data for BMM.
+ @param FormId The form id.
+
+ @return EFI_SUCCESS The function completed successfully.
+ @retval EFI_NOT_FOUND If VAR_LEGACY_DEV_ORDER and gEfiLegacyDevOrderVariableGuid EFI Variable can be found.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resource
+**/
+EFI_STATUS
+Var_UpdateBBSOption (
+ IN BMM_CALLBACK_DATA *CallbackData,
+ IN EFI_FORM_ID FormId
+ )
+{
+ UINTN Index;
+ UINTN Index2;
+ VOID *BootOptionVar;
+ CHAR16 VarName[100];
+ UINTN OptionSize;
+ EFI_STATUS Status;
+ UINT32 *Attribute;
+ BM_MENU_OPTION *OptionMenu;
+ UINT8 *LegacyDev;
+ UINT8 *VarData;
+ UINTN VarSize;
+ LEGACY_DEV_ORDER_ENTRY *DevOrder;
+ UINT8 *OriginalPtr;
+ UINT8 *DisMap;
+ UINTN Pos;
+ UINTN Bit;
+ UINT16 *NewOrder;
+ UINT16 Tmp;
+ UINT16 *EnBootOption;
+ UINTN EnBootOptionCount;
+ UINT16 *DisBootOption;
+ UINTN DisBootOptionCount;
+
+ DisMap = NULL;
+ NewOrder = NULL;
+
+ switch (FormId) {
+ case FORM_SET_FD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyFDMenu;
+ LegacyDev = CallbackData->BmmFakeNvData.LegacyFD;
+ CallbackData->BbsType = BBS_FLOPPY;
+ break;
+
+ case FORM_SET_HD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyHDMenu;
+ LegacyDev = CallbackData->BmmFakeNvData.LegacyHD;
+ CallbackData->BbsType = BBS_HARDDISK;
+ break;
+
+ case FORM_SET_CD_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyCDMenu;
+ LegacyDev = CallbackData->BmmFakeNvData.LegacyCD;
+ CallbackData->BbsType = BBS_CDROM;
+ break;
+
+ case FORM_SET_NET_ORDER_ID:
+ OptionMenu = (BM_MENU_OPTION *) &LegacyNETMenu;
+ LegacyDev = CallbackData->BmmFakeNvData.LegacyNET;
+ CallbackData->BbsType = BBS_EMBED_NETWORK;
+ break;
+
+ default:
+ ASSERT (FORM_SET_BEV_ORDER_ID == CallbackData->BmmPreviousPageId);
+ OptionMenu = (BM_MENU_OPTION *) &LegacyBEVMenu;
+ LegacyDev = CallbackData->BmmFakeNvData.LegacyBEV;
+ CallbackData->BbsType = BBS_BEV_DEVICE;
+ break;
+ }
+
+ DisMap = CallbackData->BmmOldFakeNVData.DisableMap;
+ Status = EFI_SUCCESS;
+
+
+ //
+ // Update the Variable "LegacyDevOrder"
+ //
+ VarData = (UINT8 *) BdsLibGetVariableAndSize (
+ VAR_LEGACY_DEV_ORDER,
+ &gEfiLegacyDevOrderVariableGuid,
+ &VarSize
+ );
+
+ if (VarData == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ OriginalPtr = VarData;
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) VarData;
+
+ while (VarData < OriginalPtr + VarSize) {
+ if (DevOrder->BbsType == CallbackData->BbsType) {
+ break;
+ }
+
+ VarData += sizeof (BBS_TYPE) + DevOrder->Length;
+ DevOrder = (LEGACY_DEV_ORDER_ENTRY *) VarData;
+ }
+
+ if (VarData >= OriginalPtr + VarSize) {
+ FreePool (OriginalPtr);
+ return EFI_NOT_FOUND;
+ }
+
+ NewOrder = AllocateZeroPool (DevOrder->Length - sizeof (DevOrder->Length));
+ if (NewOrder == NULL) {
+ FreePool (OriginalPtr);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ for (Index = 0; Index < OptionMenu->MenuNumber; Index++) {
+ if (0xFF == LegacyDev[Index]) {
+ break;
+ }
+
+ NewOrder[Index] = LegacyDev[Index];
+ }
+ //
+ // Only the enable/disable state of each boot device with same device type can be changed,
+ // so we can count on the index information in DevOrder.
+ // DisMap bit array is the only reliable source to check a device's en/dis state,
+ // so we use DisMap to set en/dis state of each item in NewOrder array
+ //
+ for (Index2 = 0; Index2 < OptionMenu->MenuNumber; Index2++) {
+ Tmp = (UINT16) (DevOrder->Data[Index2] & 0xFF);
+ Pos = Tmp / 8;
+ Bit = 7 - (Tmp % 8);
+ if ((DisMap[Pos] & (1 << Bit)) != 0) {
+ NewOrder[Index] = (UINT16) (0xFF00 | Tmp);
+ Index++;
+ }
+ }
+
+ CopyMem (
+ DevOrder->Data,
+ NewOrder,
+ DevOrder->Length - sizeof (DevOrder->Length)
+ );
+ FreePool (NewOrder);
+
+ Status = gRT->SetVariable (
+ VAR_LEGACY_DEV_ORDER,
+ &gEfiLegacyDevOrderVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ VarSize,
+ OriginalPtr
+ );
+
+
+ //
+ // Update BootOrder and Boot####.Attribute
+ //
+ // 1. Re-order the Option Number in BootOrder according to Legacy Dev Order
+ //
+ ASSERT (OptionMenu->MenuNumber == DevOrder->Length / sizeof (UINT16) - 1);
+
+ OrderLegacyBootOption4SameType (
+ DevOrder->Data,
+ DevOrder->Length / sizeof (UINT16) - 1,
+ &EnBootOption,
+ &EnBootOptionCount,
+ &DisBootOption,
+ &DisBootOptionCount
+ );
+
+ //
+ // 2. Deactivate the DisBootOption and activate the EnBootOption
+ //
+ for (Index = 0; Index < DisBootOptionCount; Index++) {
+ UnicodeSPrint (VarName, sizeof (VarName), L"Boot%04x", DisBootOption[Index]);
+ BootOptionVar = BdsLibGetVariableAndSize (
+ VarName,
+ &gEfiGlobalVariableGuid,
+ &OptionSize
+ );
+ if (BootOptionVar != NULL) {
+ Attribute = (UINT32 *) BootOptionVar;
+ *Attribute &= ~LOAD_OPTION_ACTIVE;
+
+ Status = gRT->SetVariable (
+ VarName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ OptionSize,
+ BootOptionVar
+ );
+ //
+ // Changing the content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ FreePool (BootOptionVar);
+ }
+ }
+
+ for (Index = 0; Index < EnBootOptionCount; Index++) {
+ UnicodeSPrint (VarName, sizeof (VarName), L"Boot%04x", EnBootOption[Index]);
+ BootOptionVar = BdsLibGetVariableAndSize (
+ VarName,
+ &gEfiGlobalVariableGuid,
+ &OptionSize
+ );
+ if (BootOptionVar != NULL) {
+ Attribute = (UINT32 *) BootOptionVar;
+ *Attribute |= LOAD_OPTION_ACTIVE;
+
+ Status = gRT->SetVariable (
+ VarName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ OptionSize,
+ BootOptionVar
+ );
+ //
+ // Changing the content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ FreePool (BootOptionVar);
+ }
+ }
+
+ BOpt_GetBootOptions (CallbackData);
+
+ FreePool (OriginalPtr);
+ FreePool (EnBootOption);
+ FreePool (DisBootOption);
+ return Status;
+}
+
+/**
+ Update the Text Mode of Console.
+
+ @param CallbackData The context data for BMM.
+
+ @retval EFI_SUCCSS If the Text Mode of Console is updated.
+ @return Other value if the Text Mode of Console is not updated.
+
+**/
+EFI_STATUS
+Var_UpdateConMode (
+ IN BMM_CALLBACK_DATA *CallbackData
+ )
+{
+ EFI_STATUS Status;
+ UINTN Mode;
+ CONSOLE_OUT_MODE ModeInfo;
+
+ Mode = CallbackData->BmmFakeNvData.ConsoleOutMode;
+
+ Status = gST->ConOut->QueryMode (gST->ConOut, Mode, &(ModeInfo.Column), &(ModeInfo.Row));
+ if (!EFI_ERROR(Status)) {
+ Status = PcdSet32S (PcdSetupConOutColumn, (UINT32) ModeInfo.Column);
+ if (!EFI_ERROR (Status)){
+ Status = PcdSet32S (PcdSetupConOutRow, (UINT32) ModeInfo.Row);
+ }
+ }
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.c
new file mode 100644
index 0000000000..9ee063859c
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.c
@@ -0,0 +1,399 @@
+/** @file
+ The platform boot manager reference implementation
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "BootManager.h"
+
+UINT16 mKeyInput;
+LIST_ENTRY mBootOptionsList;
+BDS_COMMON_OPTION *gOption;
+CHAR16 *mDeviceTypeStr[] = {
+ L"Legacy BEV",
+ L"Legacy Floppy",
+ L"Legacy Hard Drive",
+ L"Legacy CD ROM",
+ L"Legacy PCMCIA",
+ L"Legacy USB",
+ L"Legacy Embedded Network",
+ L"Legacy Unknown Device"
+};
+
+
+HII_VENDOR_DEVICE_PATH mBootManagerHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ BOOT_MANAGER_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+BOOT_MANAGER_CALLBACK_DATA gBootManagerPrivate = {
+ BOOT_MANAGER_CALLBACK_DATA_SIGNATURE,
+ NULL,
+ NULL,
+ {
+ FakeExtractConfig,
+ FakeRouteConfig,
+ BootManagerCallback
+ }
+};
+
+/**
+ This call back function is registered with Boot Manager formset.
+ When user selects a boot option, this call back function will
+ be triggered. The boot option is saved for later processing.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+BootManagerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ BDS_COMMON_OPTION *Option;
+ LIST_ENTRY *Link;
+ UINT16 KeyCount;
+
+ if (Action == EFI_BROWSER_ACTION_CHANGED) {
+ if ((Value == NULL) || (ActionRequest == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Initialize the key count
+ //
+ KeyCount = 0;
+
+ for (Link = GetFirstNode (&mBootOptionsList); !IsNull (&mBootOptionsList, Link); Link = GetNextNode (&mBootOptionsList, Link)) {
+ Option = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
+
+ KeyCount++;
+
+ gOption = Option;
+
+ //
+ // Is this device the one chosen?
+ //
+ if (KeyCount == QuestionId) {
+ //
+ // Assigning the returned Key to a global allows the original routine to know what was chosen
+ //
+ mKeyInput = QuestionId;
+
+ //
+ // Request to exit SendForm(), so that we could boot the selected option
+ //
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ break;
+ }
+ }
+
+ return EFI_SUCCESS;
+ }
+
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+}
+
+/**
+
+ Registers HII packages for the Boot Manger to HII Database.
+ It also registers the browser call back function.
+
+ @retval EFI_SUCCESS HII packages for the Boot Manager were registered successfully.
+ @retval EFI_OUT_OF_RESOURCES HII packages for the Boot Manager failed to be registered.
+
+**/
+EFI_STATUS
+InitializeBootManager (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Install Device Path Protocol and Config Access protocol to driver handle
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gBootManagerPrivate.DriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mBootManagerHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &gBootManagerPrivate.ConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Publish our HII data
+ //
+ gBootManagerPrivate.HiiHandle = HiiAddPackages (
+ &gBootManagerFormSetGuid,
+ gBootManagerPrivate.DriverHandle,
+ BootManagerVfrBin,
+ BdsDxeStrings,
+ NULL
+ );
+ if (gBootManagerPrivate.HiiHandle == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ } else {
+ Status = EFI_SUCCESS;
+ }
+ return Status;
+}
+
+/**
+ This function invokes Boot Manager. If all devices have not a chance to be connected,
+ the connect all will be triggered. It then enumerate all boot options. If
+ a boot option from the Boot Manager page is selected, Boot Manager will boot
+ from this boot option.
+
+**/
+VOID
+CallBootManager (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ BDS_COMMON_OPTION *Option;
+ LIST_ENTRY *Link;
+ CHAR16 *ExitData;
+ UINTN ExitDataSize;
+ EFI_STRING_ID Token;
+ EFI_INPUT_KEY Key;
+ CHAR16 *HelpString;
+ UINTN HelpSize;
+ EFI_STRING_ID HelpToken;
+ UINT16 *TempStr;
+ EFI_HII_HANDLE HiiHandle;
+ EFI_BROWSER_ACTION_REQUEST ActionRequest;
+ VOID *StartOpCodeHandle;
+ VOID *EndOpCodeHandle;
+ EFI_IFR_GUID_LABEL *StartLabel;
+ EFI_IFR_GUID_LABEL *EndLabel;
+ UINT16 DeviceType;
+ BOOLEAN IsLegacyOption;
+ BOOLEAN NeedEndOp;
+
+ DeviceType = (UINT16) -1;
+ gOption = NULL;
+ InitializeListHead (&mBootOptionsList);
+
+ //
+ // Connect all prior to entering the platform setup menu.
+ //
+ if (!gConnectAllHappened) {
+ BdsLibConnectAllDriversToAllControllers ();
+ gConnectAllHappened = TRUE;
+ }
+
+ BdsLibEnumerateAllBootOption (&mBootOptionsList);
+
+ //
+ // Group the legacy boot options for the same device type
+ //
+ GroupMultipleLegacyBootOption4SameType ();
+
+ InitializeListHead (&mBootOptionsList);
+ BdsLibBuildOptionFromVar (&mBootOptionsList, L"BootOrder");
+
+ HiiHandle = gBootManagerPrivate.HiiHandle;
+
+ //
+ // Allocate space for creation of UpdateData Buffer
+ //
+ StartOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (StartOpCodeHandle != NULL);
+
+ EndOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (EndOpCodeHandle != NULL);
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ StartLabel->Number = LABEL_BOOT_OPTION;
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ EndLabel->Number = LABEL_BOOT_OPTION_END;
+
+ mKeyInput = 0;
+ NeedEndOp = FALSE;
+ for (Link = GetFirstNode (&mBootOptionsList); !IsNull (&mBootOptionsList, Link); Link = GetNextNode (&mBootOptionsList, Link)) {
+ Option = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
+
+ //
+ // At this stage we are creating a menu entry, thus the Keys are reproduceable
+ //
+ mKeyInput++;
+
+ //
+ // Don't display the hidden/inactive boot option
+ //
+ if (((Option->Attribute & LOAD_OPTION_HIDDEN) != 0) || ((Option->Attribute & LOAD_OPTION_ACTIVE) == 0)) {
+ continue;
+ }
+
+ //
+ // Group the legacy boot option in the sub title created dynamically
+ //
+ IsLegacyOption = (BOOLEAN) (
+ (DevicePathType (Option->DevicePath) == BBS_DEVICE_PATH) &&
+ (DevicePathSubType (Option->DevicePath) == BBS_BBS_DP)
+ );
+
+ if (!IsLegacyOption && NeedEndOp) {
+ NeedEndOp = FALSE;
+ HiiCreateEndOpCode (StartOpCodeHandle);
+ }
+
+ if (IsLegacyOption && DeviceType != ((BBS_BBS_DEVICE_PATH *) Option->DevicePath)->DeviceType) {
+ if (NeedEndOp) {
+ HiiCreateEndOpCode (StartOpCodeHandle);
+ }
+
+ DeviceType = ((BBS_BBS_DEVICE_PATH *) Option->DevicePath)->DeviceType;
+ Token = HiiSetString (
+ HiiHandle,
+ 0,
+ mDeviceTypeStr[
+ MIN (DeviceType & 0xF, ARRAY_SIZE (mDeviceTypeStr) - 1)
+ ],
+ NULL
+ );
+ HiiCreateSubTitleOpCode (StartOpCodeHandle, Token, 0, 0, 1);
+ NeedEndOp = TRUE;
+ }
+
+ ASSERT (Option->Description != NULL);
+
+ Token = HiiSetString (HiiHandle, 0, Option->Description, NULL);
+
+ TempStr = DevicePathToStr (Option->DevicePath);
+ HelpSize = StrSize (TempStr) + StrSize (L"Device Path : ");
+ HelpString = AllocateZeroPool (HelpSize);
+ ASSERT (HelpString != NULL);
+ StrCatS (HelpString, HelpSize / sizeof (CHAR16), L"Device Path : ");
+ StrCatS (HelpString, HelpSize / sizeof (CHAR16), TempStr);
+
+ HelpToken = HiiSetString (HiiHandle, 0, HelpString, NULL);
+
+ HiiCreateActionOpCode (
+ StartOpCodeHandle,
+ mKeyInput,
+ Token,
+ HelpToken,
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+ }
+
+ if (NeedEndOp) {
+ HiiCreateEndOpCode (StartOpCodeHandle);
+ }
+
+ HiiUpdateForm (
+ HiiHandle,
+ &gBootManagerFormSetGuid,
+ BOOT_MANAGER_FORM_ID,
+ StartOpCodeHandle,
+ EndOpCodeHandle
+ );
+
+ HiiFreeOpCodeHandle (StartOpCodeHandle);
+ HiiFreeOpCodeHandle (EndOpCodeHandle);
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &HiiHandle,
+ 1,
+ &gBootManagerFormSetGuid,
+ 0,
+ NULL,
+ &ActionRequest
+ );
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ if (gOption == NULL) {
+ return ;
+ }
+
+ //
+ // Will leave browser, check any reset required change is applied? if yes, reset system
+ //
+ SetupResetReminder ();
+
+ //
+ // Restore to original mode before launching boot option.
+ //
+ BdsSetConsoleMode (FALSE);
+
+ //
+ // parse the selected option
+ //
+ Status = BdsLibBootViaBootOption (gOption, gOption->DevicePath, &ExitDataSize, &ExitData);
+
+ if (!EFI_ERROR (Status)) {
+ gOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_SUCCEEDED));
+ PlatformBdsBootSuccess (gOption);
+ } else {
+ gOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_FAILED));
+ PlatformBdsBootFail (gOption, Status, ExitData, ExitDataSize);
+ gST->ConOut->OutputString (
+ gST->ConOut,
+ GetStringById (STRING_TOKEN (STR_ANY_KEY_CONTINUE))
+ );
+ gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
+ }
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.h
new file mode 100644
index 0000000000..e26147183a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManager.h
@@ -0,0 +1,103 @@
+/** @file
+ The platform boot manager reference implement
+
+Copyright (c) 2004 - 2011, 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 _EFI_BOOT_MANAGER_H_
+#define _EFI_BOOT_MANAGER_H_
+
+#include "Bds.h"
+#include "FrontPage.h"
+
+#define BOOT_MANAGER_FORM_ID 0x1000
+
+#define LABEL_BOOT_OPTION 0x00
+#define LABEL_BOOT_OPTION_END 0x01
+
+//
+// These are the VFR compiler generated data representing our VFR data.
+//
+extern UINT8 BootManagerVfrBin[];
+
+#define BOOT_MANAGER_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('B', 'M', 'C', 'B')
+
+typedef struct {
+ UINTN Signature;
+
+ //
+ // HII relative handles
+ //
+ EFI_HII_HANDLE HiiHandle;
+ EFI_HANDLE DriverHandle;
+
+ //
+ // Produced protocols
+ //
+ EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess;
+} BOOT_MANAGER_CALLBACK_DATA;
+
+/**
+ This call back function is registered with Boot Manager formset.
+ When user selects a boot option, this call back function will
+ be triggered. The boot option is saved for later processing.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+BootManagerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ );
+
+/**
+
+ Registers HII packages for the Boot Manger to HII Database.
+ It also registers the browser call back function.
+
+ @retval EFI_SUCCESS HII packages for the Boot Manager were registered successfully.
+ @retval EFI_OUT_OF_RESOURCES HII packages for the Boot Manager failed to be registered.
+
+**/
+EFI_STATUS
+InitializeBootManager (
+ VOID
+ );
+
+/**
+ This function invokes Boot Manager. If all devices have not a chance to be connected,
+ the connect all will be triggered. It then enumerate all boot options. If
+ a boot option from the Boot Manager page is selected, Boot Manager will boot
+ from this boot option.
+
+**/
+VOID
+CallBootManager (
+ VOID
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerStrings.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerStrings.uni
new file mode 100644
index 0000000000..fbf128bc34
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerStrings.uni
@@ -0,0 +1,33 @@
+///** @file
+//
+// String definitions for BdsPlatform formset.
+//
+// Copyright (c) 2004 - 2011, 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.
+//
+//**/
+
+/=#
+
+#langdef en-US "English"
+#langdef fr-FR "Français"
+
+#string STR_BM_BANNER #language en-US "Boot Manager"
+ #language fr-FR "Boot Manager"
+#string STR_HELP_FOOTER #language en-US "↑ and ↓ to change option, ENTER to select an option, ESC to exit"
+ #language fr-FR "↑ pour ↓ changer l'option, ENTRER choisir une option, ESC pour sortir"
+#string STR_AND #language en-US " and "
+ #language fr-FR " et "
+#string STR_BOOT_OPTION_BANNER #language en-US "Boot Option Menu"
+ #language fr-FR "le Menu d'Option de Botte"
+#string STR_ANY_KEY_CONTINUE #language en-US "Press any key to continue..."
+ #language fr-FR "Appuie n'importe quelle pour continuer..."
+#string STR_LAST_STRING #language en-US ""
+ #language fr-FR ""
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerVfr.Vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerVfr.Vfr
new file mode 100644
index 0000000000..0d8142c17d
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/BootMngr/BootManagerVfr.Vfr
@@ -0,0 +1,50 @@
+///** @file
+//
+// Browser formset.
+//
+// Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+#include <Guid/BdsHii.h>
+
+#define BOOT_MANAGER_FORM_ID 0x1000
+
+#define LABEL_BOOT_OPTION 0x00
+#define LABEL_BOOT_OPTION_END 0x01
+
+#define BOOT_MANAGER_CLASS 0x00
+#define BOOT_MANAGER_SUBCLASS 0x00
+
+formset
+ guid = BOOT_MANAGER_FORMSET_GUID,
+ title = STRING_TOKEN(STR_BM_BANNER),
+ help = STRING_TOKEN(STR_LAST_STRING),
+ classguid = BOOT_MANAGER_FORMSET_GUID,
+
+ form formid = BOOT_MANAGER_FORM_ID,
+ title = STRING_TOKEN(STR_BM_BANNER);
+
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+ subtitle text = STRING_TOKEN(STR_BOOT_OPTION_BANNER);
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+
+ //
+ // This is where we will dynamically add choices for the Boot Manager
+ //
+ label LABEL_BOOT_OPTION;
+ label LABEL_BOOT_OPTION_END;
+
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+ subtitle text = STRING_TOKEN(STR_HELP_FOOTER);
+
+ endform;
+
+endformset;
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Capsules.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Capsules.c
new file mode 100644
index 0000000000..6c7fc7ced4
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Capsules.c
@@ -0,0 +1,233 @@
+/** @file
+ BDS routines to handle capsules.
+
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+#include "Bds.h"
+
+/**
+
+ This routine is called to see if there are any capsules we need to process.
+ If the boot mode is not UPDATE, then we do nothing. Otherwise find the
+ capsule HOBS and produce firmware volumes for them via the DXE service.
+ Then call the dispatcher to dispatch drivers from them. Finally, check
+ the status of the updates.
+
+ This function should be called by BDS in case we need to do some
+ sort of processing even if there is no capsule to process. We
+ need to do this if an earlier update went away and we need to
+ clear the capsule variable so on the next reset PEI does not see it and
+ think there is a capsule available.
+
+ @param BootMode the current boot mode
+
+ @retval EFI_INVALID_PARAMETER boot mode is not correct for an update
+ @retval EFI_SUCCESS There is no error when processing capsule
+
+**/
+EFI_STATUS
+EFIAPI
+BdsProcessCapsules (
+ EFI_BOOT_MODE BootMode
+ )
+{
+ EFI_STATUS Status;
+ EFI_PEI_HOB_POINTERS HobPointer;
+ EFI_CAPSULE_HEADER *CapsuleHeader;
+ UINT32 Size;
+ UINT32 CapsuleNumber;
+ UINT32 CapsuleTotalNumber;
+ EFI_CAPSULE_TABLE *CapsuleTable;
+ UINT32 Index;
+ UINT32 CacheIndex;
+ UINT32 CacheNumber;
+ VOID **CapsulePtr;
+ VOID **CapsulePtrCache;
+ EFI_GUID *CapsuleGuidCache;
+ BOOLEAN NeedReset;
+
+ CapsuleNumber = 0;
+ CapsuleTotalNumber = 0;
+ CacheIndex = 0;
+ CacheNumber = 0;
+ CapsulePtr = NULL;
+ CapsulePtrCache = NULL;
+ CapsuleGuidCache = NULL;
+ NeedReset = FALSE;
+
+ //
+ // We don't do anything else if the boot mode is not flash-update
+ //
+ if (BootMode != BOOT_ON_FLASH_UPDATE) {
+ DEBUG ((EFI_D_ERROR, "Boot mode is not correct for capsule update.\n"));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status = EFI_SUCCESS;
+ //
+ // Find all capsule images from hob
+ //
+ HobPointer.Raw = GetHobList ();
+ while ((HobPointer.Raw = GetNextHob (EFI_HOB_TYPE_UEFI_CAPSULE, HobPointer.Raw)) != NULL) {
+ CapsuleTotalNumber ++;
+ HobPointer.Raw = GET_NEXT_HOB (HobPointer);
+ }
+
+ if (CapsuleTotalNumber == 0) {
+ //
+ // We didn't find a hob, so had no errors.
+ //
+ DEBUG ((EFI_D_ERROR, "We can not find capsule data in capsule update boot mode.\n"));
+ DEBUG ((EFI_D_ERROR, "Please check the followings are correct if unexpected capsule update error happens.\n"));
+ DEBUG ((EFI_D_ERROR, "1. CapsuleX64 is built as X64 module when PEI is IA32 and DXE is X64\n"));
+ DEBUG ((EFI_D_ERROR, "2. Capsule data should persist in memory across a system reset.\n"));
+ PlatformBdsLockNonUpdatableFlash ();
+ return EFI_SUCCESS;
+ }
+
+ //
+ // Init temp Capsule Data table.
+ //
+ CapsulePtr = (VOID **) AllocateZeroPool (sizeof (VOID *) * CapsuleTotalNumber);
+ ASSERT (CapsulePtr != NULL);
+ CapsulePtrCache = (VOID **) AllocateZeroPool (sizeof (VOID *) * CapsuleTotalNumber);
+ ASSERT (CapsulePtrCache != NULL);
+ CapsuleGuidCache = (EFI_GUID *) AllocateZeroPool (sizeof (EFI_GUID) * CapsuleTotalNumber);
+ ASSERT (CapsuleGuidCache != NULL);
+
+ //
+ // Find all capsule images from hob
+ //
+ HobPointer.Raw = GetHobList ();
+ while ((HobPointer.Raw = GetNextHob (EFI_HOB_TYPE_UEFI_CAPSULE, HobPointer.Raw)) != NULL) {
+ CapsulePtr [CapsuleNumber++] = (VOID *) (UINTN) HobPointer.Capsule->BaseAddress;
+ HobPointer.Raw = GET_NEXT_HOB (HobPointer);
+ }
+
+ //
+ //Check the capsule flags,if contains CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE, install
+ //capsuleTable to configure table with EFI_CAPSULE_GUID
+ //
+
+ //
+ // Capsules who have CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE always are used for operating
+ // System to have information persist across a system reset. EFI System Table must
+ // point to an array of capsules that contains the same CapsuleGuid value. And agents
+ // searching for this type capsule will look in EFI System Table and search for the
+ // capsule's Guid and associated pointer to retrieve the data. Two steps below describes
+ // how to sorting the capsules by the unique guid and install the array to EFI System Table.
+ // Firstly, Loop for all coalesced capsules, record unique CapsuleGuids and cache them in an
+ // array for later sorting capsules by CapsuleGuid.
+ //
+ for (Index = 0; Index < CapsuleTotalNumber; Index++) {
+ CapsuleHeader = (EFI_CAPSULE_HEADER*) CapsulePtr [Index];
+ if ((CapsuleHeader->Flags & CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE) != 0) {
+ //
+ // For each capsule, we compare it with known CapsuleGuid in the CacheArray.
+ // If already has the Guid, skip it. Whereas, record it in the CacheArray as
+ // an additional one.
+ //
+ CacheIndex = 0;
+ while (CacheIndex < CacheNumber) {
+ if (CompareGuid(&CapsuleGuidCache[CacheIndex],&CapsuleHeader->CapsuleGuid)) {
+ break;
+ }
+ CacheIndex++;
+ }
+ if (CacheIndex == CacheNumber) {
+ CopyMem(&CapsuleGuidCache[CacheNumber++],&CapsuleHeader->CapsuleGuid,sizeof(EFI_GUID));
+ }
+ }
+ }
+
+ //
+ // Secondly, for each unique CapsuleGuid in CacheArray, gather all coalesced capsules
+ // whose guid is the same as it, and malloc memory for an array which preceding
+ // with UINT32. The array fills with entry point of capsules that have the same
+ // CapsuleGuid, and UINT32 represents the size of the array of capsules. Then install
+ // this array into EFI System Table, so that agents searching for this type capsule
+ // will look in EFI System Table and search for the capsule's Guid and associated
+ // pointer to retrieve the data.
+ //
+ CacheIndex = 0;
+ while (CacheIndex < CacheNumber) {
+ CapsuleNumber = 0;
+ for (Index = 0; Index < CapsuleTotalNumber; Index++) {
+ CapsuleHeader = (EFI_CAPSULE_HEADER*) CapsulePtr [Index];
+ if ((CapsuleHeader->Flags & CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE) != 0) {
+ if (CompareGuid (&CapsuleGuidCache[CacheIndex], &CapsuleHeader->CapsuleGuid)) {
+ //
+ // Cache Caspuleheader to the array, this array is uniqued with certain CapsuleGuid.
+ //
+ CapsulePtrCache[CapsuleNumber++] = (VOID*)CapsuleHeader;
+ }
+ }
+ }
+ if (CapsuleNumber != 0) {
+ Size = sizeof(EFI_CAPSULE_TABLE) + (CapsuleNumber - 1) * sizeof(VOID*);
+ CapsuleTable = AllocateRuntimePool (Size);
+ ASSERT (CapsuleTable != NULL);
+ CapsuleTable->CapsuleArrayNumber = CapsuleNumber;
+ CopyMem(&CapsuleTable->CapsulePtr[0], CapsulePtrCache, CapsuleNumber * sizeof(VOID*));
+ Status = gBS->InstallConfigurationTable (&CapsuleGuidCache[CacheIndex], (VOID*)CapsuleTable);
+ ASSERT_EFI_ERROR (Status);
+ }
+ CacheIndex++;
+ }
+
+ //
+ // Besides ones with CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE flag, all capsules left are
+ // recognized by platform with CapsuleGuid. For general platform driver, UpdateFlash
+ // type is commonly supported, so here only deal with encapsuled FVs capsule. Additional
+ // type capsule transaction could be extended. It depends on platform policy.
+ //
+ for (Index = 0; Index < CapsuleTotalNumber; Index++) {
+ CapsuleHeader = (EFI_CAPSULE_HEADER*) CapsulePtr [Index];
+ if ((CapsuleHeader->Flags & CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE) == 0) {
+ //
+ // Always reset system after all capsule processed if FMP capsule exist
+ //
+ if (CompareGuid (&gEfiFmpCapsuleGuid, &CapsuleHeader->CapsuleGuid)){
+ NeedReset = TRUE;
+ }
+
+ //
+ // Call capsule library to process capsule image.
+ //
+ ProcessCapsuleImage (CapsuleHeader);
+ }
+ }
+
+ if (NeedReset) {
+ Print(L"Capsule Request Cold Reboot.\n");
+
+ for (Index = 5; Index > 0; Index--) {
+ Print(L"\rResetting system in %d seconds ...", Index);
+ gBS->Stall (1000000);
+ }
+
+ gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
+
+ CpuDeadLoop ();
+ }
+
+ PlatformBdsLockNonUpdatableFlash ();
+
+ //
+ // Free the allocated temp memory space.
+ //
+ FreePool (CapsuleGuidCache);
+ FreePool (CapsulePtrCache);
+ FreePool (CapsulePtr);
+
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.c
new file mode 100644
index 0000000000..125c49db5e
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.c
@@ -0,0 +1,2605 @@
+/** @file
+ The platform device manager reference implementation
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "DeviceManager.h"
+
+DEVICE_MANAGER_CALLBACK_DATA gDeviceManagerPrivate = {
+ DEVICE_MANAGER_CALLBACK_DATA_SIGNATURE,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ {
+ FakeExtractConfig,
+ FakeRouteConfig,
+ DeviceManagerCallback
+ },
+ {
+ FakeExtractConfig,
+ FakeRouteConfig,
+ DriverHealthCallback
+ }
+};
+
+#define MAX_MAC_ADDRESS_NODE_LIST_LEN 10
+
+//
+// Which Mac Address string is select
+// it will decide what menu need to show in the NETWORK_DEVICE_FORM_ID form.
+//
+EFI_STRING mSelectedMacAddrString;
+
+//
+// Which form Id need to be show.
+//
+EFI_FORM_ID mNextShowFormId = DEVICE_MANAGER_FORM_ID;
+
+//
+// The Mac Address show in the NETWORK_DEVICE_LIST_FORM_ID
+//
+MAC_ADDRESS_NODE_LIST mMacDeviceList;
+
+DEVICE_MANAGER_MENU_ITEM mDeviceManagerMenuItemTable[] = {
+ { STRING_TOKEN (STR_DISK_DEVICE), EFI_DISK_DEVICE_CLASS },
+ { STRING_TOKEN (STR_VIDEO_DEVICE), EFI_VIDEO_DEVICE_CLASS },
+ { STRING_TOKEN (STR_NETWORK_DEVICE), EFI_NETWORK_DEVICE_CLASS },
+ { STRING_TOKEN (STR_INPUT_DEVICE), EFI_INPUT_DEVICE_CLASS },
+ { STRING_TOKEN (STR_ON_BOARD_DEVICE), EFI_ON_BOARD_DEVICE_CLASS },
+ { STRING_TOKEN (STR_OTHER_DEVICE), EFI_OTHER_DEVICE_CLASS }
+};
+
+HII_VENDOR_DEVICE_PATH mDeviceManagerHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ DEVICE_MANAGER_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+HII_VENDOR_DEVICE_PATH mDriverHealthHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ DRIVER_HEALTH_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+/**
+ This function is invoked if user selected a interactive opcode from Device Manager's
+ Formset. The decision by user is saved to gCallbackKey for later processing. If
+ user set VBIOS, the new value is saved to EFI variable.
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+DeviceManagerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ UINTN CurIndex;
+
+ if (Action != EFI_BROWSER_ACTION_CHANGING) {
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ if (Value == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ gCallbackKey = QuestionId;
+ if ((QuestionId < MAX_KEY_SECTION_LEN + NETWORK_DEVICE_LIST_KEY_OFFSET) && (QuestionId >= NETWORK_DEVICE_LIST_KEY_OFFSET)) {
+ //
+ // If user select the mac address, need to record mac address string to support next form show.
+ //
+ for (CurIndex = 0; CurIndex < mMacDeviceList.CurListLen; CurIndex ++) {
+ if (mMacDeviceList.NodeList[CurIndex].QuestionId == QuestionId) {
+ mSelectedMacAddrString = HiiGetString (gDeviceManagerPrivate.HiiHandle, mMacDeviceList.NodeList[CurIndex].PromptId, NULL);
+ }
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+
+ This function registers HII packages to HII database.
+
+ @retval EFI_SUCCESS HII packages for the Device Manager were registered successfully.
+ @retval EFI_OUT_OF_RESOURCES HII packages for the Device Manager failed to be registered.
+
+**/
+EFI_STATUS
+InitializeDeviceManager (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Install Device Path Protocol and Config Access protocol to driver handle
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gDeviceManagerPrivate.DriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mDeviceManagerHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &gDeviceManagerPrivate.ConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gDeviceManagerPrivate.DriverHealthHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mDriverHealthHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &gDeviceManagerPrivate.DriverHealthConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ mMacDeviceList.CurListLen = 0;
+ mMacDeviceList.MaxListLen = 0;
+
+ return Status;
+}
+
+/**
+ Extract the displayed formset for given HII handle and class guid.
+
+ @param Handle The HII handle.
+ @param SetupClassGuid The class guid specifies which form set will be displayed.
+ @param SkipCount Skip some formsets which has processed before.
+ @param FormSetTitle Formset title string.
+ @param FormSetHelp Formset help string.
+ @param FormSetGuid Return the formset guid for this formset.
+
+ @retval TRUE The formset for given HII handle will be displayed.
+ @return FALSE The formset for given HII handle will not be displayed.
+
+**/
+BOOLEAN
+ExtractDisplayedHiiFormFromHiiHandle (
+ IN EFI_HII_HANDLE Handle,
+ IN EFI_GUID *SetupClassGuid,
+ IN UINTN SkipCount,
+ OUT EFI_STRING_ID *FormSetTitle,
+ OUT EFI_STRING_ID *FormSetHelp,
+ OUT EFI_GUID **FormSetGuid
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ EFI_HII_PACKAGE_LIST_HEADER *HiiPackageList;
+ UINT8 *Package;
+ UINT8 *OpCodeData;
+ UINT32 Offset;
+ UINT32 Offset2;
+ UINT32 PackageListLength;
+ EFI_HII_PACKAGE_HEADER PackageHeader;
+ EFI_GUID *ClassGuid;
+ UINT8 ClassGuidNum;
+
+ ASSERT (Handle != NULL);
+ ASSERT (SetupClassGuid != NULL);
+ ASSERT (FormSetTitle != NULL);
+ ASSERT (FormSetHelp != NULL);
+
+ *FormSetTitle = 0;
+ *FormSetHelp = 0;
+ ClassGuidNum = 0;
+ ClassGuid = NULL;
+
+ //
+ // Get HII PackageList
+ //
+ BufferSize = 0;
+ HiiPackageList = NULL;
+ Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &BufferSize, HiiPackageList);
+ //
+ // Handle is a invalid handle. Check if Handle is corrupted.
+ //
+ ASSERT (Status != EFI_NOT_FOUND);
+ //
+ // The return status should always be EFI_BUFFER_TOO_SMALL as input buffer's size is 0.
+ //
+ ASSERT (Status == EFI_BUFFER_TOO_SMALL);
+
+ HiiPackageList = AllocatePool (BufferSize);
+ ASSERT (HiiPackageList != NULL);
+
+ Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &BufferSize, HiiPackageList);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ //
+ // Get Form package from this HII package List
+ //
+ Offset = sizeof (EFI_HII_PACKAGE_LIST_HEADER);
+ Offset2 = 0;
+ PackageListLength = ReadUnaligned32 (&HiiPackageList->PackageLength);
+
+ while (Offset < PackageListLength) {
+ Package = ((UINT8 *) HiiPackageList) + Offset;
+ CopyMem (&PackageHeader, Package, sizeof (EFI_HII_PACKAGE_HEADER));
+
+ if (PackageHeader.Type == EFI_HII_PACKAGE_FORMS) {
+ //
+ // Search FormSet Opcode in this Form Package
+ //
+ Offset2 = sizeof (EFI_HII_PACKAGE_HEADER);
+ while (Offset2 < PackageHeader.Length) {
+ OpCodeData = Package + Offset2;
+ Offset2 += ((EFI_IFR_OP_HEADER *) OpCodeData)->Length;
+
+ if (((EFI_IFR_OP_HEADER *) OpCodeData)->OpCode == EFI_IFR_FORM_SET_OP) {
+ if (SkipCount != 0) {
+ SkipCount --;
+ continue;
+ }
+
+ if (((EFI_IFR_OP_HEADER *) OpCodeData)->Length > OFFSET_OF (EFI_IFR_FORM_SET, Flags)) {
+ //
+ // Find FormSet OpCode
+ //
+ ClassGuidNum = (UINT8) (((EFI_IFR_FORM_SET *) OpCodeData)->Flags & 0x3);
+ ClassGuid = (EFI_GUID *) (VOID *)(OpCodeData + sizeof (EFI_IFR_FORM_SET));
+ while (ClassGuidNum-- > 0) {
+ if (CompareGuid (SetupClassGuid, ClassGuid)) {
+ CopyMem (FormSetTitle, &((EFI_IFR_FORM_SET *) OpCodeData)->FormSetTitle, sizeof (EFI_STRING_ID));
+ CopyMem (FormSetHelp, &((EFI_IFR_FORM_SET *) OpCodeData)->Help, sizeof (EFI_STRING_ID));
+ *FormSetGuid = AllocateCopyPool (sizeof (EFI_GUID), &((EFI_IFR_FORM_SET *) OpCodeData)->Guid);
+ ASSERT (*FormSetGuid != NULL);
+ FreePool (HiiPackageList);
+ return TRUE;
+ }
+ ClassGuid ++;
+ }
+ } else {
+ CopyMem (FormSetTitle, &((EFI_IFR_FORM_SET *) OpCodeData)->FormSetTitle, sizeof (EFI_STRING_ID));
+ CopyMem (FormSetHelp, &((EFI_IFR_FORM_SET *) OpCodeData)->Help, sizeof (EFI_STRING_ID));
+ *FormSetGuid = AllocateCopyPool (sizeof (EFI_GUID), &((EFI_IFR_FORM_SET *) OpCodeData)->Guid);
+ ASSERT (*FormSetGuid != NULL);
+ FreePool (HiiPackageList);
+ return TRUE;
+ }
+ }
+ }
+ }
+
+ //
+ // Go to next package
+ //
+ Offset += PackageHeader.Length;
+ }
+
+ FreePool (HiiPackageList);
+
+ return FALSE;
+}
+
+/**
+ Get the mac address string from the device path.
+ if the device path has the vlan, get the vanid also.
+
+ @param MacAddressNode Device path begin with mac address
+ @param PBuffer Output string buffer contain mac address.
+
+**/
+BOOLEAN
+GetMacAddressString(
+ IN MAC_ADDR_DEVICE_PATH *MacAddressNode,
+ OUT CHAR16 **PBuffer
+ )
+{
+ UINTN HwAddressSize;
+ UINTN Index;
+ UINT8 *HwAddress;
+ EFI_DEVICE_PATH_PROTOCOL *Node;
+ UINT16 VlanId;
+ CHAR16 *String;
+ UINTN BufferLen;
+
+ VlanId = 0;
+ String = NULL;
+ ASSERT(MacAddressNode != NULL);
+
+ HwAddressSize = sizeof (EFI_MAC_ADDRESS);
+ if (MacAddressNode->IfType == 0x01 || MacAddressNode->IfType == 0x00) {
+ HwAddressSize = 6;
+ }
+
+ //
+ // The output format is MAC:XX:XX:XX:...\XXXX
+ // The size is the Number size + ":" size + Vlan size(\XXXX) + End
+ //
+ BufferLen = (4 + 2 * HwAddressSize + (HwAddressSize - 1) + 5 + 1) * sizeof (CHAR16);
+ String = AllocateZeroPool (BufferLen);
+ if (String == NULL) {
+ return FALSE;
+ }
+
+ *PBuffer = String;
+ StrCpyS (String, BufferLen / sizeof (CHAR16), L"MAC:");
+ String += 4;
+
+ //
+ // Convert the MAC address into a unicode string.
+ //
+ HwAddress = &MacAddressNode->MacAddress.Addr[0];
+ for (Index = 0; Index < HwAddressSize; Index++) {
+ UnicodeValueToStringS (
+ String,
+ BufferLen - ((UINTN)String - (UINTN)*PBuffer),
+ PREFIX_ZERO | RADIX_HEX,
+ *(HwAddress++),
+ 2
+ );
+ String += StrnLenS (String, (BufferLen - ((UINTN)String - (UINTN)*PBuffer)) / sizeof (CHAR16));
+ if (Index < HwAddressSize - 1) {
+ *String++ = L':';
+ }
+ }
+
+ //
+ // If VLAN is configured, it will need extra 5 characters like "\0005".
+ // Plus one unicode character for the null-terminator.
+ //
+ Node = (EFI_DEVICE_PATH_PROTOCOL *)MacAddressNode;
+ while (!IsDevicePathEnd (Node)) {
+ if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) {
+ VlanId = ((VLAN_DEVICE_PATH *) Node)->VlanId;
+ }
+ Node = NextDevicePathNode (Node);
+ }
+
+ if (VlanId != 0) {
+ *String++ = L'\\';
+ UnicodeValueToStringS (
+ String,
+ BufferLen - ((UINTN)String - (UINTN)*PBuffer),
+ PREFIX_ZERO | RADIX_HEX,
+ VlanId,
+ 4
+ );
+ String += StrnLenS (String, (BufferLen - ((UINTN)String - (UINTN)*PBuffer)) / sizeof (CHAR16));
+ }
+
+ //
+ // Null terminate the Unicode string
+ //
+ *String = L'\0';
+
+ return TRUE;
+}
+
+/**
+ Save question id and prompt id to the mac device list.
+ If the same mac address has saved yet, no need to add more.
+
+ @param MacAddrString Mac address string.
+
+ @retval EFI_SUCCESS Add the item is successful.
+ @return Other values if failed to Add the item.
+**/
+BOOLEAN
+AddIdToMacDeviceList (
+ IN EFI_STRING MacAddrString
+ )
+{
+ MENU_INFO_ITEM *TempDeviceList;
+ UINTN Index;
+ EFI_STRING StoredString;
+ EFI_STRING_ID PromptId;
+ EFI_HII_HANDLE HiiHandle;
+
+ HiiHandle = gDeviceManagerPrivate.HiiHandle;
+ TempDeviceList = NULL;
+
+ for (Index = 0; Index < mMacDeviceList.CurListLen; Index ++) {
+ StoredString = HiiGetString (HiiHandle, mMacDeviceList.NodeList[Index].PromptId, NULL);
+ if (StoredString == NULL) {
+ return FALSE;
+ }
+
+ //
+ // Already has save the same mac address to the list.
+ //
+ if (StrCmp (MacAddrString, StoredString) == 0) {
+ return FALSE;
+ }
+ }
+
+ PromptId = HiiSetString(HiiHandle, 0, MacAddrString, NULL);
+ //
+ // If not in the list, save it.
+ //
+ if (mMacDeviceList.MaxListLen > mMacDeviceList.CurListLen + 1) {
+ mMacDeviceList.NodeList[mMacDeviceList.CurListLen].PromptId = PromptId;
+ mMacDeviceList.NodeList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID) (mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET);
+ } else {
+ mMacDeviceList.MaxListLen += MAX_MAC_ADDRESS_NODE_LIST_LEN;
+ if (mMacDeviceList.CurListLen != 0) {
+ TempDeviceList = (MENU_INFO_ITEM *)AllocateCopyPool (sizeof (MENU_INFO_ITEM) * mMacDeviceList.MaxListLen, (VOID *)mMacDeviceList.NodeList);
+ } else {
+ TempDeviceList = (MENU_INFO_ITEM *)AllocatePool (sizeof (MENU_INFO_ITEM) * mMacDeviceList.MaxListLen);
+ }
+
+ if (TempDeviceList == NULL) {
+ return FALSE;
+ }
+ TempDeviceList[mMacDeviceList.CurListLen].PromptId = PromptId;
+ TempDeviceList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID) (mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET);
+
+ if (mMacDeviceList.CurListLen > 0) {
+ FreePool(mMacDeviceList.NodeList);
+ }
+
+ mMacDeviceList.NodeList = TempDeviceList;
+ }
+ mMacDeviceList.CurListLen ++;
+
+ return TRUE;
+}
+
+/**
+ Check the devcie path, try to find whether it has mac address path.
+
+ In this function, first need to check whether this path has mac address path.
+ second, when the mac address device path has find, also need to deicide whether
+ need to add this mac address relate info to the menu.
+
+ @param *Node Input device which need to be check.
+ @param *NeedAddItem Whether need to add the menu in the network device list.
+
+ @retval TRUE Has mac address device path.
+ @retval FALSE NOT Has mac address device path.
+
+**/
+BOOLEAN
+IsMacAddressDevicePath (
+ IN VOID *Node,
+ OUT BOOLEAN *NeedAddItem
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ CHAR16 *Buffer;
+ BOOLEAN ReturnVal;
+
+ ASSERT (Node != NULL);
+ *NeedAddItem = FALSE;
+ ReturnVal = FALSE;
+ Buffer = NULL;
+
+ DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Node;
+
+ //
+ // find the partition device path node
+ //
+ while (!IsDevicePathEnd (DevicePath)) {
+ if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) &&
+ (DevicePathSubType (DevicePath) == MSG_MAC_ADDR_DP)) {
+ ReturnVal = TRUE;
+
+ if (DEVICE_MANAGER_FORM_ID == mNextShowFormId) {
+ *NeedAddItem = TRUE;
+ break;
+ }
+
+ if (!GetMacAddressString((MAC_ADDR_DEVICE_PATH*)DevicePath, &Buffer)) {
+ break;
+ }
+
+ if (NETWORK_DEVICE_FORM_ID == mNextShowFormId) {
+ if (StrCmp (Buffer, mSelectedMacAddrString) == 0) {
+ *NeedAddItem = TRUE;
+ }
+ break;
+ }
+
+ if (NETWORK_DEVICE_LIST_FORM_ID == mNextShowFormId) {
+ //
+ // Same handle may has two network child handle, so the questionid
+ // has the offset of SAME_HANDLE_KEY_OFFSET.
+ //
+ if (AddIdToMacDeviceList (Buffer)) {
+ *NeedAddItem = TRUE;
+ }
+ break;
+ }
+ }
+ DevicePath = NextDevicePathNode (DevicePath);
+ }
+
+ if (Buffer != NULL) {
+ FreePool (Buffer);
+ }
+
+ return ReturnVal;
+}
+
+/**
+ Check to see if the device path is for the network device.
+
+ @param Handle The HII handle which include the mac address device path.
+ @param ItemCount The new add Mac address item count.
+
+ @retval TRUE Need to add new item in the menu.
+ @return FALSE Do not need to add the menu about the network.
+
+**/
+BOOLEAN
+IsNeedAddNetworkMenu (
+ IN EFI_HII_HANDLE Handle,
+ OUT UINTN *ItemCount
+ )
+{
+ EFI_STATUS Status;
+ UINTN EntryCount;
+ UINTN Index;
+ EFI_HANDLE DriverHandle;
+ EFI_HANDLE ControllerHandle;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL *ChildDevicePath;
+ EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer;
+ BOOLEAN IsNeedAdd;
+
+ IsNeedAdd = FALSE;
+ OpenInfoBuffer = NULL;
+ if ((Handle == NULL) || (ItemCount == NULL)) {
+ return FALSE;
+ }
+ *ItemCount = 0;
+
+ Status = gHiiDatabase->GetPackageListHandle (gHiiDatabase, Handle, &DriverHandle);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+ //
+ // Get the device path by the got Driver handle .
+ //
+ Status = gBS->HandleProtocol (DriverHandle, &gEfiDevicePathProtocolGuid, (VOID **) &DevicePath);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+ TmpDevicePath = DevicePath;
+
+ //
+ // Check whether this device path include mac address device path.
+ // If this path has mac address path, get the value whether need
+ // add this info to the menu and return.
+ // Else check more about the child handle devcie path.
+ //
+ if (IsMacAddressDevicePath(TmpDevicePath, &IsNeedAdd)) {
+ if ((NETWORK_DEVICE_LIST_FORM_ID == mNextShowFormId) && IsNeedAdd) {
+ (*ItemCount) = 1;
+ }
+ return IsNeedAdd;
+ }
+
+ //
+ // Search whether this path is the controller path, not he child handle path.
+ // And the child handle has the network devcie connected.
+ //
+ TmpDevicePath = DevicePath;
+ Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &TmpDevicePath, &ControllerHandle);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ if (!IsDevicePathEnd (TmpDevicePath)) {
+ return FALSE;
+ }
+
+ //
+ // Retrieve the list of agents that are consuming the specific protocol
+ // on ControllerHandle.
+ // The buffer point by OpenInfoBuffer need be free at this function.
+ //
+ Status = gBS->OpenProtocolInformation (
+ ControllerHandle,
+ &gEfiPciIoProtocolGuid,
+ &OpenInfoBuffer,
+ &EntryCount
+ );
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ //
+ // Inspect if ChildHandle is one of the agents.
+ //
+ Status = EFI_UNSUPPORTED;
+ for (Index = 0; Index < EntryCount; Index++) {
+ //
+ // Query all the children created by the controller handle's driver
+ //
+ if ((OpenInfoBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) {
+ Status = gBS->OpenProtocol (
+ OpenInfoBuffer[Index].ControllerHandle,
+ &gEfiDevicePathProtocolGuid,
+ (VOID **) &ChildDevicePath,
+ NULL,
+ NULL,
+ EFI_OPEN_PROTOCOL_GET_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ //
+ // Check whether this device path include mac address device path.
+ //
+ if (!IsMacAddressDevicePath(ChildDevicePath, &IsNeedAdd)) {
+ //
+ // If this path not has mac address path, check the other.
+ //
+ continue;
+ } else {
+ //
+ // If need to update the NETWORK_DEVICE_LIST_FORM, try to get more.
+ //
+ if ((NETWORK_DEVICE_LIST_FORM_ID == mNextShowFormId)) {
+ if (IsNeedAdd) {
+ (*ItemCount) += 1;
+ }
+ continue;
+ } else {
+ //
+ // If need to update other form, return whether need to add to the menu.
+ //
+ goto Done;
+ }
+ }
+ }
+ }
+
+Done:
+ if (OpenInfoBuffer != NULL) {
+ FreePool (OpenInfoBuffer);
+ }
+ return IsNeedAdd;
+}
+
+/**
+ Get HiiHandle total number.
+
+ @param HiiHandles The input HiiHandle array.
+
+ @retval the Hiihandle count.
+
+**/
+UINTN
+GetHiiHandleCount (
+ IN EFI_HII_HANDLE *HiiHandles
+ )
+{
+ UINTN Index;
+
+ for (Index = 0; HiiHandles[Index] != NULL; Index++) {
+ }
+
+ return Index;
+}
+
+/**
+ Insert the new HiiHandle + FormsetGuid at the NewPair[InsertOffset].
+
+ @param HiiHandles The input HiiHandle array.
+ @param GuidLists The input form set guid lists.
+ @param ArrayCount The input array count, new array will be arraycount + 1 size.
+ @param Offset The current used HiiHandle's Offset.
+ @param FormSetGuid The new found formset guid.
+
+**/
+VOID
+AdjustArrayData (
+ IN OUT EFI_HII_HANDLE **HiiHandles,
+ IN OUT EFI_GUID ***GuidLists,
+ IN UINTN ArrayCount,
+ IN UINTN Offset,
+ IN EFI_GUID *FormSetGuid
+ )
+{
+ EFI_HII_HANDLE *NewHiiHandles;
+ EFI_GUID **NewGuidLists;
+
+ //
+ // +2 means include the new HiiHandle and the last empty NULL pointer.
+ //
+ NewHiiHandles = AllocateZeroPool ((ArrayCount + 2) * sizeof (EFI_HII_HANDLE));
+ ASSERT (NewHiiHandles != NULL);
+
+ CopyMem (NewHiiHandles, *HiiHandles, Offset * sizeof (EFI_HII_HANDLE));
+ NewHiiHandles[Offset] = NewHiiHandles[Offset - 1];
+ CopyMem (NewHiiHandles + Offset + 1, *HiiHandles + Offset, (ArrayCount - Offset) * sizeof (EFI_HII_HANDLE));
+
+ NewGuidLists = AllocateZeroPool ((ArrayCount + 2) * sizeof (EFI_GUID *));
+ ASSERT (NewGuidLists != NULL);
+
+ CopyMem (NewGuidLists, *GuidLists, Offset * sizeof (EFI_GUID *));
+ NewGuidLists[Offset] = FormSetGuid;
+
+ FreePool (*HiiHandles);
+ *HiiHandles = NewHiiHandles;
+ FreePool (*GuidLists);
+ *GuidLists = NewGuidLists;
+}
+
+/**
+ Call the browser and display the device manager to allow user
+ to configure the platform.
+
+ This function create the dynamic content for device manager. It includes
+ section header for all class of devices, one-of opcode to set VBIOS.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @return Other values if failed to clean up the dynamic content from HII
+ database.
+
+**/
+EFI_STATUS
+CallDeviceManager (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_STRING String;
+ EFI_STRING_ID Token;
+ EFI_STRING_ID TokenHelp;
+ EFI_HII_HANDLE *HiiHandles;
+ EFI_HII_HANDLE HiiHandle;
+ EFI_STRING_ID FormSetTitle;
+ EFI_STRING_ID FormSetHelp;
+ EFI_BROWSER_ACTION_REQUEST ActionRequest;
+ VOID *StartOpCodeHandle;
+ VOID *EndOpCodeHandle;
+ EFI_IFR_GUID_LABEL *StartLabel;
+ EFI_IFR_GUID_LABEL *EndLabel;
+ UINTN NumHandles;
+ EFI_HANDLE *DriverHealthHandles;
+ BOOLEAN AddNetworkMenu;
+ UINTN AddItemCount;
+ UINTN NewStringLen;
+ EFI_STRING NewStringTitle;
+ EFI_GUID **GuidLists;
+ UINTN HandleNum;
+ UINTN SkipCount;
+ EFI_GUID *FormSetGuid;
+
+ GuidLists = NULL;
+ HiiHandles = NULL;
+ Status = EFI_SUCCESS;
+ gCallbackKey = 0;
+ NumHandles = 0;
+ DriverHealthHandles = NULL;
+ AddNetworkMenu = FALSE;
+ AddItemCount = 0;
+ SkipCount = 0;
+ FormSetGuid = NULL;
+
+ //
+ // Connect all prior to entering the platform setup menu.
+ //
+ if (!gConnectAllHappened) {
+ BdsLibConnectAllDriversToAllControllers ();
+ gConnectAllHappened = TRUE;
+ }
+
+ HiiHandle = gDeviceManagerPrivate.HiiHandle;
+ if (HiiHandle == NULL) {
+ //
+ // Publish our HII data.
+ //
+ HiiHandle = HiiAddPackages (
+ &gDeviceManagerFormSetGuid,
+ gDeviceManagerPrivate.DriverHandle,
+ DeviceManagerVfrBin,
+ BdsDxeStrings,
+ NULL
+ );
+ if (HiiHandle == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ gDeviceManagerPrivate.HiiHandle = HiiHandle;
+ }
+
+ //
+ // If need show the Network device list form, clear the old save list first.
+ //
+ if ((mNextShowFormId == NETWORK_DEVICE_LIST_FORM_ID) && (mMacDeviceList.CurListLen > 0)) {
+ mMacDeviceList.CurListLen = 0;
+ }
+
+ //
+ // Update the network device form titile.
+ //
+ if (mNextShowFormId == NETWORK_DEVICE_FORM_ID) {
+ String = HiiGetString (HiiHandle, STRING_TOKEN (STR_FORM_NETWORK_DEVICE_TITLE), NULL);
+ NewStringLen = StrLen(mSelectedMacAddrString) * 2;
+ NewStringLen += (StrLen(String) + 2) * 2;
+ NewStringTitle = AllocatePool (NewStringLen);
+ UnicodeSPrint (NewStringTitle, NewStringLen, L"%s %s", String, mSelectedMacAddrString);
+ HiiSetString (HiiHandle, STRING_TOKEN (STR_FORM_NETWORK_DEVICE_TITLE), NewStringTitle, NULL);
+ FreePool (String);
+ FreePool (NewStringTitle);
+ }
+
+ //
+ // Allocate space for creation of UpdateData Buffer
+ //
+ StartOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (StartOpCodeHandle != NULL);
+
+ EndOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (EndOpCodeHandle != NULL);
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ //
+ // According to the next show Form id(mNextShowFormId) to decide which form need to update.
+ //
+ StartLabel->Number = (UINT16) (LABEL_FORM_ID_OFFSET + mNextShowFormId);
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ EndLabel->Number = LABEL_END;
+
+ //
+ // Get all the Hii handles
+ //
+ HiiHandles = HiiGetHiiHandles (NULL);
+ ASSERT (HiiHandles != NULL);
+
+ HandleNum = GetHiiHandleCount (HiiHandles);
+ GuidLists = AllocateZeroPool ((HandleNum + 1) * sizeof (EFI_GUID *));
+ ASSERT (GuidLists != NULL);
+
+ //
+ // Search for formset of each class type
+ //
+ for (Index = 0; HiiHandles[Index] != NULL; Index++) {
+ //
+ // The QuestionId in the form which will call the driver form has this asssumption.
+ // QuestionId = Handle Index + NETWORK_DEVICE_LIST_KEY_OFFSET;
+ // Different QuestionId at least has the section of NETWORK_DEVICE_LIST_KEY_OFFSET.
+ //
+ ASSERT(Index < MAX_KEY_SECTION_LEN);
+
+ if (!ExtractDisplayedHiiFormFromHiiHandle (HiiHandles[Index], &gEfiHiiPlatformSetupFormsetGuid, SkipCount, &FormSetTitle, &FormSetHelp, &FormSetGuid)) {
+ SkipCount = 0;
+ continue;
+ }
+
+ //
+ // One HiiHandle has more than one formset can be shown,
+ // Insert a new pair of HiiHandle + Guid to the HiiHandles and GuidLists list.
+ //
+ if (SkipCount > 0) {
+ AdjustArrayData (&HiiHandles, &GuidLists, HandleNum, Index + 1, FormSetGuid);
+ HandleNum ++;
+ Index ++;
+ }
+
+ String = HiiGetString (HiiHandles[Index], FormSetTitle, NULL);
+ if (String == NULL) {
+ String = HiiGetString (HiiHandle, STR_MISSING_STRING, NULL);
+ ASSERT (String != NULL);
+ }
+ Token = HiiSetString (HiiHandle, 0, String, NULL);
+ FreePool (String);
+
+ String = HiiGetString (HiiHandles[Index], FormSetHelp, NULL);
+ if (String == NULL) {
+ String = HiiGetString (HiiHandle, STR_MISSING_STRING, NULL);
+ ASSERT (String != NULL);
+ }
+ TokenHelp = HiiSetString (HiiHandle, 0, String, NULL);
+ FreePool (String);
+
+ //
+ // Network device process
+ //
+ if (IsNeedAddNetworkMenu (HiiHandles[Index], &AddItemCount)) {
+ if (mNextShowFormId == DEVICE_MANAGER_FORM_ID) {
+ //
+ // Only show one menu item "Network Config" in the device manger form.
+ //
+ if (!AddNetworkMenu) {
+ AddNetworkMenu = TRUE;
+ HiiCreateGotoOpCode (
+ StartOpCodeHandle,
+ INVALID_FORM_ID,
+ STRING_TOKEN (STR_FORM_NETWORK_DEVICE_LIST_TITLE),
+ STRING_TOKEN (STR_FORM_NETWORK_DEVICE_LIST_HELP),
+ EFI_IFR_FLAG_CALLBACK,
+ (EFI_QUESTION_ID) QUESTION_NETWORK_DEVICE_ID
+ );
+ }
+ } else if (mNextShowFormId == NETWORK_DEVICE_LIST_FORM_ID) {
+ //
+ // In network device list form, same mac address device only show one menu.
+ //
+ while (AddItemCount > 0) {
+ HiiCreateGotoOpCode (
+ StartOpCodeHandle,
+ INVALID_FORM_ID,
+ mMacDeviceList.NodeList[mMacDeviceList.CurListLen - AddItemCount].PromptId,
+ STRING_TOKEN (STR_NETWORK_DEVICE_HELP),
+ EFI_IFR_FLAG_CALLBACK,
+ mMacDeviceList.NodeList[mMacDeviceList.CurListLen - AddItemCount].QuestionId
+ );
+ AddItemCount -= 1;
+ }
+ } else if (mNextShowFormId == NETWORK_DEVICE_FORM_ID) {
+ //
+ // In network device form, only the selected mac address device need to be show.
+ //
+ HiiCreateGotoOpCode (
+ StartOpCodeHandle,
+ INVALID_FORM_ID,
+ Token,
+ TokenHelp,
+ EFI_IFR_FLAG_CALLBACK,
+ (EFI_QUESTION_ID) (Index + DEVICE_KEY_OFFSET)
+ );
+ }
+ } else {
+ //
+ //
+ // Not network device process, only need to show at device manger form.
+ //
+ if (mNextShowFormId == DEVICE_MANAGER_FORM_ID) {
+ HiiCreateGotoOpCode (
+ StartOpCodeHandle,
+ INVALID_FORM_ID,
+ Token,
+ TokenHelp,
+ EFI_IFR_FLAG_CALLBACK,
+ (EFI_QUESTION_ID) (Index + DEVICE_KEY_OFFSET)
+ );
+ }
+ }
+
+ //
+ // Try to find more formset in this HiiHandle.
+ //
+ SkipCount++;
+ Index--;
+ }
+
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiDriverHealthProtocolGuid,
+ NULL,
+ &NumHandles,
+ &DriverHealthHandles
+ );
+
+ //
+ // If there are no drivers installed driver health protocol, do not create driver health entry in UI
+ //
+ if (NumHandles != 0) {
+ //
+ // If driver health protocol is installed, create Driver Health subtitle and entry
+ //
+ HiiCreateSubTitleOpCode (StartOpCodeHandle, STRING_TOKEN (STR_DM_DRIVER_HEALTH_TITLE), 0, 0, 0);
+ HiiCreateGotoOpCode (
+ StartOpCodeHandle,
+ DRIVER_HEALTH_FORM_ID,
+ STRING_TOKEN(STR_DRIVER_HEALTH_ALL_HEALTHY), // Prompt text
+ STRING_TOKEN(STR_DRIVER_HEALTH_STATUS_HELP), // Help text
+ EFI_IFR_FLAG_CALLBACK,
+ DEVICE_MANAGER_KEY_DRIVER_HEALTH // Question ID
+ );
+
+ //
+ // Check All Driver health status
+ //
+ if (!PlaformHealthStatusCheck ()) {
+ //
+ // At least one driver in the platform are not in healthy status
+ //
+ HiiSetString (HiiHandle, STRING_TOKEN (STR_DRIVER_HEALTH_ALL_HEALTHY), GetStringById (STRING_TOKEN (STR_DRIVER_NOT_HEALTH)), NULL);
+ } else {
+ //
+ // For the string of STR_DRIVER_HEALTH_ALL_HEALTHY previously has been updated and we need to update it while re-entry.
+ //
+ HiiSetString (HiiHandle, STRING_TOKEN (STR_DRIVER_HEALTH_ALL_HEALTHY), GetStringById (STRING_TOKEN (STR_DRIVER_HEALTH_ALL_HEALTHY)), NULL);
+ }
+ }
+
+ HiiUpdateForm (
+ HiiHandle,
+ &gDeviceManagerFormSetGuid,
+ mNextShowFormId,
+ StartOpCodeHandle,
+ EndOpCodeHandle
+ );
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &HiiHandle,
+ 1,
+ &gDeviceManagerFormSetGuid,
+ mNextShowFormId,
+ NULL,
+ &ActionRequest
+ );
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ //
+ // We will have returned from processing a callback, selected
+ // a target to display
+ //
+ if ((gCallbackKey >= DEVICE_KEY_OFFSET)) {
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &HiiHandles[gCallbackKey - DEVICE_KEY_OFFSET],
+ 1,
+ GuidLists[gCallbackKey - DEVICE_KEY_OFFSET],
+ 0,
+ NULL,
+ &ActionRequest
+ );
+
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ //
+ // Force return to Device Manager
+ //
+ gCallbackKey = FRONT_PAGE_KEY_DEVICE_MANAGER;
+ goto Done;
+ }
+
+ //
+ // Driver Health item chose.
+ //
+ if (gCallbackKey == DEVICE_MANAGER_KEY_DRIVER_HEALTH) {
+ CallDriverHealth ();
+ //
+ // Force return to Device Manager
+ //
+ gCallbackKey = FRONT_PAGE_KEY_DEVICE_MANAGER;
+ goto Done;
+ }
+
+ //
+ // Enter from device manager and into the network device list.
+ //
+ if (gCallbackKey == QUESTION_NETWORK_DEVICE_ID) {
+ mNextShowFormId = NETWORK_DEVICE_LIST_FORM_ID;
+ gCallbackKey = FRONT_PAGE_KEY_DEVICE_MANAGER;
+ goto Done;
+ }
+
+ //
+ // In this case, go from the network device list to the specify device.
+ //
+ if ((gCallbackKey < MAX_KEY_SECTION_LEN + NETWORK_DEVICE_LIST_KEY_OFFSET ) && (gCallbackKey >= NETWORK_DEVICE_LIST_KEY_OFFSET)) {
+ mNextShowFormId = NETWORK_DEVICE_FORM_ID;
+ gCallbackKey = FRONT_PAGE_KEY_DEVICE_MANAGER;
+ goto Done;
+ }
+
+ //
+ // Select the ESC, the gCallbackKey == 0.
+ //
+ if(mNextShowFormId - 1 < DEVICE_MANAGER_FORM_ID) {
+ mNextShowFormId = DEVICE_MANAGER_FORM_ID;
+ } else {
+ mNextShowFormId = (UINT16) (mNextShowFormId - 1);
+ gCallbackKey = FRONT_PAGE_KEY_DEVICE_MANAGER;
+ }
+
+Done:
+ //
+ // Remove our packagelist from HII database.
+ //
+ HiiRemovePackages (HiiHandle);
+ gDeviceManagerPrivate.HiiHandle = NULL;
+
+ HiiFreeOpCodeHandle (StartOpCodeHandle);
+ HiiFreeOpCodeHandle (EndOpCodeHandle);
+ FreePool (HiiHandles);
+
+ for (Index = 0; Index < HandleNum; Index++) {
+ if (GuidLists[Index] != NULL) {
+ FreePool (GuidLists[Index]);
+ }
+ }
+ FreePool (GuidLists);
+
+ return Status;
+}
+
+/**
+ This function is invoked if user selected a interactive opcode from Driver Health's
+ Formset. The decision by user is saved to gCallbackKey for later processing.
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+DriverHealthCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ if (Action == EFI_BROWSER_ACTION_CHANGED) {
+ if ((Value == NULL) || (ActionRequest == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ gCallbackKey = QuestionId;
+
+ //
+ // Request to exit SendForm(), so as to switch to selected form
+ //
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+
+ return EFI_SUCCESS;
+ }
+
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Collect and display the platform's driver health relative information, allow user to do interactive
+ operation while the platform is unhealthy.
+
+ This function display a form which divided into two parts. The one list all modules which has installed
+ driver health protocol. The list usually contain driver name, controller name, and it's health info.
+ While the driver name can't be retrieved, will use device path as backup. The other part of the form provide
+ a choice to the user to repair all platform.
+
+**/
+VOID
+CallDriverHealth (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_HII_HANDLE HiiHandle;
+ EFI_BROWSER_ACTION_REQUEST ActionRequest;
+ EFI_IFR_GUID_LABEL *StartLabel;
+ EFI_IFR_GUID_LABEL *StartLabelRepair;
+ EFI_IFR_GUID_LABEL *EndLabel;
+ EFI_IFR_GUID_LABEL *EndLabelRepair;
+ VOID *StartOpCodeHandle;
+ VOID *EndOpCodeHandle;
+ VOID *StartOpCodeHandleRepair;
+ VOID *EndOpCodeHandleRepair;
+ UINTN Index;
+ EFI_STRING_ID Token;
+ EFI_STRING_ID TokenHelp;
+ EFI_STRING String;
+ EFI_STRING TmpString;
+ EFI_STRING DriverName;
+ EFI_STRING ControllerName;
+ LIST_ENTRY DriverHealthList;
+ DRIVER_HEALTH_INFO *DriverHealthInfo;
+ LIST_ENTRY *Link;
+ EFI_DEVICE_PATH_PROTOCOL *DriverDevicePath;
+ BOOLEAN RebootRequired;
+ BOOLEAN IsControllerNameEmpty;
+ UINTN StringSize;
+
+ Index = 0;
+ DriverHealthInfo = NULL;
+ DriverDevicePath = NULL;
+ IsControllerNameEmpty = FALSE;
+ InitializeListHead (&DriverHealthList);
+
+ HiiHandle = gDeviceManagerPrivate.DriverHealthHiiHandle;
+ if (HiiHandle == NULL) {
+ //
+ // Publish Driver Health HII data.
+ //
+ HiiHandle = HiiAddPackages (
+ &gDeviceManagerFormSetGuid,
+ gDeviceManagerPrivate.DriverHealthHandle,
+ DriverHealthVfrBin,
+ BdsDxeStrings,
+ NULL
+ );
+ if (HiiHandle == NULL) {
+ return;
+ }
+
+ gDeviceManagerPrivate.DriverHealthHiiHandle = HiiHandle;
+ }
+
+ //
+ // Allocate space for creation of UpdateData Buffer
+ //
+ StartOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (StartOpCodeHandle != NULL);
+
+ EndOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (EndOpCodeHandle != NULL);
+
+ StartOpCodeHandleRepair = HiiAllocateOpCodeHandle ();
+ ASSERT (StartOpCodeHandleRepair != NULL);
+
+ EndOpCodeHandleRepair = HiiAllocateOpCodeHandle ();
+ ASSERT (EndOpCodeHandleRepair != NULL);
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ StartLabel->Number = LABEL_DRIVER_HEALTH;
+
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ StartLabelRepair = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandleRepair, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ StartLabelRepair->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ StartLabelRepair->Number = LABEL_DRIVER_HEALTH_REAPIR_ALL;
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ EndLabel->Number = LABEL_DRIVER_HEALTH_END;
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ EndLabelRepair = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandleRepair, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ EndLabelRepair->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ EndLabelRepair->Number = LABEL_DRIVER_HEALTH_REAPIR_ALL_END;
+
+ HiiCreateSubTitleOpCode (StartOpCodeHandle, STRING_TOKEN (STR_DH_STATUS_LIST), 0, 0, 1);
+
+ Status = GetAllControllersHealthStatus (&DriverHealthList);
+ ASSERT (Status != EFI_OUT_OF_RESOURCES);
+
+ Link = GetFirstNode (&DriverHealthList);
+
+ while (!IsNull (&DriverHealthList, Link)) {
+ DriverHealthInfo = DEVICE_MANAGER_HEALTH_INFO_FROM_LINK (Link);
+
+ Status = DriverHealthGetDriverName (DriverHealthInfo->DriverHandle, &DriverName);
+ if (EFI_ERROR (Status)) {
+ //
+ // Can not get the Driver name, so use the Device path
+ //
+ DriverDevicePath = DevicePathFromHandle (DriverHealthInfo->DriverHandle);
+ DriverName = DevicePathToStr (DriverDevicePath);
+ }
+ StringSize = StrSize (DriverName);
+
+ Status = DriverHealthGetControllerName (
+ DriverHealthInfo->DriverHandle,
+ DriverHealthInfo->ControllerHandle,
+ DriverHealthInfo->ChildHandle,
+ &ControllerName
+ );
+
+ if (!EFI_ERROR (Status)) {
+ IsControllerNameEmpty = FALSE;
+ StringSize += StrLen (L" ") * sizeof(CHAR16);
+ StringSize += StrLen (ControllerName) * sizeof(CHAR16);
+ } else {
+ IsControllerNameEmpty = TRUE;
+ }
+
+ //
+ // Add the message of the Module itself provided after the string item.
+ //
+ if ((DriverHealthInfo->MessageList != NULL) && (DriverHealthInfo->MessageList->StringId != 0)) {
+ TmpString = HiiGetString (
+ DriverHealthInfo->MessageList->HiiHandle,
+ DriverHealthInfo->MessageList->StringId,
+ NULL
+ );
+ ASSERT (TmpString != NULL);
+
+ StringSize += StrLen (L" ") * sizeof(CHAR16);
+ StringSize += StrLen (TmpString) * sizeof(CHAR16);
+
+ String = (EFI_STRING) AllocateZeroPool (StringSize);
+ ASSERT (String != NULL);
+
+ StrCpyS (String, StringSize / sizeof(CHAR16), DriverName);
+ if (!IsControllerNameEmpty) {
+ StrCatS (String, StringSize / sizeof(CHAR16), L" ");
+ StrCatS (String, StringSize / sizeof(CHAR16), ControllerName);
+ }
+
+ StrCatS (String, StringSize / sizeof(CHAR16), L" ");
+ StrCatS (String, StringSize / sizeof(CHAR16), TmpString);
+
+ } else {
+ //
+ // Update the string will be displayed base on the driver's health status
+ //
+ switch(DriverHealthInfo->HealthStatus) {
+ case EfiDriverHealthStatusRepairRequired:
+ TmpString = GetStringById (STRING_TOKEN (STR_REPAIR_REQUIRED));
+ break;
+ case EfiDriverHealthStatusConfigurationRequired:
+ TmpString = GetStringById (STRING_TOKEN (STR_CONFIGURATION_REQUIRED));
+ break;
+ case EfiDriverHealthStatusFailed:
+ TmpString = GetStringById (STRING_TOKEN (STR_OPERATION_FAILED));
+ break;
+ case EfiDriverHealthStatusReconnectRequired:
+ TmpString = GetStringById (STRING_TOKEN (STR_RECONNECT_REQUIRED));
+ break;
+ case EfiDriverHealthStatusRebootRequired:
+ TmpString = GetStringById (STRING_TOKEN (STR_REBOOT_REQUIRED));
+ break;
+ default:
+ TmpString = GetStringById (STRING_TOKEN (STR_DRIVER_HEALTH_HEALTHY));
+ break;
+ }
+ ASSERT (TmpString != NULL);
+
+ StringSize += StrLen (TmpString) * sizeof(CHAR16);
+
+ String = (EFI_STRING) AllocateZeroPool (StringSize);
+ ASSERT (String != NULL);
+
+ StrCpyS (String, StringSize / sizeof (CHAR16), DriverName);
+ if (!IsControllerNameEmpty) {
+ StrCatS (String, StringSize / sizeof (CHAR16), L" ");
+ StrCatS (String, StringSize / sizeof (CHAR16), ControllerName);
+ }
+
+ StrCatS (String, StringSize / sizeof (CHAR16), TmpString);
+ }
+
+ FreePool (TmpString);
+
+ Token = HiiSetString (HiiHandle, 0, String, NULL);
+ FreePool (String);
+
+ TokenHelp = HiiSetString (HiiHandle, 0, GetStringById( STRING_TOKEN (STR_DH_REPAIR_SINGLE_HELP)), NULL);
+
+ HiiCreateActionOpCode (
+ StartOpCodeHandle,
+ (EFI_QUESTION_ID) (Index + DRIVER_HEALTH_KEY_OFFSET),
+ Token,
+ TokenHelp,
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+ Index++;
+ Link = GetNextNode (&DriverHealthList, Link);
+ }
+
+ //
+ // Add End Opcode for Subtitle
+ //
+ HiiCreateEndOpCode (StartOpCodeHandle);
+
+ HiiCreateSubTitleOpCode (StartOpCodeHandleRepair, STRING_TOKEN (STR_DRIVER_HEALTH_REPAIR_ALL), 0, 0, 1);
+ TokenHelp = HiiSetString (HiiHandle, 0, GetStringById( STRING_TOKEN (STR_DH_REPAIR_ALL_HELP)), NULL);
+
+ if (PlaformHealthStatusCheck ()) {
+ //
+ // No action need to do for the platform
+ //
+ Token = HiiSetString (HiiHandle, 0, GetStringById( STRING_TOKEN (STR_DRIVER_HEALTH_ALL_HEALTHY)), NULL);
+ HiiCreateActionOpCode (
+ StartOpCodeHandleRepair,
+ 0,
+ Token,
+ TokenHelp,
+ EFI_IFR_FLAG_READ_ONLY,
+ 0
+ );
+ } else {
+ //
+ // Create ActionOpCode only while the platform need to do health related operation.
+ //
+ Token = HiiSetString (HiiHandle, 0, GetStringById( STRING_TOKEN (STR_DH_REPAIR_ALL_TITLE)), NULL);
+ HiiCreateActionOpCode (
+ StartOpCodeHandleRepair,
+ (EFI_QUESTION_ID) DRIVER_HEALTH_REPAIR_ALL_KEY,
+ Token,
+ TokenHelp,
+ EFI_IFR_FLAG_CALLBACK,
+ 0
+ );
+ }
+
+ HiiCreateEndOpCode (StartOpCodeHandleRepair);
+
+ Status = HiiUpdateForm (
+ HiiHandle,
+ &gDriverHealthFormSetGuid,
+ DRIVER_HEALTH_FORM_ID,
+ StartOpCodeHandle,
+ EndOpCodeHandle
+ );
+ ASSERT (Status != EFI_NOT_FOUND);
+ ASSERT (Status != EFI_BUFFER_TOO_SMALL);
+
+ Status = HiiUpdateForm (
+ HiiHandle,
+ &gDriverHealthFormSetGuid,
+ DRIVER_HEALTH_FORM_ID,
+ StartOpCodeHandleRepair,
+ EndOpCodeHandleRepair
+ );
+ ASSERT (Status != EFI_NOT_FOUND);
+ ASSERT (Status != EFI_BUFFER_TOO_SMALL);
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &HiiHandle,
+ 1,
+ &gDriverHealthFormSetGuid,
+ DRIVER_HEALTH_FORM_ID,
+ NULL,
+ &ActionRequest
+ );
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ //
+ // We will have returned from processing a callback - user either hit ESC to exit, or selected
+ // a target to display.
+ // Process the diver health status states here.
+ //
+ if (gCallbackKey >= DRIVER_HEALTH_KEY_OFFSET && gCallbackKey != DRIVER_HEALTH_REPAIR_ALL_KEY) {
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+
+ Link = GetFirstNode (&DriverHealthList);
+ Index = 0;
+
+ while (!IsNull (&DriverHealthList, Link)) {
+ //
+ // Got the item relative node in the List
+ //
+ if (Index == (gCallbackKey - DRIVER_HEALTH_KEY_OFFSET)) {
+ DriverHealthInfo = DEVICE_MANAGER_HEALTH_INFO_FROM_LINK (Link);
+ //
+ // Process the driver's healthy status for the specify module
+ //
+ RebootRequired = FALSE;
+ ProcessSingleControllerHealth (
+ DriverHealthInfo->DriverHealth,
+ DriverHealthInfo->ControllerHandle,
+ DriverHealthInfo->ChildHandle,
+ DriverHealthInfo->HealthStatus,
+ &(DriverHealthInfo->MessageList),
+ DriverHealthInfo->HiiHandle,
+ &RebootRequired
+ );
+ if (RebootRequired) {
+ gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL);
+ }
+ break;
+ }
+ Index++;
+ Link = GetNextNode (&DriverHealthList, Link);
+ }
+
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ //
+ // Force return to the form of Driver Health in Device Manager
+ //
+ gCallbackKey = DRIVER_HEALTH_RETURN_KEY;
+ }
+
+ //
+ // Repair the whole platform
+ //
+ if (gCallbackKey == DRIVER_HEALTH_REPAIR_ALL_KEY) {
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+
+ PlatformRepairAll (&DriverHealthList);
+
+ gCallbackKey = DRIVER_HEALTH_RETURN_KEY;
+ }
+
+ //
+ // Remove driver health packagelist from HII database.
+ //
+ HiiRemovePackages (HiiHandle);
+ gDeviceManagerPrivate.DriverHealthHiiHandle = NULL;
+
+ //
+ // Free driver health info list
+ //
+ while (!IsListEmpty (&DriverHealthList)) {
+
+ Link = GetFirstNode(&DriverHealthList);
+ DriverHealthInfo = DEVICE_MANAGER_HEALTH_INFO_FROM_LINK (Link);
+ RemoveEntryList (Link);
+
+ if (DriverHealthInfo->MessageList != NULL) {
+ FreePool(DriverHealthInfo->MessageList);
+ FreePool (DriverHealthInfo);
+ }
+ }
+
+ HiiFreeOpCodeHandle (StartOpCodeHandle);
+ HiiFreeOpCodeHandle (EndOpCodeHandle);
+ HiiFreeOpCodeHandle (StartOpCodeHandleRepair);
+ HiiFreeOpCodeHandle (EndOpCodeHandleRepair);
+
+ if (gCallbackKey == DRIVER_HEALTH_RETURN_KEY) {
+ //
+ // Force return to Driver Health Form
+ //
+ gCallbackKey = DEVICE_MANAGER_KEY_DRIVER_HEALTH;
+ CallDriverHealth ();
+ }
+}
+
+
+/**
+ Check the Driver Health status of a single controller and try to process it if not healthy.
+
+ This function called by CheckAllControllersHealthStatus () function in order to process a specify
+ contoller's health state.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health information.
+ @param DriverHandle The handle of driver.
+ @param ControllerHandle The class guid specifies which form set will be displayed.
+ @param ChildHandle The handle of the child controller to retrieve the health
+ status on. This is an optional parameter that may be NULL.
+ @param DriverHealth A pointer to the EFI_DRIVER_HEALTH_PROTOCOL instance.
+ @param HealthStatus The health status of the controller.
+
+ @retval EFI_INVALID_PARAMETER HealthStatus or DriverHealth is NULL.
+ @retval HealthStatus The Health status of specify controller.
+ @retval EFI_OUT_OF_RESOURCES The list of Driver Health Protocol handles can not be retrieved.
+ @retval EFI_NOT_FOUND No controller in the platform install Driver Health Protocol.
+ @retval EFI_SUCCESS The Health related operation has been taken successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+GetSingleControllerHealthStatus (
+ IN OUT LIST_ENTRY *DriverHealthList,
+ IN EFI_HANDLE DriverHandle,
+ IN EFI_HANDLE ControllerHandle, OPTIONAL
+ IN EFI_HANDLE ChildHandle, OPTIONAL
+ IN EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth,
+ IN EFI_DRIVER_HEALTH_STATUS *HealthStatus
+ )
+{
+ EFI_STATUS Status;
+ EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList;
+ EFI_HII_HANDLE FormHiiHandle;
+ DRIVER_HEALTH_INFO *DriverHealthInfo;
+
+ if (HealthStatus == NULL) {
+ //
+ // If HealthStatus is NULL, then return EFI_INVALID_PARAMETER
+ //
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Assume the HealthStatus is healthy
+ //
+ *HealthStatus = EfiDriverHealthStatusHealthy;
+
+ if (DriverHealth == NULL) {
+ //
+ // If DriverHealth is NULL, then return EFI_INVALID_PARAMETER
+ //
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (ControllerHandle == NULL) {
+ //
+ // If ControllerHandle is NULL, the return the cumulative health status of the driver
+ //
+ Status = DriverHealth->GetHealthStatus (DriverHealth, NULL, NULL, HealthStatus, NULL, NULL);
+ if (*HealthStatus == EfiDriverHealthStatusHealthy) {
+ //
+ // Add the driver health related information into the list
+ //
+ DriverHealthInfo = AllocateZeroPool (sizeof (DRIVER_HEALTH_INFO));
+ if (DriverHealthInfo == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ DriverHealthInfo->Signature = DEVICE_MANAGER_DRIVER_HEALTH_INFO_SIGNATURE;
+ DriverHealthInfo->DriverHandle = DriverHandle;
+ DriverHealthInfo->ControllerHandle = NULL;
+ DriverHealthInfo->ChildHandle = NULL;
+ DriverHealthInfo->HiiHandle = NULL;
+ DriverHealthInfo->DriverHealth = DriverHealth;
+ DriverHealthInfo->MessageList = NULL;
+ DriverHealthInfo->HealthStatus = *HealthStatus;
+
+ InsertTailList (DriverHealthList, &DriverHealthInfo->Link);
+ }
+ return Status;
+ }
+
+ MessageList = NULL;
+ FormHiiHandle = NULL;
+
+ //
+ // Collect the health status with the optional HII message list
+ //
+ Status = DriverHealth->GetHealthStatus (DriverHealth, ControllerHandle, ChildHandle, HealthStatus, &MessageList, &FormHiiHandle);
+
+ if (EFI_ERROR (Status)) {
+ //
+ // If the health status could not be retrieved, then return immediately
+ //
+ return Status;
+ }
+
+ //
+ // Add the driver health related information into the list
+ //
+ DriverHealthInfo = AllocateZeroPool (sizeof (DRIVER_HEALTH_INFO));
+ if (DriverHealthInfo == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ DriverHealthInfo->Signature = DEVICE_MANAGER_DRIVER_HEALTH_INFO_SIGNATURE;
+ DriverHealthInfo->DriverHandle = DriverHandle;
+ DriverHealthInfo->ControllerHandle = ControllerHandle;
+ DriverHealthInfo->ChildHandle = ChildHandle;
+ DriverHealthInfo->HiiHandle = FormHiiHandle;
+ DriverHealthInfo->DriverHealth = DriverHealth;
+ DriverHealthInfo->MessageList = MessageList;
+ DriverHealthInfo->HealthStatus = *HealthStatus;
+
+ InsertTailList (DriverHealthList, &DriverHealthInfo->Link);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Collects all the EFI Driver Health Protocols currently present in the EFI Handle Database,
+ and queries each EFI Driver Health Protocol to determine if one or more of the controllers
+ managed by each EFI Driver Health Protocol instance are not healthy.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health
+ information.
+
+ @retval EFI_NOT_FOUND No controller in the platform install Driver Health Protocol.
+ @retval EFI_SUCCESS All the controllers in the platform are healthy.
+ @retval EFI_OUT_OF_RESOURCES The list of Driver Health Protocol handles can not be retrieved.
+
+**/
+EFI_STATUS
+GetAllControllersHealthStatus (
+ IN OUT LIST_ENTRY *DriverHealthList
+ )
+{
+ EFI_STATUS Status;
+ UINTN NumHandles;
+ EFI_HANDLE *DriverHealthHandles;
+ EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth;
+ EFI_DRIVER_HEALTH_STATUS HealthStatus;
+ UINTN DriverHealthIndex;
+ EFI_HANDLE *Handles;
+ UINTN HandleCount;
+ UINTN ControllerIndex;
+ UINTN ChildIndex;
+
+ //
+ // Initialize local variables
+ //
+ Handles = NULL;
+ DriverHealthHandles = NULL;
+ NumHandles = 0;
+ HandleCount = 0;
+
+ HealthStatus = EfiDriverHealthStatusHealthy;
+
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiDriverHealthProtocolGuid,
+ NULL,
+ &NumHandles,
+ &DriverHealthHandles
+ );
+
+ if (Status == EFI_NOT_FOUND || NumHandles == 0) {
+ //
+ // If there are no Driver Health Protocols handles, then return EFI_NOT_FOUND
+ //
+ return EFI_NOT_FOUND;
+ }
+
+ if (EFI_ERROR (Status) || DriverHealthHandles == NULL) {
+ //
+ // If the list of Driver Health Protocol handles can not be retrieved, then
+ // return EFI_OUT_OF_RESOURCES
+ //
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Check the health status of all controllers in the platform
+ // Start by looping through all the Driver Health Protocol handles in the handle database
+ //
+ for (DriverHealthIndex = 0; DriverHealthIndex < NumHandles; DriverHealthIndex++) {
+ //
+ // Skip NULL Driver Health Protocol handles
+ //
+ if (DriverHealthHandles[DriverHealthIndex] == NULL) {
+ continue;
+ }
+
+ //
+ // Retrieve the Driver Health Protocol from DriverHandle
+ //
+ Status = gBS->HandleProtocol (
+ DriverHealthHandles[DriverHealthIndex],
+ &gEfiDriverHealthProtocolGuid,
+ (VOID **)&DriverHealth
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // If the Driver Health Protocol can not be retrieved, then skip to the next
+ // Driver Health Protocol handle
+ //
+ continue;
+ }
+
+ //
+ // Check the health of all the controllers managed by a Driver Health Protocol handle
+ //
+ Status = GetSingleControllerHealthStatus (DriverHealthList, DriverHealthHandles[DriverHealthIndex], NULL, NULL, DriverHealth, &HealthStatus);
+
+ //
+ // If Status is an error code, then the health information could not be retrieved, so assume healthy
+ // and skip to the next Driver Health Protocol handle
+ //
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ //
+ // If all the controllers managed by this Driver Health Protocol are healthy, then skip to the next
+ // Driver Health Protocol handle
+ //
+ if (HealthStatus == EfiDriverHealthStatusHealthy) {
+ continue;
+ }
+
+ //
+ // See if the list of all handles in the handle database has been retrieved
+ //
+ //
+ if (Handles == NULL) {
+ //
+ // Retrieve the list of all handles from the handle database
+ //
+ Status = gBS->LocateHandleBuffer (
+ AllHandles,
+ NULL,
+ NULL,
+ &HandleCount,
+ &Handles
+ );
+ if (EFI_ERROR (Status) || Handles == NULL) {
+ //
+ // If all the handles in the handle database can not be retrieved, then
+ // return EFI_OUT_OF_RESOURCES
+ //
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Done;
+ }
+ }
+ //
+ // Loop through all the controller handles in the handle database
+ //
+ for (ControllerIndex = 0; ControllerIndex < HandleCount; ControllerIndex++) {
+ //
+ // Skip NULL controller handles
+ //
+ if (Handles[ControllerIndex] == NULL) {
+ continue;
+ }
+
+ Status = GetSingleControllerHealthStatus (DriverHealthList, DriverHealthHandles[DriverHealthIndex], Handles[ControllerIndex], NULL, DriverHealth, &HealthStatus);
+ if (EFI_ERROR (Status)) {
+ //
+ // If Status is an error code, then the health information could not be retrieved, so assume healthy
+ //
+ HealthStatus = EfiDriverHealthStatusHealthy;
+ }
+
+ //
+ // If CheckHealthSingleController() returned an error on a terminal state, then do not check the health of child controllers
+ //
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ //
+ // Loop through all the child handles in the handle database
+ //
+ for (ChildIndex = 0; ChildIndex < HandleCount; ChildIndex++) {
+ //
+ // Skip NULL child handles
+ //
+ if (Handles[ChildIndex] == NULL) {
+ continue;
+ }
+
+ Status = GetSingleControllerHealthStatus (DriverHealthList, DriverHealthHandles[DriverHealthIndex], Handles[ControllerIndex], Handles[ChildIndex], DriverHealth, &HealthStatus);
+ if (EFI_ERROR (Status)) {
+ //
+ // If Status is an error code, then the health information could not be retrieved, so assume healthy
+ //
+ HealthStatus = EfiDriverHealthStatusHealthy;
+ }
+
+ //
+ // If CheckHealthSingleController() returned an error on a terminal state, then skip to the next child
+ //
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+ }
+ }
+ }
+
+ Status = EFI_SUCCESS;
+
+Done:
+ if (Handles != NULL) {
+ gBS->FreePool (Handles);
+ }
+ if (DriverHealthHandles != NULL) {
+ gBS->FreePool (DriverHealthHandles);
+ }
+
+ return Status;
+}
+
+
+/**
+ Check the healthy status of the platform, this function will return immediately while found one driver
+ in the platform are not healthy.
+
+ @retval FALSE at least one driver in the platform are not healthy.
+ @retval TRUE No controller install Driver Health Protocol,
+ or all controllers in the platform are in healthy status.
+**/
+BOOLEAN
+PlaformHealthStatusCheck (
+ VOID
+ )
+{
+ EFI_DRIVER_HEALTH_STATUS HealthStatus;
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN NoHandles;
+ EFI_HANDLE *DriverHealthHandles;
+ EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth;
+ BOOLEAN AllHealthy;
+
+ //
+ // Initialize local variables
+ //
+ DriverHealthHandles = NULL;
+ DriverHealth = NULL;
+
+ HealthStatus = EfiDriverHealthStatusHealthy;
+
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiDriverHealthProtocolGuid,
+ NULL,
+ &NoHandles,
+ &DriverHealthHandles
+ );
+ //
+ // There are no handles match the search for Driver Health Protocol has been installed.
+ //
+ if (Status == EFI_NOT_FOUND) {
+ return TRUE;
+ }
+ //
+ // Assume all modules are healthy.
+ //
+ AllHealthy = TRUE;
+
+ //
+ // Found one or more Handles.
+ //
+ if (!EFI_ERROR (Status)) {
+ for (Index = 0; Index < NoHandles; Index++) {
+ Status = gBS->HandleProtocol (
+ DriverHealthHandles[Index],
+ &gEfiDriverHealthProtocolGuid,
+ (VOID **) &DriverHealth
+ );
+ if (!EFI_ERROR (Status)) {
+ Status = DriverHealth->GetHealthStatus (
+ DriverHealth,
+ NULL,
+ NULL,
+ &HealthStatus,
+ NULL,
+ NULL
+ );
+ }
+ //
+ // Get the healthy status of the module
+ //
+ if (!EFI_ERROR (Status)) {
+ if (HealthStatus != EfiDriverHealthStatusHealthy) {
+ //
+ // Return immediately one driver's status not in healthy.
+ //
+ return FALSE;
+ }
+ }
+ }
+ }
+ return AllHealthy;
+}
+
+/**
+ Processes a single controller using the EFI Driver Health Protocol associated with
+ that controller. This algorithm continues to query the GetHealthStatus() service until
+ one of the legal terminal states of the EFI Driver Health Protocol is reached. This may
+ require the processing of HII Messages, HII Form, and invocation of repair operations.
+
+ @param DriverHealth A pointer to the EFI_DRIVER_HEALTH_PROTOCOL instance.
+ @param ControllerHandle The class guid specifies which form set will be displayed.
+ @param ChildHandle The handle of the child controller to retrieve the health
+ status on. This is an optional parameter that may be NULL.
+ @param HealthStatus The health status of the controller.
+ @param MessageList An array of warning or error messages associated
+ with the controller specified by ControllerHandle and
+ ChildHandle. This is an optional parameter that may be NULL.
+ @param FormHiiHandle The HII handle for an HII form associated with the
+ controller specified by ControllerHandle and ChildHandle.
+ @param RebootRequired Indicate whether a reboot is required to repair the controller.
+**/
+VOID
+ProcessSingleControllerHealth (
+ IN EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth,
+ IN EFI_HANDLE ControllerHandle, OPTIONAL
+ IN EFI_HANDLE ChildHandle, OPTIONAL
+ IN EFI_DRIVER_HEALTH_STATUS HealthStatus,
+ IN EFI_DRIVER_HEALTH_HII_MESSAGE **MessageList, OPTIONAL
+ IN EFI_HII_HANDLE FormHiiHandle,
+ IN OUT BOOLEAN *RebootRequired
+ )
+{
+ EFI_STATUS Status;
+ EFI_DRIVER_HEALTH_STATUS LocalHealthStatus;
+
+ LocalHealthStatus = HealthStatus;
+ //
+ // If the module need to be repaired or reconfiguration, will process it until
+ // reach a terminal status. The status from EfiDriverHealthStatusRepairRequired after repair
+ // will be in (Health, Failed, Configuration Required).
+ //
+ while(LocalHealthStatus == EfiDriverHealthStatusConfigurationRequired ||
+ LocalHealthStatus == EfiDriverHealthStatusRepairRequired) {
+
+ if (LocalHealthStatus == EfiDriverHealthStatusRepairRequired) {
+ Status = DriverHealth->Repair (
+ DriverHealth,
+ ControllerHandle,
+ ChildHandle,
+ RepairNotify
+ );
+ }
+ //
+ // Via a form of the driver need to do configuration provided to process of status in
+ // EfiDriverHealthStatusConfigurationRequired. The status after configuration should be in
+ // (Healthy, Reboot Required, Failed, Reconnect Required, Repair Required).
+ //
+ if (LocalHealthStatus == EfiDriverHealthStatusConfigurationRequired) {
+ if (FormHiiHandle != NULL) {
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &FormHiiHandle,
+ 1,
+ &gEfiHiiDriverHealthFormsetGuid,
+ 0,
+ NULL,
+ NULL
+ );
+ ASSERT( !EFI_ERROR (Status));
+ } else {
+ //
+ // Exit the loop in case no FormHiiHandle is supplied to prevent dead-loop
+ //
+ break;
+ }
+ }
+
+ Status = DriverHealth->GetHealthStatus (
+ DriverHealth,
+ ControllerHandle,
+ ChildHandle,
+ &LocalHealthStatus,
+ NULL,
+ &FormHiiHandle
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ if (*MessageList != NULL) {
+ ProcessMessages (*MessageList);
+ }
+ }
+
+ //
+ // Health status in {Healthy, Failed} may also have Messages need to process
+ //
+ if (LocalHealthStatus == EfiDriverHealthStatusHealthy || LocalHealthStatus == EfiDriverHealthStatusFailed) {
+ if (*MessageList != NULL) {
+ ProcessMessages (*MessageList);
+ }
+ }
+ //
+ // Check for RebootRequired or ReconnectRequired
+ //
+ if (LocalHealthStatus == EfiDriverHealthStatusRebootRequired) {
+ *RebootRequired = TRUE;
+ }
+
+ //
+ // Do reconnect if need.
+ //
+ if (LocalHealthStatus == EfiDriverHealthStatusReconnectRequired) {
+ Status = gBS->DisconnectController (ControllerHandle, NULL, NULL);
+ if (EFI_ERROR (Status)) {
+ //
+ // Disconnect failed. Need to promote reconnect to a reboot.
+ //
+ *RebootRequired = TRUE;
+ } else {
+ gBS->ConnectController (ControllerHandle, NULL, NULL, TRUE);
+ }
+ }
+}
+
+
+/**
+ Reports the progress of a repair operation.
+
+ @param[in] Value A value between 0 and Limit that identifies the current
+ progress of the repair operation.
+
+ @param[in] Limit The maximum value of Value for the current repair operation.
+ For example, a driver that wants to specify progress in
+ percent would use a Limit value of 100.
+
+ @retval EFI_SUCCESS The progress of a repair operation is reported successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+RepairNotify (
+ IN UINTN Value,
+ IN UINTN Limit
+ )
+{
+ UINTN Percent;
+
+ if (Limit == 0) {
+ Print(L"Repair Progress Undefined\n\r");
+ } else {
+ Percent = Value * 100 / Limit;
+ Print(L"Repair Progress = %3d%%\n\r", Percent);
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Processes a set of messages returned by the GetHealthStatus ()
+ service of the EFI Driver Health Protocol
+
+ @param MessageList The MessageList point to messages need to processed.
+
+**/
+VOID
+ProcessMessages (
+ IN EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList
+ )
+{
+ UINTN MessageIndex;
+ EFI_STRING MessageString;
+
+ for (MessageIndex = 0;
+ MessageList[MessageIndex].HiiHandle != NULL;
+ MessageIndex++) {
+
+ MessageString = HiiGetString (
+ MessageList[MessageIndex].HiiHandle,
+ MessageList[MessageIndex].StringId,
+ NULL
+ );
+ if (MessageString != NULL) {
+ //
+ // User can customize the output. Just simply print out the MessageString like below.
+ // Also can use the HiiHandle to display message on the front page.
+ //
+ // Print(L"%s\n",MessageString);
+ // gBS->Stall (100000);
+ }
+ }
+
+}
+
+/**
+ Repair the whole platform.
+
+ This function is the main entry for user choose "Repair All" in the front page.
+ It will try to do recovery job till all the driver health protocol installed modules
+ reach a terminal state.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health
+ information.
+
+**/
+VOID
+PlatformRepairAll (
+ IN LIST_ENTRY *DriverHealthList
+ )
+{
+ DRIVER_HEALTH_INFO *DriverHealthInfo;
+ LIST_ENTRY *Link;
+ BOOLEAN RebootRequired;
+
+ ASSERT (DriverHealthList != NULL);
+
+ RebootRequired = FALSE;
+
+ for ( Link = GetFirstNode (DriverHealthList)
+ ; !IsNull (DriverHealthList, Link)
+ ; Link = GetNextNode (DriverHealthList, Link)
+ ) {
+ DriverHealthInfo = DEVICE_MANAGER_HEALTH_INFO_FROM_LINK (Link);
+ //
+ // Do driver health status operation by each link node
+ //
+ ASSERT (DriverHealthInfo != NULL);
+
+ ProcessSingleControllerHealth (
+ DriverHealthInfo->DriverHealth,
+ DriverHealthInfo->ControllerHandle,
+ DriverHealthInfo->ChildHandle,
+ DriverHealthInfo->HealthStatus,
+ &(DriverHealthInfo->MessageList),
+ DriverHealthInfo->HiiHandle,
+ &RebootRequired
+ );
+ }
+
+ if (RebootRequired) {
+ gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL);
+ }
+}
+
+/**
+
+ Select the best matching language according to front page policy for best user experience.
+
+ This function supports both ISO 639-2 and RFC 4646 language codes, but language
+ code types may not be mixed in a single call to this function.
+
+ @param SupportedLanguages A pointer to a Null-terminated ASCII string that
+ contains a set of language codes in the format
+ specified by Iso639Language.
+ @param Iso639Language If TRUE, then all language codes are assumed to be
+ in ISO 639-2 format. If FALSE, then all language
+ codes are assumed to be in RFC 4646 language format.
+
+ @retval NULL The best matching language could not be found in SupportedLanguages.
+ @retval NULL There are not enough resources available to return the best matching
+ language.
+ @retval Other A pointer to a Null-terminated ASCII string that is the best matching
+ language in SupportedLanguages.
+**/
+CHAR8 *
+DriverHealthSelectBestLanguage (
+ IN CHAR8 *SupportedLanguages,
+ IN BOOLEAN Iso639Language
+ )
+{
+ CHAR8 *LanguageVariable;
+ CHAR8 *BestLanguage;
+
+ GetEfiGlobalVariable2 (Iso639Language ? L"Lang" : L"PlatformLang", (VOID**)&LanguageVariable, NULL);
+
+ BestLanguage = GetBestLanguage(
+ SupportedLanguages,
+ Iso639Language,
+ (LanguageVariable != NULL) ? LanguageVariable : "",
+ Iso639Language ? "eng" : "en-US",
+ NULL
+ );
+ if (LanguageVariable != NULL) {
+ FreePool (LanguageVariable);
+ }
+
+ return BestLanguage;
+}
+
+
+
+/**
+
+ This is an internal worker function to get the Component Name (2) protocol interface
+ and the language it supports.
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ComponentName A pointer to the Component Name (2) protocol interface.
+ @param SupportedLanguage The best suitable language that matches the SupportedLangues interface for the
+ located Component Name (2) instance.
+
+ @retval EFI_SUCCESS The Component Name (2) protocol instance is successfully located and we find
+ the best matching language it support.
+ @retval EFI_UNSUPPORTED The input Language is not supported by the Component Name (2) protocol.
+ @retval Other Some error occurs when locating Component Name (2) protocol instance or finding
+ the supported language.
+
+**/
+EFI_STATUS
+GetComponentNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT EFI_COMPONENT_NAME_PROTOCOL **ComponentName,
+ OUT CHAR8 **SupportedLanguage
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Locate Component Name (2) protocol on the driver binging handle.
+ //
+ Status = gBS->OpenProtocol (
+ DriverBindingHandle,
+ ProtocolGuid,
+ (VOID **) ComponentName,
+ NULL,
+ NULL,
+ EFI_OPEN_PROTOCOL_GET_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Apply shell policy to select the best language.
+ //
+ *SupportedLanguage = DriverHealthSelectBestLanguage (
+ (*ComponentName)->SupportedLanguages,
+ (BOOLEAN) (ProtocolGuid == &gEfiComponentNameProtocolGuid)
+ );
+ if (*SupportedLanguage == NULL) {
+ Status = EFI_UNSUPPORTED;
+ }
+
+ return Status;
+}
+
+/**
+
+ This is an internal worker function to get driver name from Component Name (2) protocol interface.
+
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param DriverName A pointer to the Unicode string to return. This Unicode string is the name
+ of the driver specified by This.
+
+ @retval EFI_SUCCESS The driver name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The driver name cannot be retrieved from Component Name (2) protocol
+ interface.
+
+**/
+EFI_STATUS
+GetDriverNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT CHAR16 **DriverName
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *BestLanguage;
+ EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
+
+ //
+ // Retrieve Component Name (2) protocol instance on the driver binding handle and
+ // find the best language this instance supports.
+ //
+ Status = GetComponentNameWorker (
+ ProtocolGuid,
+ DriverBindingHandle,
+ &ComponentName,
+ &BestLanguage
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Get the driver name from Component Name (2) protocol instance on the driver binging handle.
+ //
+ Status = ComponentName->GetDriverName (
+ ComponentName,
+ BestLanguage,
+ DriverName
+ );
+ FreePool (BestLanguage);
+
+ return Status;
+}
+
+/**
+
+ This function gets driver name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the driver name.
+ If the attempt fails, it then gets the driver name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param DriverName A pointer to the Unicode string to return. This Unicode string is the name
+ of the driver specified by This.
+
+ @retval EFI_SUCCESS The driver name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The driver name cannot be retrieved from Component Name (2) protocol
+ interface.
+
+**/
+EFI_STATUS
+DriverHealthGetDriverName (
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT CHAR16 **DriverName
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Get driver name from UEFI 2.0 Component Name 2 protocol interface.
+ //
+ Status = GetDriverNameWorker (&gEfiComponentName2ProtocolGuid, DriverBindingHandle, DriverName);
+ if (EFI_ERROR (Status)) {
+ //
+ // If it fails to get the driver name from Component Name protocol interface, we should fall back on
+ // EFI 1.1 Component Name protocol interface.
+ //
+ Status = GetDriverNameWorker (&gEfiComponentNameProtocolGuid, DriverBindingHandle, DriverName);
+ }
+
+ return Status;
+}
+
+
+
+/**
+ This function gets controller name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the controller name.
+ If the attempt fails, it then gets the controller name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ControllerHandle The handle of a controller that the driver specified by This is managing.
+ This handle specifies the controller whose name is to be returned.
+ @param ChildHandle The handle of the child controller to retrieve the name of. This is an
+ optional parameter that may be NULL. It will be NULL for device drivers.
+ It will also be NULL for bus drivers that attempt to retrieve the name
+ of the bus controller. It will not be NULL for a bus driver that attempts
+ to retrieve the name of a child controller.
+ @param ControllerName A pointer to the Unicode string to return. This Unicode string
+ is the name of the controller specified by ControllerHandle and ChildHandle.
+
+ @retval EFI_SUCCESS The controller name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The controller name cannot be retrieved from Component Name (2) protocol.
+
+**/
+EFI_STATUS
+GetControllerNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle,
+ OUT CHAR16 **ControllerName
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *BestLanguage;
+ EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
+
+ //
+ // Retrieve Component Name (2) protocol instance on the driver binding handle and
+ // find the best language this instance supports.
+ //
+ Status = GetComponentNameWorker (
+ ProtocolGuid,
+ DriverBindingHandle,
+ &ComponentName,
+ &BestLanguage
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Get the controller name from Component Name (2) protocol instance on the driver binging handle.
+ //
+ Status = ComponentName->GetControllerName (
+ ComponentName,
+ ControllerHandle,
+ ChildHandle,
+ BestLanguage,
+ ControllerName
+ );
+ FreePool (BestLanguage);
+
+ return Status;
+}
+
+/**
+
+ This function gets controller name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the controller name.
+ If the attempt fails, it then gets the controller name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ControllerHandle The handle of a controller that the driver specified by This is managing.
+ This handle specifies the controller whose name is to be returned.
+ @param ChildHandle The handle of the child controller to retrieve the name of. This is an
+ optional parameter that may be NULL. It will be NULL for device drivers.
+ It will also be NULL for bus drivers that attempt to retrieve the name
+ of the bus controller. It will not be NULL for a bus driver that attempts
+ to retrieve the name of a child controller.
+ @param ControllerName A pointer to the Unicode string to return. This Unicode string
+ is the name of the controller specified by ControllerHandle and ChildHandle.
+
+ @retval EFI_SUCCESS The controller name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The controller name cannot be retrieved from Component Name (2) protocol.
+
+**/
+EFI_STATUS
+DriverHealthGetControllerName (
+ IN EFI_HANDLE DriverBindingHandle,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle,
+ OUT CHAR16 **ControllerName
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Get controller name from UEFI 2.0 Component Name 2 protocol interface.
+ //
+ Status = GetControllerNameWorker (
+ &gEfiComponentName2ProtocolGuid,
+ DriverBindingHandle,
+ ControllerHandle,
+ ChildHandle,
+ ControllerName
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // If it fails to get the controller name from Component Name protocol interface, we should fall back on
+ // EFI 1.1 Component Name protocol interface.
+ //
+ Status = GetControllerNameWorker (
+ &gEfiComponentNameProtocolGuid,
+ DriverBindingHandle,
+ ControllerHandle,
+ ChildHandle,
+ ControllerName
+ );
+ }
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.h
new file mode 100644
index 0000000000..95bde8de5a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManager.h
@@ -0,0 +1,523 @@
+/** @file
+ The platform device manager reference implement
+
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+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 _DEVICE_MANAGER_H_
+#define _DEVICE_MANAGER_H_
+
+#include "Bds.h"
+#include "FrontPage.h"
+#include "DeviceManagerVfr.h"
+#include <Protocol/PciIo.h>
+
+#define DEVICE_MANAGER_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('D', 'M', 'C', 'B')
+#define DEVICE_MANAGER_DRIVER_HEALTH_INFO_SIGNATURE SIGNATURE_32 ('D', 'M', 'D', 'H')
+
+
+typedef struct {
+ UINTN Signature;
+
+ ///
+ /// Device Manager HII relative handles
+ ///
+ EFI_HII_HANDLE HiiHandle;
+
+ ///
+ /// Driver Health HII relative handles
+ ///
+ EFI_HII_HANDLE DriverHealthHiiHandle;
+
+ EFI_HANDLE DriverHandle;
+ EFI_HANDLE DriverHealthHandle;
+
+ ///
+ /// Device Manager Produced protocols
+ ///
+ EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess;
+
+ ///
+ /// Driver Health Produced protocols
+ ///
+ EFI_HII_CONFIG_ACCESS_PROTOCOL DriverHealthConfigAccess;
+
+ ///
+ /// Configuration data
+ ///
+ UINT8 VideoBios;
+} DEVICE_MANAGER_CALLBACK_DATA;
+
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Link;
+
+ ///
+ /// HII relative handles
+ ///
+ EFI_HII_HANDLE HiiHandle;
+
+ ///
+ /// Driver relative handles
+ ///
+ EFI_HANDLE DriverHandle;
+ EFI_HANDLE ControllerHandle;
+ EFI_HANDLE ChildHandle;
+
+ EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth;
+ ///
+ /// Driver health messages of the specify Driver
+ ///
+ EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList;
+
+ ///
+ /// Driver Health status
+ ///
+ EFI_DRIVER_HEALTH_STATUS HealthStatus;
+} DRIVER_HEALTH_INFO;
+
+typedef struct {
+ EFI_STRING_ID PromptId;
+ EFI_QUESTION_ID QuestionId;
+}MENU_INFO_ITEM;
+
+typedef struct {
+ UINTN CurListLen;
+ UINTN MaxListLen;
+ MENU_INFO_ITEM *NodeList;
+} MAC_ADDRESS_NODE_LIST;
+
+#define DEVICE_MANAGER_HEALTH_INFO_FROM_LINK(a) \
+ CR (a, \
+ DRIVER_HEALTH_INFO, \
+ Link, \
+ DEVICE_MANAGER_DRIVER_HEALTH_INFO_SIGNATURE \
+ )
+
+#define DEVICE_MANAGER_CALLBACK_DATA_FROM_THIS(a) \
+ CR (a, \
+ DEVICE_MANAGER_CALLBACK_DATA, \
+ ConfigAccess, \
+ DEVICE_MANAGER_CALLBACK_DATA_SIGNATURE \
+ )
+typedef struct {
+ EFI_STRING_ID StringId;
+ UINT16 Class;
+} DEVICE_MANAGER_MENU_ITEM;
+
+/**
+ This function is invoked if user selected a interactive opcode from Device Manager's
+ Formset. The decision by user is saved to gCallbackKey for later processing. If
+ user set VBIOS, the new value is saved to EFI variable.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+DeviceManagerCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ );
+
+/**
+ This function is invoked if user selected a interactive opcode from Driver Health's
+ Formset. The decision by user is saved to gCallbackKey for later processing.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_INVALID_PARAMETER The setup browser call this function with invalid parameters.
+
+**/
+EFI_STATUS
+EFIAPI
+DriverHealthCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ );
+
+
+/**
+
+ This function registers HII packages to HII database.
+
+ @retval EFI_SUCCESS HII packages for the Device Manager were registered successfully.
+ @retval EFI_OUT_OF_RESOURCES HII packages for the Device Manager failed to be registered.
+
+**/
+EFI_STATUS
+InitializeDeviceManager (
+ VOID
+ );
+
+/**
+
+ Call the browser and display the device manager to allow user
+ to configure the platform.
+
+ This function create the dynamic content for device manager. It includes
+ section header for all class of devices, one-of opcode to set VBIOS.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval Other values if failed to clean up the dynamic content from HII
+ database.
+
+**/
+EFI_STATUS
+CallDeviceManager (
+ VOID
+ );
+
+
+/**
+ Check the Driver Health status of a single controller and try to process it if not healthy.
+
+ This function called by CheckAllControllersHealthStatus () function in order to process a specify
+ contoller's health state.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health information.
+ @param DriverHandle The handle of driver.
+ @param ControllerHandle The class guid specifies which form set will be displayed.
+ @param ChildHandle The handle of the child controller to retrieve the health
+ status on. This is an optional parameter that may be NULL.
+ @param DriverHealth A pointer to the EFI_DRIVER_HEALTH_PROTOCOL instance.
+ @param HealthStatus The health status of the controller.
+
+ @retval EFI_INVALID_PARAMETER HealthStatus or DriverHealth is NULL.
+ @retval HealthStatus The Health status of specify controller.
+ @retval EFI_OUT_OF_RESOURCES The list of Driver Health Protocol handles can not be retrieved.
+ @retval EFI_NOT_FOUND No controller in the platform install Driver Health Protocol.
+ @retval EFI_SUCCESS The Health related operation has been taken successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+GetSingleControllerHealthStatus (
+ IN OUT LIST_ENTRY *DriverHealthList,
+ IN EFI_HANDLE DriverHandle,
+ IN EFI_HANDLE ControllerHandle, OPTIONAL
+ IN EFI_HANDLE ChildHandle, OPTIONAL
+ IN EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth,
+ IN EFI_DRIVER_HEALTH_STATUS *HealthStatus
+ );
+
+/**
+ Collects all the EFI Driver Health Protocols currently present in the EFI Handle Database,
+ and queries each EFI Driver Health Protocol to determine if one or more of the controllers
+ managed by each EFI Driver Health Protocol instance are not healthy.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health
+ information.
+
+ @retval EFI_NOT_FOUND No controller in the platform install Driver Health Protocol.
+ @retval EFI_SUCCESS All the controllers in the platform are healthy.
+ @retval EFI_OUT_OF_RESOURCES The list of Driver Health Protocol handles can not be retrieved.
+
+**/
+EFI_STATUS
+GetAllControllersHealthStatus (
+ IN OUT LIST_ENTRY *DriverHealthList
+ );
+
+/**
+ Check the healthy status of the platform, this function will return immediately while found one driver
+ in the platform are not healthy.
+
+ @retval FALSE at least one driver in the platform are not healthy.
+ @retval TRUE No controller install Driver Health Protocol,
+ or all controllers in the platform are in healthy status.
+**/
+BOOLEAN
+PlaformHealthStatusCheck (
+ VOID
+ );
+
+/**
+ Repair the whole platform.
+
+ This function is the main entry for user choose "Repair All" in the front page.
+ It will try to do recovery job till all the driver health protocol installed modules
+ reach a terminal state.
+
+ @param DriverHealthList A Pointer to the list contain all of the platform driver health
+ information.
+
+**/
+VOID
+PlatformRepairAll (
+ IN LIST_ENTRY *DriverHealthList
+ );
+
+/**
+ Processes a single controller using the EFI Driver Health Protocol associated with
+ that controller. This algorithm continues to query the GetHealthStatus() service until
+ one of the legal terminal states of the EFI Driver Health Protocol is reached. This may
+ require the processing of HII Messages, HII Form, and invocation of repair operations.
+
+ @param DriverHealth A pointer to the EFI_DRIVER_HEALTH_PROTOCOL instance.
+ @param ControllerHandle The class guid specifies which form set will be displayed.
+ @param ChildHandle The handle of the child controller to retrieve the health
+ status on. This is an optional parameter that may be NULL.
+ @param HealthStatus The health status of the controller.
+ @param MessageList An array of warning or error messages associated
+ with the controller specified by ControllerHandle and
+ ChildHandle. This is an optional parameter that may be NULL.
+ @param FormHiiHandle The HII handle for an HII form associated with the
+ controller specified by ControllerHandle and ChildHandle.
+ @param RebootRequired Indicate whether a reboot is required to repair the controller.
+**/
+VOID
+ProcessSingleControllerHealth (
+ IN EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth,
+ IN EFI_HANDLE ControllerHandle, OPTIONAL
+ IN EFI_HANDLE ChildHandle, OPTIONAL
+ IN EFI_DRIVER_HEALTH_STATUS HealthStatus,
+ IN EFI_DRIVER_HEALTH_HII_MESSAGE **MessageList, OPTIONAL
+ IN EFI_HII_HANDLE FormHiiHandle,
+ IN OUT BOOLEAN *RebootRequired
+ );
+
+/**
+ Reports the progress of a repair operation.
+
+ @param[in] Value A value between 0 and Limit that identifies the current
+ progress of the repair operation.
+
+ @param[in] Limit The maximum value of Value for the current repair operation.
+ For example, a driver that wants to specify progress in
+ percent would use a Limit value of 100.
+
+ @retval EFI_SUCCESS The progress of a repair operation is reported successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+RepairNotify (
+ IN UINTN Value,
+ IN UINTN Limit
+ );
+
+/**
+ Processes a set of messages returned by the GetHealthStatus ()
+ service of the EFI Driver Health Protocol
+
+ @param MessageList The MessageList point to messages need to processed.
+
+**/
+VOID
+ProcessMessages (
+ IN EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList
+ );
+
+
+/**
+ Collect and display the platform's driver health relative information, allow user to do interactive
+ operation while the platform is unhealthy.
+
+ This function display a form which divided into two parts. The one list all modules which has installed
+ driver health protocol. The list usually contain driver name, controller name, and it's health info.
+ While the driver name can't be retrieved, will use device path as backup. The other part of the form provide
+ a choice to the user to repair all platform.
+
+**/
+VOID
+CallDriverHealth (
+ VOID
+ );
+
+/**
+
+ Select the best matching language according to front page policy for best user experience.
+
+ This function supports both ISO 639-2 and RFC 4646 language codes, but language
+ code types may not be mixed in a single call to this function.
+
+ @param SupportedLanguages A pointer to a Null-terminated ASCII string that
+ contains a set of language codes in the format
+ specified by Iso639Language.
+ @param Iso639Language If TRUE, then all language codes are assumed to be
+ in ISO 639-2 format. If FALSE, then all language
+ codes are assumed to be in RFC 4646 language format.
+
+ @retval NULL The best matching language could not be found in SupportedLanguages.
+ @retval NULL There are not enough resources available to return the best matching
+ language.
+ @retval Other A pointer to a Null-terminated ASCII string that is the best matching
+ language in SupportedLanguages.
+**/
+CHAR8 *
+DriverHealthSelectBestLanguage (
+ IN CHAR8 *SupportedLanguages,
+ IN BOOLEAN Iso639Language
+ );
+
+/**
+
+ This is an internal worker function to get the Component Name (2) protocol interface
+ and the language it supports.
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ComponentName A pointer to the Component Name (2) protocol interface.
+ @param SupportedLanguage The best suitable language that matches the SupportedLangues interface for the
+ located Component Name (2) instance.
+
+ @retval EFI_SUCCESS The Component Name (2) protocol instance is successfully located and we find
+ the best matching language it support.
+ @retval EFI_UNSUPPORTED The input Language is not supported by the Component Name (2) protocol.
+ @retval Other Some error occurs when locating Component Name (2) protocol instance or finding
+ the supported language.
+
+**/
+EFI_STATUS
+GetComponentNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT EFI_COMPONENT_NAME_PROTOCOL **ComponentName,
+ OUT CHAR8 **SupportedLanguage
+ );
+
+/**
+
+ This is an internal worker function to get driver name from Component Name (2) protocol interface.
+
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param DriverName A pointer to the Unicode string to return. This Unicode string is the name
+ of the driver specified by This.
+
+ @retval EFI_SUCCESS The driver name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The driver name cannot be retrieved from Component Name (2) protocol
+ interface.
+
+**/
+EFI_STATUS
+GetDriverNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT CHAR16 **DriverName
+ );
+
+/**
+
+ This function gets driver name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the driver name.
+ If the attempt fails, it then gets the driver name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param DriverName A pointer to the Unicode string to return. This Unicode string is the name
+ of the driver specified by This.
+
+ @retval EFI_SUCCESS The driver name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The driver name cannot be retrieved from Component Name (2) protocol
+ interface.
+
+**/
+EFI_STATUS
+DriverHealthGetDriverName (
+ IN EFI_HANDLE DriverBindingHandle,
+ OUT CHAR16 **DriverName
+ );
+
+/**
+ This function gets controller name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the controller name.
+ If the attempt fails, it then gets the controller name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param ProtocolGuid A pointer to an EFI_GUID. It points to Component Name (2) protocol GUID.
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ControllerHandle The handle of a controller that the driver specified by This is managing.
+ This handle specifies the controller whose name is to be returned.
+ @param ChildHandle The handle of the child controller to retrieve the name of. This is an
+ optional parameter that may be NULL. It will be NULL for device drivers.
+ It will also be NULL for bus drivers that attempt to retrieve the name
+ of the bus controller. It will not be NULL for a bus driver that attempts
+ to retrieve the name of a child controller.
+ @param ControllerName A pointer to the Unicode string to return. This Unicode string
+ is the name of the controller specified by ControllerHandle and ChildHandle.
+
+ @retval EFI_SUCCESS The controller name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The controller name cannot be retrieved from Component Name (2) protocol.
+
+**/
+EFI_STATUS
+GetControllerNameWorker (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_HANDLE DriverBindingHandle,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle,
+ OUT CHAR16 **ControllerName
+ );
+
+/**
+ This function gets controller name from Component Name 2 protocol interface and Component Name protocol interface
+ in turn. It first tries UEFI 2.0 Component Name 2 protocol interface and try to get the controller name.
+ If the attempt fails, it then gets the controller name from EFI 1.1 Component Name protocol for backward
+ compatibility support.
+
+ @param DriverBindingHandle The handle on which the Component Name (2) protocol instance is retrieved.
+ @param ControllerHandle The handle of a controller that the driver specified by This is managing.
+ This handle specifies the controller whose name is to be returned.
+ @param ChildHandle The handle of the child controller to retrieve the name of. This is an
+ optional parameter that may be NULL. It will be NULL for device drivers.
+ It will also be NULL for bus drivers that attempt to retrieve the name
+ of the bus controller. It will not be NULL for a bus driver that attempts
+ to retrieve the name of a child controller.
+ @param ControllerName A pointer to the Unicode string to return. This Unicode string
+ is the name of the controller specified by ControllerHandle and ChildHandle.
+
+ @retval EFI_SUCCESS The controller name is successfully retrieved from Component Name (2) protocol
+ interface.
+ @retval Other The controller name cannot be retrieved from Component Name (2) protocol.
+
+**/
+EFI_STATUS
+DriverHealthGetControllerName (
+ IN EFI_HANDLE DriverBindingHandle,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle,
+ OUT CHAR16 **ControllerName
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerStrings.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerStrings.uni
new file mode 100644
index 0000000000..8d1b10b301
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerStrings.uni
@@ -0,0 +1,96 @@
+///** @file
+//
+// String definitions for the Device Manager.
+//
+// Copyright (c) 2004 - 2014, 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.
+//
+//**/
+
+/=#
+
+#langdef en-US "English"
+#langdef fr-FR "Français"
+
+#string STR_DEVICE_MANAGER_TITLE #language en-US "Device Manager"
+ #language fr-FR "Device Manager"
+#string STR_DEVICES_LIST #language en-US "Devices List"
+ #language fr-FR "Devices List"
+#string STR_DISK_DEVICE #language en-US "Disk Devices"
+ #language fr-FR "Disk Devices"
+#string STR_VIDEO_DEVICE #language en-US "Video Devices"
+ #language fr-FR "Video Devices"
+#string STR_NETWORK_DEVICE #language en-US "Network Devices"
+ #language fr-FR "Network Devices"
+#string STR_INPUT_DEVICE #language en-US "Input Devices"
+ #language fr-FR "Input Devices"
+#string STR_ON_BOARD_DEVICE #language en-US "Motherboard Devices"
+ #language fr-FR "Motherboard Devices"
+#string STR_OTHER_DEVICE #language en-US "Other Devices"
+ #language fr-FR "Other Devices"
+#string STR_EMPTY_STRING #language en-US ""
+ #language fr-FR ""
+#string STR_DRIVER_HEALTH_STATUS_HELP #language en-US "Check whether all the controllers in the platform are healthy"
+ #language fr-FR "Check whether all the controllers in the platform are healthy"
+#string STR_DRIVER_HEALTH_ALL_HEALTHY #language en-US " The platform is healthy"
+ #language fr-FR " The platform is healthy"
+#string STR_DRIVER_NOT_HEALTH #language en-US " Some drivers are not healthy"
+ #language fr-FR " Some drivers are not healthy"
+#string STR_DH_BANNER #language en-US "Driver Health"
+ #language fr-FR "Driver Health"
+#string STR_DM_DRIVER_HEALTH_TITLE #language en-US "Driver Health"
+ #language fr-FR "Driver Health"
+#string STR_DH_STATUS_LIST #language en-US "All Driver Health Status List"
+ #language fr-FR "All Driver Health Status List"
+#string STR_DRIVER_HEALTH_REPAIR_ALL #language en-US "Repair All"
+ #language fr-FR "Repair All"
+#string STR_DH_REPAIR_ALL_TITLE #language en-US "Repair the whole platform"
+ #language fr-FR "Repair the whole platform"
+#string STR_DH_REPAIR_ALL_HELP #language en-US "Repair the whole platform until all modules reach terminal status"
+ #language fr-FR "Repair the whole platform until all modules reach terminal status"
+#string STR_DH_REPAIR_SINGLE_TITLE #language en-US "Item cannot get name"
+ #language fr-FR "Item cannot get name"
+#string STR_DH_REPAIR_SINGLE_HELP #language en-US "Repair single driver with specify controller"
+ #language fr-FR "Repair single driver with specify controller"
+
+#string STR_EXIT_STRING #language en-US "Press ESC to exit."
+ #language fr-FR "Press ESC to exit."
+#string STR_REPAIR_REQUIRED #language en-US " Repair Required."
+ #language fr-FR " Repair Required."
+#string STR_CONFIGURATION_REQUIRED #language en-US " Configuration Required."
+ #language fr-FR " Configuration Required."
+#string STR_OPERATION_FAILED #language en-US " Operation Failed."
+ #language fr-FR " Operation Failed."
+#string STR_RECONNECT_REQUIRED #language en-US " Reconnect Required."
+ #language fr-FR " Reconnect Required."
+#string STR_REBOOT_REQUIRED #language en-US " Reboot Required."
+ #language fr-FR " Reboot Required."
+#string STR_NO_OPERATION_REQUIRED #language en-US " No Operation Required."
+ #language fr-FR " No Operation Required."
+#string STR_DRIVER_HEALTH_HEALTHY #language en-US " Healthy."
+ #language fr-FR " Healthy."
+#string STR_FORM_NETWORK_DEVICE_TITLE #language en-US "Network Device"
+ #language fr-FR "Network Device"
+#string STR_FORM_NETWORK_DEVICE_HELP #language en-US "Network Device Help..."
+ #language fr-FR "Network Device Help..."
+#string STR_NETWORK_DEVICE_STRING #language en-US "Network Device"
+ #language fr-FR "Network Device"
+#string STR_FORM_NETWORK_DEVICE_LIST_HELP #language en-US "Select the network device according the MAC address"
+ #language fr-FR "Select the network device according the MAC address"
+#string STR_FORM_NETWORK_DEVICE_LIST_TITLE #language en-US "Network Device List"
+ #language fr-FR "Network Device List"
+#string STR_NETWORK_DEVICE_LIST_STRING #language en-US "Network Device List"
+ #language fr-FR "Network Device List"
+#string STR_NETWORK_DEVICE_HELP #language en-US "Network Device"
+ #language fr-FR "Network Device"
+//
+// Ensure that this is the last string. We are using it programmatically
+// to do string token re-usage settings for the Device Manager since we are
+// constantly recreating this page based on HII population.
+////
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.Vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.Vfr
new file mode 100644
index 0000000000..0ad671bdca
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.Vfr
@@ -0,0 +1,93 @@
+///** @file
+//
+// Device Manager formset.
+//
+// Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+#include "DeviceManagerVfr.h"
+
+#define EFI_DISK_DEVICE_CLASS 0x0001
+#define EFI_VIDEO_DEVICE_CLASS 0x0002
+#define EFI_NETWORK_DEVICE_CLASS 0x0004
+#define EFI_INPUT_DEVICE_CLASS 0x0008
+#define EFI_ON_BOARD_DEVICE_CLASS 0x0010
+#define EFI_OTHER_DEVICE_CLASS 0x0020
+
+#define DEVICE_MANAGER_CLASS 0x0000
+#define FRONT_PAGE_SUBCLASS 0x0003
+
+formset
+ guid = DEVICE_MANAGER_FORMSET_GUID,
+ title = STRING_TOKEN(STR_DEVICE_MANAGER_TITLE),
+ help = STRING_TOKEN(STR_EMPTY_STRING),
+ classguid = DEVICE_MANAGER_FORMSET_GUID,
+
+ form formid = DEVICE_MANAGER_FORM_ID,
+ title = STRING_TOKEN(STR_DEVICE_MANAGER_TITLE);
+
+ subtitle text = STRING_TOKEN(STR_DEVICES_LIST);
+ //
+ // This is where devices get added to the device manager hierarchy
+ //
+ label EFI_DISK_DEVICE_CLASS;
+// label LABEL_END; // Since next opcode is a label, so this one could be omitted to save code size
+
+ label EFI_VIDEO_DEVICE_CLASS;
+// label LABEL_END;
+
+ label EFI_NETWORK_DEVICE_CLASS;
+// label LABEL_END;
+
+ label EFI_INPUT_DEVICE_CLASS;
+// label LABEL_END;
+
+ label EFI_ON_BOARD_DEVICE_CLASS;
+// label LABEL_END;
+
+// label EFI_OTHER_DEVICE_CLASS;
+
+ label LABEL_DEVICES_LIST;
+ label LABEL_END;
+
+ subtitle text = STRING_TOKEN(STR_EMPTY_STRING);
+
+ label LABEL_VBIOS;
+ label LABEL_END;
+
+ subtitle text = STRING_TOKEN(STR_EMPTY_STRING);
+ subtitle text = STRING_TOKEN(STR_EXIT_STRING);
+
+ endform;
+
+ form formid = NETWORK_DEVICE_LIST_FORM_ID,
+ title = STRING_TOKEN(STR_FORM_NETWORK_DEVICE_LIST_TITLE);
+
+ subtitle text = STRING_TOKEN(STR_NETWORK_DEVICE_LIST_STRING);
+
+ label LABEL_NETWORK_DEVICE_LIST_ID;
+ label LABEL_END;
+ subtitle text = STRING_TOKEN(STR_EMPTY_STRING);
+ subtitle text = STRING_TOKEN(STR_EXIT_STRING);
+ endform;
+
+ form formid = NETWORK_DEVICE_FORM_ID,
+ title = STRING_TOKEN(STR_FORM_NETWORK_DEVICE_TITLE);
+
+ subtitle text = STRING_TOKEN(STR_NETWORK_DEVICE_STRING);
+
+ label LABEL_NETWORK_DEVICE_ID;
+ label LABEL_END;
+ subtitle text = STRING_TOKEN(STR_EMPTY_STRING);
+ subtitle text = STRING_TOKEN(STR_EXIT_STRING);
+ endform;
+endformset;
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.h
new file mode 100644
index 0000000000..b6b086600f
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DeviceManagerVfr.h
@@ -0,0 +1,56 @@
+/** @file
+ The platform device manager reference implement
+
+Copyright (c) 2011, 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 _DEVICE_MANAGER_VFR_H_
+#define _DEVICE_MANAGER_VFR_H_
+
+#include <Guid/BdsHii.h>
+
+#define LABEL_DEVICES_LIST 0x1100
+#define LABEL_NETWORK_DEVICE_LIST_ID 0x1101
+#define LABEL_NETWORK_DEVICE_ID 0x1102
+#define LABEL_END 0xffff
+#define LABEL_FORM_ID_OFFSET 0x0100
+
+#define LABEL_DRIVER_HEALTH 0x2000
+#define LABEL_DRIVER_HEALTH_END 0x2001
+
+#define LABEL_DRIVER_HEALTH_REAPIR_ALL 0x3000
+#define LABEL_DRIVER_HEALTH_REAPIR_ALL_END 0x3001
+
+#define LABEL_VBIOS 0x0040
+
+#define INVALID_FORM_ID 0x0FFF
+#define DEVICE_MANAGER_FORM_ID 0x1000
+#define NETWORK_DEVICE_LIST_FORM_ID 0x1001
+#define NETWORK_DEVICE_FORM_ID 0x1002
+#define DRIVER_HEALTH_FORM_ID 0x1003
+#define DEVICE_KEY_OFFSET 0x4000
+#define NETWORK_DEVICE_LIST_KEY_OFFSET 0x2000
+#define DEVICE_MANAGER_KEY_VBIOS 0x3000
+#define MAX_KEY_SECTION_LEN 0x1000
+
+#define DEVICE_MANAGER_KEY_DRIVER_HEALTH 0x1111
+#define DRIVER_HEALTH_KEY_OFFSET 0x2000
+#define DRIVER_HEALTH_REPAIR_ALL_KEY 0x3000
+#define DRIVER_HEALTH_RETURN_KEY 0x4000
+
+#define QUESTION_NETWORK_DEVICE_ID 0x3FFF
+//
+// These are the VFR compiler generated data representing our VFR data.
+//
+extern UINT8 DeviceManagerVfrBin[];
+extern UINT8 DriverHealthVfrBin[];
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DriverHealthVfr.Vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DriverHealthVfr.Vfr
new file mode 100644
index 0000000000..cb1a8f887b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/DeviceMngr/DriverHealthVfr.Vfr
@@ -0,0 +1,38 @@
+///** @file
+//
+// Driver Health formset.
+//
+// Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+#include "DeviceManagerVfr.h"
+
+formset
+ guid = DRIVER_HEALTH_FORMSET_GUID,
+ title = STRING_TOKEN(STR_DH_BANNER),
+ help = STRING_TOKEN(STR_EMPTY_STRING),
+ classguid = DRIVER_HEALTH_FORMSET_GUID,
+
+ form formid = DRIVER_HEALTH_FORM_ID,
+ title = STRING_TOKEN(STR_DH_BANNER);
+
+ label LABEL_DRIVER_HEALTH;
+ label LABEL_DRIVER_HEALTH_END;
+
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+ label LABEL_DRIVER_HEALTH_REAPIR_ALL;
+ label LABEL_DRIVER_HEALTH_REAPIR_ALL_END;
+
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+ subtitle text = STRING_TOKEN(STR_HELP_FOOTER);
+ subtitle text = STRING_TOKEN(STR_LAST_STRING);
+ endform;
+endformset;
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.c
new file mode 100644
index 0000000000..2163710cc9
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.c
@@ -0,0 +1,1487 @@
+/** @file
+ FrontPage routines to handle the callbacks and browser calls
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "Bds.h"
+#include "FrontPage.h"
+#include "Language.h"
+#include "Hotkey.h"
+
+BOOLEAN mModeInitialized = FALSE;
+
+BOOLEAN gConnectAllHappened = FALSE;
+UINTN gCallbackKey;
+CHAR8 *mLanguageString;
+
+//
+// Boot video resolution and text mode.
+//
+UINT32 mBootHorizontalResolution = 0;
+UINT32 mBootVerticalResolution = 0;
+UINT32 mBootTextModeColumn = 0;
+UINT32 mBootTextModeRow = 0;
+//
+// BIOS setup video resolution and text mode.
+//
+UINT32 mSetupTextModeColumn = 0;
+UINT32 mSetupTextModeRow = 0;
+UINT32 mSetupHorizontalResolution = 0;
+UINT32 mSetupVerticalResolution = 0;
+
+EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2;
+
+FRONT_PAGE_CALLBACK_DATA gFrontPagePrivate = {
+ FRONT_PAGE_CALLBACK_DATA_SIGNATURE,
+ NULL,
+ NULL,
+ NULL,
+ {
+ FakeExtractConfig,
+ FakeRouteConfig,
+ FrontPageCallback
+ }
+};
+
+HII_VENDOR_DEVICE_PATH mFrontPageHiiVendorDevicePath = {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8)
+ }
+ },
+ FRONT_PAGE_FORMSET_GUID
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (END_DEVICE_PATH_LENGTH),
+ (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8)
+ }
+ }
+};
+
+/**
+ This function allows a caller to extract the current configuration for one
+ or more named elements from the target driver.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Request A null-terminated Unicode string in <ConfigRequest> format.
+ @param Progress On return, points to a character in the Request string.
+ Points to the string's null terminator if request was successful.
+ Points to the most recent '&' before the first failing name/value
+ pair (or the beginning of the string if the failure is in the
+ first name/value pair) if the request was not successful.
+ @param Results A null-terminated Unicode string in <ConfigAltResp> format which
+ has all values filled in for the names in the Request string.
+ String to be allocated by the called function.
+
+ @retval EFI_SUCCESS The Results is filled with the requested values.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the results.
+ @retval EFI_INVALID_PARAMETER Request is illegal syntax, or unknown name.
+ @retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
+
+**/
+EFI_STATUS
+EFIAPI
+FakeExtractConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Request,
+ OUT EFI_STRING *Progress,
+ OUT EFI_STRING *Results
+ )
+{
+ if (Progress == NULL || Results == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ *Progress = Request;
+ return EFI_NOT_FOUND;
+}
+
+/**
+ This function processes the results of changes in configuration.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Configuration A null-terminated Unicode string in <ConfigResp> format.
+ @param Progress A pointer to a string filled in with the offset of the most
+ recent '&' before the first failing name/value pair (or the
+ beginning of the string if the failure is in the first
+ name/value pair) or the terminating NULL if all was successful.
+
+ @retval EFI_SUCCESS The Results is processed successfully.
+ @retval EFI_INVALID_PARAMETER Configuration is NULL.
+ @retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
+
+**/
+EFI_STATUS
+EFIAPI
+FakeRouteConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Configuration,
+ OUT EFI_STRING *Progress
+ )
+{
+ if (Configuration == NULL || Progress == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *Progress = Configuration;
+ if (!HiiIsConfigHdrMatch (Configuration, &gBootMaintFormSetGuid, mBootMaintStorageName)
+ && !HiiIsConfigHdrMatch (Configuration, &gFileExploreFormSetGuid, mFileExplorerStorageName)) {
+ return EFI_NOT_FOUND;
+ }
+
+ *Progress = Configuration + StrLen (Configuration);
+ return EFI_SUCCESS;
+}
+
+/**
+ This function processes the results of changes in configuration.
+
+
+ @param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action Specifies the type of action taken by the browser.
+ @param QuestionId A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type The type of value for the question.
+ @param Value A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be saved.
+ @retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
+
+**/
+EFI_STATUS
+EFIAPI
+FrontPageCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ )
+{
+ CHAR8 *LangCode;
+ CHAR8 *Lang;
+ UINTN Index;
+
+ if (Action != EFI_BROWSER_ACTION_CHANGING && Action != EFI_BROWSER_ACTION_CHANGED) {
+ //
+ // All other action return unsupported.
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ gCallbackKey = QuestionId;
+
+ if (Action == EFI_BROWSER_ACTION_CHANGED) {
+ if ((Value == NULL) || (ActionRequest == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ switch (QuestionId) {
+ case FRONT_PAGE_KEY_CONTINUE:
+ //
+ // This is the continue - clear the screen and return an error to get out of FrontPage loop
+ //
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+ break;
+
+ case FRONT_PAGE_KEY_LANGUAGE:
+ //
+ // Allocate working buffer for RFC 4646 language in supported LanguageString.
+ //
+ Lang = AllocatePool (AsciiStrSize (mLanguageString));
+ ASSERT (Lang != NULL);
+
+ Index = 0;
+ LangCode = mLanguageString;
+ while (*LangCode != 0) {
+ GetNextLanguage (&LangCode, Lang);
+
+ if (Index == Value->u8) {
+ break;
+ }
+
+ Index++;
+ }
+
+ if (Index == Value->u8) {
+ BdsDxeSetVariableAndReportStatusCodeOnError (
+ L"PlatformLang",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ AsciiStrSize (Lang),
+ Lang
+ );
+ } else {
+ ASSERT (FALSE);
+ }
+
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
+
+ FreePool (Lang);
+ break;
+
+ default:
+ break;
+ }
+ } else if (Action == EFI_BROWSER_ACTION_CHANGING) {
+ if (Value == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // The first 4 entries in the Front Page are to be GUARANTEED to remain constant so IHV's can
+ // describe to their customers in documentation how to find their setup information (namely
+ // under the device manager and specific buckets)
+ //
+ switch (QuestionId) {
+ case FRONT_PAGE_KEY_BOOT_MANAGER:
+ //
+ // Boot Manager
+ //
+ break;
+
+ case FRONT_PAGE_KEY_DEVICE_MANAGER:
+ //
+ // Device Manager
+ //
+ break;
+
+ case FRONT_PAGE_KEY_BOOT_MAINTAIN:
+ //
+ // Boot Maintenance Manager
+ //
+ break;
+
+ default:
+ gCallbackKey = 0;
+ break;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Initialize HII information for the FrontPage
+
+
+ @param InitializeHiiData TRUE if HII elements need to be initialized.
+
+ @retval EFI_SUCCESS The operation is successful.
+ @retval EFI_DEVICE_ERROR If the dynamic opcode creation failed.
+
+**/
+EFI_STATUS
+InitializeFrontPage (
+ IN BOOLEAN InitializeHiiData
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *LangCode;
+ CHAR8 *Lang;
+ UINTN LangSize;
+ CHAR8 *CurrentLang;
+ UINTN OptionCount;
+ CHAR16 *StringBuffer;
+ EFI_HII_HANDLE HiiHandle;
+ VOID *OptionsOpCodeHandle;
+ VOID *StartOpCodeHandle;
+ VOID *EndOpCodeHandle;
+ EFI_IFR_GUID_LABEL *StartLabel;
+ EFI_IFR_GUID_LABEL *EndLabel;
+ EFI_HII_STRING_PROTOCOL *HiiString;
+ UINTN StringSize;
+
+ Lang = NULL;
+ StringBuffer = NULL;
+
+ if (InitializeHiiData) {
+ //
+ // Initialize the Device Manager
+ //
+ InitializeDeviceManager ();
+
+ //
+ // Initialize the Device Manager
+ //
+ InitializeBootManager ();
+
+ gCallbackKey = 0;
+
+ //
+ // Locate Hii relative protocols
+ //
+ Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &gFormBrowser2);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Install Device Path Protocol and Config Access protocol to driver handle
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gFrontPagePrivate.DriverHandle,
+ &gEfiDevicePathProtocolGuid,
+ &mFrontPageHiiVendorDevicePath,
+ &gEfiHiiConfigAccessProtocolGuid,
+ &gFrontPagePrivate.ConfigAccess,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Publish our HII data
+ //
+ gFrontPagePrivate.HiiHandle = HiiAddPackages (
+ &gFrontPageFormSetGuid,
+ gFrontPagePrivate.DriverHandle,
+ FrontPageVfrBin,
+ BdsDxeStrings,
+ NULL
+ );
+ if (gFrontPagePrivate.HiiHandle == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ }
+
+
+ //
+ // Init OpCode Handle and Allocate space for creation of UpdateData Buffer
+ //
+ StartOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (StartOpCodeHandle != NULL);
+
+ EndOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (EndOpCodeHandle != NULL);
+
+ OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
+ ASSERT (OptionsOpCodeHandle != NULL);
+ //
+ // Create Hii Extend Label OpCode as the start opcode
+ //
+ StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ StartLabel->Number = LABEL_SELECT_LANGUAGE;
+
+ //
+ // Create Hii Extend Label OpCode as the end opcode
+ //
+ EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL));
+ EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL;
+ EndLabel->Number = LABEL_END;
+
+ //
+ // Collect the languages from what our current Language support is based on our VFR
+ //
+ HiiHandle = gFrontPagePrivate.HiiHandle;
+
+ GetEfiGlobalVariable2 (L"PlatformLang", (VOID**)&CurrentLang, NULL);
+
+ //
+ // Get Support language list from variable.
+ //
+ if (mLanguageString == NULL){
+ GetEfiGlobalVariable2 (L"PlatformLangCodes", (VOID**)&mLanguageString, NULL);
+ if (mLanguageString == NULL) {
+ mLanguageString = AllocateCopyPool (
+ AsciiStrSize ((CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes)),
+ (CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes)
+ );
+ ASSERT (mLanguageString != NULL);
+ }
+ }
+
+ if (gFrontPagePrivate.LanguageToken == NULL) {
+ //
+ // Count the language list number.
+ //
+ LangCode = mLanguageString;
+ Lang = AllocatePool (AsciiStrSize (mLanguageString));
+ ASSERT (Lang != NULL);
+ OptionCount = 0;
+ while (*LangCode != 0) {
+ GetNextLanguage (&LangCode, Lang);
+ OptionCount ++;
+ }
+
+ //
+ // Allocate extra 1 as the end tag.
+ //
+ gFrontPagePrivate.LanguageToken = AllocateZeroPool ((OptionCount + 1) * sizeof (EFI_STRING_ID));
+ ASSERT (gFrontPagePrivate.LanguageToken != NULL);
+
+ Status = gBS->LocateProtocol (&gEfiHiiStringProtocolGuid, NULL, (VOID **) &HiiString);
+ ASSERT_EFI_ERROR (Status);
+
+ LangCode = mLanguageString;
+ OptionCount = 0;
+ while (*LangCode != 0) {
+ GetNextLanguage (&LangCode, Lang);
+
+ StringSize = 0;
+ Status = HiiString->GetString (HiiString, Lang, HiiHandle, PRINTABLE_LANGUAGE_NAME_STRING_ID, StringBuffer, &StringSize, NULL);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ StringBuffer = AllocateZeroPool (StringSize);
+ ASSERT (StringBuffer != NULL);
+ Status = HiiString->GetString (HiiString, Lang, HiiHandle, PRINTABLE_LANGUAGE_NAME_STRING_ID, StringBuffer, &StringSize, NULL);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ if (EFI_ERROR (Status)) {
+ LangSize = AsciiStrSize (Lang);
+ StringBuffer = AllocatePool (LangSize * sizeof (CHAR16));
+ ASSERT (StringBuffer != NULL);
+ AsciiStrToUnicodeStrS (Lang, StringBuffer, LangSize);
+ }
+
+ ASSERT (StringBuffer != NULL);
+ gFrontPagePrivate.LanguageToken[OptionCount] = HiiSetString (HiiHandle, 0, StringBuffer, NULL);
+ FreePool (StringBuffer);
+
+ OptionCount++;
+ }
+ }
+
+ ASSERT (gFrontPagePrivate.LanguageToken != NULL);
+ LangCode = mLanguageString;
+ OptionCount = 0;
+ if (Lang == NULL) {
+ Lang = AllocatePool (AsciiStrSize (mLanguageString));
+ ASSERT (Lang != NULL);
+ }
+ while (*LangCode != 0) {
+ GetNextLanguage (&LangCode, Lang);
+
+ if (CurrentLang != NULL && AsciiStrCmp (Lang, CurrentLang) == 0) {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ gFrontPagePrivate.LanguageToken[OptionCount],
+ EFI_IFR_OPTION_DEFAULT,
+ EFI_IFR_NUMERIC_SIZE_1,
+ (UINT8) OptionCount
+ );
+ } else {
+ HiiCreateOneOfOptionOpCode (
+ OptionsOpCodeHandle,
+ gFrontPagePrivate.LanguageToken[OptionCount],
+ 0,
+ EFI_IFR_NUMERIC_SIZE_1,
+ (UINT8) OptionCount
+ );
+ }
+
+ OptionCount++;
+ }
+
+ if (CurrentLang != NULL) {
+ FreePool (CurrentLang);
+ }
+ FreePool (Lang);
+
+ HiiCreateOneOfOpCode (
+ StartOpCodeHandle,
+ FRONT_PAGE_KEY_LANGUAGE,
+ 0,
+ 0,
+ STRING_TOKEN (STR_LANGUAGE_SELECT),
+ STRING_TOKEN (STR_LANGUAGE_SELECT_HELP),
+ EFI_IFR_FLAG_CALLBACK,
+ EFI_IFR_NUMERIC_SIZE_1,
+ OptionsOpCodeHandle,
+ NULL
+ );
+
+ Status = HiiUpdateForm (
+ HiiHandle,
+ &gFrontPageFormSetGuid,
+ FRONT_PAGE_FORM_ID,
+ StartOpCodeHandle, // LABEL_SELECT_LANGUAGE
+ EndOpCodeHandle // LABEL_END
+ );
+
+ HiiFreeOpCodeHandle (StartOpCodeHandle);
+ HiiFreeOpCodeHandle (EndOpCodeHandle);
+ HiiFreeOpCodeHandle (OptionsOpCodeHandle);
+ return Status;
+}
+
+/**
+ Call the browser and display the front page
+
+ @return Status code that will be returned by
+ EFI_FORM_BROWSER2_PROTOCOL.SendForm ().
+
+**/
+EFI_STATUS
+CallFrontPage (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_BROWSER_ACTION_REQUEST ActionRequest;
+
+ //
+ // Begin waiting for USER INPUT
+ //
+ REPORT_STATUS_CODE (
+ EFI_PROGRESS_CODE,
+ (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_PC_INPUT_WAIT)
+ );
+
+ ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE;
+ Status = gFormBrowser2->SendForm (
+ gFormBrowser2,
+ &gFrontPagePrivate.HiiHandle,
+ 1,
+ &gFrontPageFormSetGuid,
+ 0,
+ NULL,
+ &ActionRequest
+ );
+ //
+ // Check whether user change any option setting which needs a reset to be effective
+ //
+ if (ActionRequest == EFI_BROWSER_ACTION_REQUEST_RESET) {
+ EnableResetRequired ();
+ }
+
+ return Status;
+}
+
+/**
+ Acquire the string associated with the ProducerGuid and return it.
+
+
+ @param ProducerGuid The Guid to search the HII database for
+ @param Token The token value of the string to extract
+ @param String The string that is extracted
+
+ @retval EFI_SUCCESS The function returns EFI_SUCCESS always.
+
+**/
+EFI_STATUS
+GetProducerString (
+ IN EFI_GUID *ProducerGuid,
+ IN EFI_STRING_ID Token,
+ OUT CHAR16 **String
+ )
+{
+ EFI_STRING TmpString;
+
+ TmpString = HiiGetPackageString (ProducerGuid, Token, NULL);
+ if (TmpString == NULL) {
+ *String = GetStringById (STRING_TOKEN (STR_MISSING_STRING));
+ } else {
+ *String = TmpString;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Convert Processor Frequency Data to a string.
+
+ @param ProcessorFrequency The frequency data to process
+ @param Base10Exponent The exponent based on 10
+ @param String The string that is created
+
+**/
+VOID
+ConvertProcessorToString (
+ IN UINT16 ProcessorFrequency,
+ IN UINT16 Base10Exponent,
+ OUT CHAR16 **String
+ )
+{
+ CHAR16 *StringBuffer;
+ UINTN Index;
+ UINT32 FreqMhz;
+
+ if (Base10Exponent >= 6) {
+ FreqMhz = ProcessorFrequency;
+ for (Index = 0; Index < ((UINT32)Base10Exponent - 6); Index++) {
+ FreqMhz *= 10;
+ }
+ } else {
+ FreqMhz = 0;
+ }
+
+ StringBuffer = AllocateZeroPool (0x20);
+ ASSERT (StringBuffer != NULL);
+ UnicodeValueToStringS (StringBuffer, 0x20, LEFT_JUSTIFY, FreqMhz / 1000, 3);
+ Index = StrnLenS (StringBuffer, 0x20 / sizeof (CHAR16));
+ StrCatS (StringBuffer, 0x20 / sizeof (CHAR16), L".");
+ UnicodeValueToStringS (
+ StringBuffer + Index + 1,
+ 0x20 - sizeof (CHAR16) * (Index + 1),
+ PREFIX_ZERO,
+ (FreqMhz % 1000) / 10,
+ 2
+ );
+ StrCatS (StringBuffer, 0x20 / sizeof (CHAR16), L" GHz");
+ *String = (CHAR16 *) StringBuffer;
+ return ;
+}
+
+
+/**
+ Convert Memory Size to a string.
+
+ @param MemorySize The size of the memory to process
+ @param String The string that is created
+
+**/
+VOID
+ConvertMemorySizeToString (
+ IN UINT32 MemorySize,
+ OUT CHAR16 **String
+ )
+{
+ CHAR16 *StringBuffer;
+
+ StringBuffer = AllocateZeroPool (0x20);
+ ASSERT (StringBuffer != NULL);
+ UnicodeValueToStringS (StringBuffer, 0x20, LEFT_JUSTIFY, MemorySize, 6);
+ StrCatS (StringBuffer, 0x20 / sizeof (CHAR16), L" MB RAM");
+
+ *String = (CHAR16 *) StringBuffer;
+
+ return ;
+}
+
+/**
+
+ Acquire the string associated with the Index from smbios structure and return it.
+ The caller is responsible for free the string buffer.
+
+ @param OptionalStrStart The start position to search the string
+ @param Index The index of the string to extract
+ @param String The string that is extracted
+
+ @retval EFI_SUCCESS The function returns EFI_SUCCESS always.
+
+**/
+EFI_STATUS
+GetOptionalStringByIndex (
+ IN CHAR8 *OptionalStrStart,
+ IN UINT8 Index,
+ OUT CHAR16 **String
+ )
+{
+ UINTN StrSize;
+
+ if (Index == 0) {
+ *String = AllocateZeroPool (sizeof (CHAR16));
+ return EFI_SUCCESS;
+ }
+
+ StrSize = 0;
+ do {
+ Index--;
+ OptionalStrStart += StrSize;
+ StrSize = AsciiStrSize (OptionalStrStart);
+ } while (OptionalStrStart[StrSize] != 0 && Index != 0);
+
+ if ((Index != 0) || (StrSize == 1)) {
+ //
+ // Meet the end of strings set but Index is non-zero, or
+ // Find an empty string
+ //
+ *String = GetStringById (STRING_TOKEN (STR_MISSING_STRING));
+ } else {
+ *String = AllocatePool (StrSize * sizeof (CHAR16));
+ AsciiStrToUnicodeStrS (OptionalStrStart, *String, StrSize);
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Update the banner information for the Front Page based on DataHub information.
+
+**/
+VOID
+UpdateFrontPageStrings (
+ VOID
+ )
+{
+ UINT8 StrIndex;
+ CHAR16 *NewString;
+ EFI_STATUS Status;
+ EFI_STRING_ID TokenToUpdate;
+ EFI_SMBIOS_HANDLE SmbiosHandle;
+ EFI_SMBIOS_PROTOCOL *Smbios;
+ SMBIOS_TABLE_TYPE0 *Type0Record;
+ SMBIOS_TABLE_TYPE1 *Type1Record;
+ SMBIOS_TABLE_TYPE4 *Type4Record;
+ SMBIOS_TABLE_TYPE19 *Type19Record;
+ EFI_SMBIOS_TABLE_HEADER *Record;
+ UINT64 InstalledMemory;
+
+ InstalledMemory = 0;
+
+ //
+ // Update Front Page strings
+ //
+ Status = gBS->LocateProtocol (
+ &gEfiSmbiosProtocolGuid,
+ NULL,
+ (VOID **) &Smbios
+ );
+ if (!EFI_ERROR (Status)) {
+ SmbiosHandle = SMBIOS_HANDLE_PI_RESERVED;
+ Status = Smbios->GetNext (Smbios, &SmbiosHandle, NULL, &Record, NULL);
+ while (!EFI_ERROR(Status)) {
+ if (Record->Type == SMBIOS_TYPE_BIOS_INFORMATION) {
+ Type0Record = (SMBIOS_TABLE_TYPE0 *) Record;
+ StrIndex = Type0Record->BiosVersion;
+ GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type0Record + Type0Record->Hdr.Length), StrIndex, &NewString);
+ TokenToUpdate = STRING_TOKEN (STR_FRONT_PAGE_BIOS_VERSION);
+ HiiSetString (gFrontPagePrivate.HiiHandle, TokenToUpdate, NewString, NULL);
+ FreePool (NewString);
+ }
+
+ if (Record->Type == SMBIOS_TYPE_SYSTEM_INFORMATION) {
+ Type1Record = (SMBIOS_TABLE_TYPE1 *) Record;
+ StrIndex = Type1Record->ProductName;
+ GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type1Record + Type1Record->Hdr.Length), StrIndex, &NewString);
+ TokenToUpdate = STRING_TOKEN (STR_FRONT_PAGE_COMPUTER_MODEL);
+ HiiSetString (gFrontPagePrivate.HiiHandle, TokenToUpdate, NewString, NULL);
+ FreePool (NewString);
+ }
+
+ if (Record->Type == SMBIOS_TYPE_PROCESSOR_INFORMATION) {
+ Type4Record = (SMBIOS_TABLE_TYPE4 *) Record;
+ StrIndex = Type4Record->ProcessorVersion;
+ GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type4Record + Type4Record->Hdr.Length), StrIndex, &NewString);
+ TokenToUpdate = STRING_TOKEN (STR_FRONT_PAGE_CPU_MODEL);
+ HiiSetString (gFrontPagePrivate.HiiHandle, TokenToUpdate, NewString, NULL);
+ FreePool (NewString);
+ }
+
+ if (Record->Type == SMBIOS_TYPE_PROCESSOR_INFORMATION) {
+ Type4Record = (SMBIOS_TABLE_TYPE4 *) Record;
+ ConvertProcessorToString(Type4Record->CurrentSpeed, 6, &NewString);
+ TokenToUpdate = STRING_TOKEN (STR_FRONT_PAGE_CPU_SPEED);
+ HiiSetString (gFrontPagePrivate.HiiHandle, TokenToUpdate, NewString, NULL);
+ FreePool (NewString);
+ }
+
+ if ( Record->Type == SMBIOS_TYPE_MEMORY_ARRAY_MAPPED_ADDRESS ) {
+ Type19Record = (SMBIOS_TABLE_TYPE19 *) Record;
+ if (Type19Record->StartingAddress != 0xFFFFFFFF ) {
+ InstalledMemory += RShiftU64(Type19Record->EndingAddress -
+ Type19Record->StartingAddress + 1, 10);
+ } else {
+ InstalledMemory += RShiftU64(Type19Record->ExtendedEndingAddress -
+ Type19Record->ExtendedStartingAddress + 1, 20);
+ }
+ }
+
+ Status = Smbios->GetNext (Smbios, &SmbiosHandle, NULL, &Record, NULL);
+ }
+
+ // now update the total installed RAM size
+ ConvertMemorySizeToString ((UINT32)InstalledMemory, &NewString );
+ TokenToUpdate = STRING_TOKEN (STR_FRONT_PAGE_MEMORY_SIZE);
+ HiiSetString (gFrontPagePrivate.HiiHandle, TokenToUpdate, NewString, NULL);
+ FreePool (NewString);
+ }
+
+ return ;
+}
+
+
+/**
+ Function waits for a given event to fire, or for an optional timeout to expire.
+
+ @param Event The event to wait for
+ @param Timeout An optional timeout value in 100 ns units.
+
+ @retval EFI_SUCCESS Event fired before Timeout expired.
+ @retval EFI_TIME_OUT Timout expired before Event fired..
+
+**/
+EFI_STATUS
+WaitForSingleEvent (
+ IN EFI_EVENT Event,
+ IN UINT64 Timeout OPTIONAL
+ )
+{
+ UINTN Index;
+ EFI_STATUS Status;
+ EFI_EVENT TimerEvent;
+ EFI_EVENT WaitList[2];
+
+ if (Timeout != 0) {
+ //
+ // Create a timer event
+ //
+ Status = gBS->CreateEvent (EVT_TIMER, 0, NULL, NULL, &TimerEvent);
+ if (!EFI_ERROR (Status)) {
+ //
+ // Set the timer event
+ //
+ gBS->SetTimer (
+ TimerEvent,
+ TimerRelative,
+ Timeout
+ );
+
+ //
+ // Wait for the original event or the timer
+ //
+ WaitList[0] = Event;
+ WaitList[1] = TimerEvent;
+ Status = gBS->WaitForEvent (2, WaitList, &Index);
+ gBS->CloseEvent (TimerEvent);
+
+ //
+ // If the timer expired, change the return to timed out
+ //
+ if (!EFI_ERROR (Status) && Index == 1) {
+ Status = EFI_TIMEOUT;
+ }
+ }
+ } else {
+ //
+ // No timeout... just wait on the event
+ //
+ Status = gBS->WaitForEvent (1, &Event, &Index);
+ ASSERT (!EFI_ERROR (Status));
+ ASSERT (Index == 0);
+ }
+
+ return Status;
+}
+
+/**
+ Function show progress bar to wait for user input.
+
+
+ @param TimeoutDefault The fault time out value before the system continue to boot.
+
+ @retval EFI_SUCCESS User pressed some key except "Enter"
+ @retval EFI_TIME_OUT Timeout expired or user press "Enter"
+
+**/
+EFI_STATUS
+ShowProgress (
+ IN UINT16 TimeoutDefault
+ )
+{
+ CHAR16 *TmpStr;
+ UINT16 TimeoutRemain;
+ EFI_STATUS Status;
+ EFI_INPUT_KEY Key;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Foreground;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Background;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Color;
+
+ if (TimeoutDefault != 0) {
+ DEBUG ((EFI_D_INFO, "\n\nStart showing progress bar... Press any key to stop it! ...Zzz....\n"));
+
+ SetMem (&Foreground, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);
+ SetMem (&Background, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
+ SetMem (&Color, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);
+
+ TmpStr = GetStringById (STRING_TOKEN (STR_START_BOOT_OPTION));
+
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ //
+ // Clear the progress status bar first
+ //
+ if (TmpStr != NULL) {
+ PlatformBdsShowProgress (Foreground, Background, TmpStr, Color, 0, 0);
+ }
+ }
+
+
+ TimeoutRemain = TimeoutDefault;
+ while (TimeoutRemain != 0) {
+ DEBUG ((EFI_D_INFO, "Showing progress bar...Remaining %d second!\n", TimeoutRemain));
+
+ Status = WaitForSingleEvent (gST->ConIn->WaitForKey, ONE_SECOND);
+ if (Status != EFI_TIMEOUT) {
+ break;
+ }
+ TimeoutRemain--;
+
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ //
+ // Show progress
+ //
+ if (TmpStr != NULL) {
+ PlatformBdsShowProgress (
+ Foreground,
+ Background,
+ TmpStr,
+ Color,
+ ((TimeoutDefault - TimeoutRemain) * 100 / TimeoutDefault),
+ 0
+ );
+ }
+ }
+ }
+
+ if (TmpStr != NULL) {
+ gBS->FreePool (TmpStr);
+ }
+
+ //
+ // Timeout expired
+ //
+ if (TimeoutRemain == 0) {
+ return EFI_TIMEOUT;
+ }
+ }
+
+ //
+ // User pressed some key
+ //
+ if (!PcdGetBool (PcdConInConnectOnDemand)) {
+ Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ if (Key.UnicodeChar == CHAR_CARRIAGE_RETURN) {
+ //
+ // User pressed enter, equivalent to select "continue"
+ //
+ return EFI_TIMEOUT;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function is the main entry of the platform setup entry.
+ The function will present the main menu of the system setup,
+ this is the platform reference part and can be customize.
+
+
+ @param TimeoutDefault The fault time out value before the system
+ continue to boot.
+ @param ConnectAllHappened The indicater to check if the connect all have
+ already happened.
+
+**/
+VOID
+PlatformBdsEnterFrontPage (
+ IN UINT16 TimeoutDefault,
+ IN BOOLEAN ConnectAllHappened
+ )
+{
+ EFI_STATUS Status;
+ EFI_STATUS StatusHotkey;
+ EFI_BOOT_LOGO_PROTOCOL *BootLogo;
+ EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut;
+ UINTN BootTextColumn;
+ UINTN BootTextRow;
+ UINT64 OsIndication;
+ UINTN DataSize;
+ EFI_INPUT_KEY Key;
+
+ GraphicsOutput = NULL;
+ SimpleTextOut = NULL;
+
+ PERF_START (NULL, "BdsTimeOut", "BDS", 0);
+ //
+ // Indicate if we need connect all in the platform setup
+ //
+ if (ConnectAllHappened) {
+ gConnectAllHappened = TRUE;
+ }
+
+ if (!mModeInitialized) {
+ //
+ // After the console is ready, get current video resolution
+ // and text mode before launching setup at first time.
+ //
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiGraphicsOutputProtocolGuid,
+ (VOID**)&GraphicsOutput
+ );
+ if (EFI_ERROR (Status)) {
+ GraphicsOutput = NULL;
+ }
+
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiSimpleTextOutProtocolGuid,
+ (VOID**)&SimpleTextOut
+ );
+ if (EFI_ERROR (Status)) {
+ SimpleTextOut = NULL;
+ }
+
+ if (GraphicsOutput != NULL) {
+ //
+ // Get current video resolution and text mode.
+ //
+ mBootHorizontalResolution = GraphicsOutput->Mode->Info->HorizontalResolution;
+ mBootVerticalResolution = GraphicsOutput->Mode->Info->VerticalResolution;
+ }
+
+ if (SimpleTextOut != NULL) {
+ Status = SimpleTextOut->QueryMode (
+ SimpleTextOut,
+ SimpleTextOut->Mode->Mode,
+ &BootTextColumn,
+ &BootTextRow
+ );
+ mBootTextModeColumn = (UINT32)BootTextColumn;
+ mBootTextModeRow = (UINT32)BootTextRow;
+ }
+
+ //
+ // Get user defined text mode for setup.
+ //
+ mSetupHorizontalResolution = PcdGet32 (PcdSetupVideoHorizontalResolution);
+ mSetupVerticalResolution = PcdGet32 (PcdSetupVideoVerticalResolution);
+ mSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn);
+ mSetupTextModeRow = PcdGet32 (PcdSetupConOutRow);
+
+ mModeInitialized = TRUE;
+ }
+
+
+ //
+ // goto FrontPage directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set
+ //
+ OsIndication = 0;
+ DataSize = sizeof(UINT64);
+ Status = gRT->GetVariable (
+ L"OsIndications",
+ &gEfiGlobalVariableGuid,
+ NULL,
+ &DataSize,
+ &OsIndication
+ );
+
+ //
+ // goto FrontPage directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
+ //
+ if (!EFI_ERROR(Status) && ((OsIndication & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0)) {
+ //
+ // Clear EFI_OS_INDICATIONS_BOOT_TO_FW_UI to acknowledge OS
+ //
+ OsIndication &= ~((UINT64)EFI_OS_INDICATIONS_BOOT_TO_FW_UI);
+ Status = gRT->SetVariable (
+ L"OsIndications",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof(UINT64),
+ &OsIndication
+ );
+ //
+ // Changing the content without increasing its size with current variable implementation shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Follow generic rule, Call ReadKeyStroke to connect ConIn before enter UI
+ //
+ if (PcdGetBool (PcdConInConnectOnDemand)) {
+ gST->ConIn->ReadKeyStroke(gST->ConIn, &Key);
+ }
+
+ //
+ // Ensure screen is clear when switch Console from Graphics mode to Text mode
+ //
+ gST->ConOut->EnableCursor (gST->ConOut, TRUE);
+ gST->ConOut->ClearScreen (gST->ConOut);
+
+ } else {
+
+ HotkeyBoot ();
+ if (TimeoutDefault != 0xffff) {
+ Status = ShowProgress (TimeoutDefault);
+ StatusHotkey = HotkeyBoot ();
+
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable) || !EFI_ERROR(Status) || !EFI_ERROR(StatusHotkey)){
+ //
+ // Ensure screen is clear when switch Console from Graphics mode to Text mode
+ // Skip it in normal boot
+ //
+ gST->ConOut->EnableCursor (gST->ConOut, TRUE);
+ gST->ConOut->ClearScreen (gST->ConOut);
+ }
+
+ if (EFI_ERROR (Status)) {
+ //
+ // Timeout or user press enter to continue
+ //
+ goto Exit;
+ }
+ }
+ }
+
+ //
+ // Boot Logo is corrupted, report it using Boot Logo protocol.
+ //
+ Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo);
+ if (!EFI_ERROR (Status) && (BootLogo != NULL)) {
+ BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0);
+ }
+
+ //
+ // Install BM HiiPackages.
+ // Keep BootMaint HiiPackage, so that it can be covered by global setting.
+ //
+ InitBMPackage ();
+
+ Status = EFI_SUCCESS;
+ do {
+ //
+ // Set proper video resolution and text mode for setup
+ //
+ BdsSetConsoleMode (TRUE);
+
+ InitializeFrontPage (FALSE);
+
+ //
+ // Update Front Page strings
+ //
+ UpdateFrontPageStrings ();
+
+ gCallbackKey = 0;
+ CallFrontPage ();
+
+ //
+ // If gCallbackKey is greater than 1 and less or equal to 5,
+ // it will launch configuration utilities.
+ // 2 = set language
+ // 3 = boot manager
+ // 4 = device manager
+ // 5 = boot maintenance manager
+ //
+ if (gCallbackKey != 0) {
+ REPORT_STATUS_CODE (
+ EFI_PROGRESS_CODE,
+ (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_PC_USER_SETUP)
+ );
+ }
+ //
+ // Based on the key that was set, we can determine what to do
+ //
+ switch (gCallbackKey) {
+ //
+ // The first 4 entries in the Front Page are to be GUARANTEED to remain constant so IHV's can
+ // describe to their customers in documentation how to find their setup information (namely
+ // under the device manager and specific buckets)
+ //
+ // These entries consist of the Continue, Select language, Boot Manager, and Device Manager
+ //
+ case FRONT_PAGE_KEY_CONTINUE:
+ //
+ // User hit continue
+ //
+ break;
+
+ case FRONT_PAGE_KEY_LANGUAGE:
+ //
+ // User made a language setting change - display front page again
+ //
+ break;
+
+ case FRONT_PAGE_KEY_BOOT_MANAGER:
+ //
+ // Remove the installed BootMaint HiiPackages when exit.
+ //
+ FreeBMPackage ();
+
+ //
+ // User chose to run the Boot Manager
+ //
+ CallBootManager ();
+
+ //
+ // Reinstall BootMaint HiiPackages after exiting from Boot Manager.
+ //
+ InitBMPackage ();
+ break;
+
+ case FRONT_PAGE_KEY_DEVICE_MANAGER:
+ //
+ // Display the Device Manager
+ //
+ do {
+ CallDeviceManager ();
+ } while (gCallbackKey == FRONT_PAGE_KEY_DEVICE_MANAGER);
+ break;
+
+ case FRONT_PAGE_KEY_BOOT_MAINTAIN:
+ //
+ // Display the Boot Maintenance Manager
+ //
+ BdsStartBootMaint ();
+ break;
+ }
+
+ } while ((Status == EFI_SUCCESS) && (gCallbackKey != FRONT_PAGE_KEY_CONTINUE));
+
+ if (mLanguageString != NULL) {
+ FreePool (mLanguageString);
+ mLanguageString = NULL;
+ }
+ //
+ //Will leave browser, check any reset required change is applied? if yes, reset system
+ //
+ SetupResetReminder ();
+
+ //
+ // Remove the installed BootMaint HiiPackages when exit.
+ //
+ FreeBMPackage ();
+
+Exit:
+ //
+ // Automatically load current entry
+ // Note: The following lines of code only execute when Auto boot
+ // takes affect
+ //
+ PERF_END (NULL, "BdsTimeOut", "BDS", 0);
+}
+
+/**
+ This function will change video resolution and text mode
+ according to defined setup mode or defined boot mode
+
+ @param IsSetupMode Indicate mode is changed to setup mode or boot mode.
+
+ @retval EFI_SUCCESS Mode is changed successfully.
+ @retval Others Mode failed to be changed.
+
+**/
+EFI_STATUS
+EFIAPI
+BdsSetConsoleMode (
+ BOOLEAN IsSetupMode
+ )
+{
+ EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut;
+ UINTN SizeOfInfo;
+ EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
+ UINT32 MaxGopMode;
+ UINT32 MaxTextMode;
+ UINT32 ModeNumber;
+ UINT32 NewHorizontalResolution;
+ UINT32 NewVerticalResolution;
+ UINT32 NewColumns;
+ UINT32 NewRows;
+ UINTN HandleCount;
+ EFI_HANDLE *HandleBuffer;
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN CurrentColumn;
+ UINTN CurrentRow;
+
+ MaxGopMode = 0;
+ MaxTextMode = 0;
+
+ //
+ // Get current video resolution and text mode
+ //
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiGraphicsOutputProtocolGuid,
+ (VOID**)&GraphicsOutput
+ );
+ if (EFI_ERROR (Status)) {
+ GraphicsOutput = NULL;
+ }
+
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiSimpleTextOutProtocolGuid,
+ (VOID**)&SimpleTextOut
+ );
+ if (EFI_ERROR (Status)) {
+ SimpleTextOut = NULL;
+ }
+
+ if ((GraphicsOutput == NULL) || (SimpleTextOut == NULL)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ if (IsSetupMode) {
+ //
+ // The required resolution and text mode is setup mode.
+ //
+ NewHorizontalResolution = mSetupHorizontalResolution;
+ NewVerticalResolution = mSetupVerticalResolution;
+ NewColumns = mSetupTextModeColumn;
+ NewRows = mSetupTextModeRow;
+ } else {
+ //
+ // The required resolution and text mode is boot mode.
+ //
+ NewHorizontalResolution = mBootHorizontalResolution;
+ NewVerticalResolution = mBootVerticalResolution;
+ NewColumns = mBootTextModeColumn;
+ NewRows = mBootTextModeRow;
+ }
+
+ if (GraphicsOutput != NULL) {
+ MaxGopMode = GraphicsOutput->Mode->MaxMode;
+ }
+
+ if (SimpleTextOut != NULL) {
+ MaxTextMode = SimpleTextOut->Mode->MaxMode;
+ }
+
+ //
+ // 1. If current video resolution is same with required video resolution,
+ // video resolution need not be changed.
+ // 1.1. If current text mode is same with required text mode, text mode need not be changed.
+ // 1.2. If current text mode is different from required text mode, text mode need be changed.
+ // 2. If current video resolution is different from required video resolution, we need restart whole console drivers.
+ //
+ for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) {
+ Status = GraphicsOutput->QueryMode (
+ GraphicsOutput,
+ ModeNumber,
+ &SizeOfInfo,
+ &Info
+ );
+ if (!EFI_ERROR (Status)) {
+ if ((Info->HorizontalResolution == NewHorizontalResolution) &&
+ (Info->VerticalResolution == NewVerticalResolution)) {
+ if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) &&
+ (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) {
+ //
+ // Current resolution is same with required resolution, check if text mode need be set
+ //
+ Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow);
+ ASSERT_EFI_ERROR (Status);
+ if (CurrentColumn == NewColumns && CurrentRow == NewRows) {
+ //
+ // If current text mode is same with required text mode. Do nothing
+ //
+ FreePool (Info);
+ return EFI_SUCCESS;
+ } else {
+ //
+ // If current text mode is different from required text mode. Set new video mode
+ //
+ for (Index = 0; Index < MaxTextMode; Index++) {
+ Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow);
+ if (!EFI_ERROR(Status)) {
+ if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) {
+ //
+ // Required text mode is supported, set it.
+ //
+ Status = SimpleTextOut->SetMode (SimpleTextOut, Index);
+ ASSERT_EFI_ERROR (Status);
+ //
+ // Update text mode PCD.
+ //
+ Status = PcdSet32S (PcdConOutColumn, mSetupTextModeColumn);
+ ASSERT_EFI_ERROR (Status);
+ Status = PcdSet32S (PcdConOutRow, mSetupTextModeRow);
+ ASSERT_EFI_ERROR (Status);
+ FreePool (Info);
+ return EFI_SUCCESS;
+ }
+ }
+ }
+ if (Index == MaxTextMode) {
+ //
+ // If required text mode is not supported, return error.
+ //
+ FreePool (Info);
+ return EFI_UNSUPPORTED;
+ }
+ }
+ } else {
+ //
+ // If current video resolution is not same with the new one, set new video resolution.
+ // In this case, the driver which produces simple text out need be restarted.
+ //
+ Status = GraphicsOutput->SetMode (GraphicsOutput, ModeNumber);
+ if (!EFI_ERROR (Status)) {
+ FreePool (Info);
+ break;
+ }
+ }
+ }
+ FreePool (Info);
+ }
+ }
+
+ if (ModeNumber == MaxGopMode) {
+ //
+ // If the resolution is not supported, return error.
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ //
+ // Set PCD to Inform GraphicsConsole to change video resolution.
+ // Set PCD to Inform Consplitter to change text mode.
+ //
+ Status = PcdSet32S (PcdVideoHorizontalResolution, NewHorizontalResolution);
+ ASSERT_EFI_ERROR (Status);
+ Status = PcdSet32S (PcdVideoVerticalResolution, NewVerticalResolution);
+ ASSERT_EFI_ERROR (Status);
+ Status = PcdSet32S (PcdConOutColumn, NewColumns);
+ ASSERT_EFI_ERROR (Status);
+ Status = PcdSet32S (PcdConOutRow, NewRows);
+ ASSERT_EFI_ERROR (Status);
+
+
+ //
+ // Video mode is changed, so restart graphics console driver and higher level driver.
+ // Reconnect graphics console driver and higher level driver.
+ // Locate all the handles with GOP protocol and reconnect it.
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiSimpleTextOutProtocolGuid,
+ NULL,
+ &HandleCount,
+ &HandleBuffer
+ );
+ if (!EFI_ERROR (Status)) {
+ for (Index = 0; Index < HandleCount; Index++) {
+ gBS->DisconnectController (HandleBuffer[Index], NULL, NULL);
+ }
+ for (Index = 0; Index < HandleCount; Index++) {
+ gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE);
+ }
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.h
new file mode 100644
index 0000000000..a7b1c5bca0
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPage.h
@@ -0,0 +1,254 @@
+/** @file
+ FrontPage routines to handle the callbacks and browser calls
+
+Copyright (c) 2004 - 2012, 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 _FRONT_PAGE_H_
+#define _FRONT_PAGE_H_
+
+#include "DeviceMngr/DeviceManager.h"
+#include "BootMaint/BootMaint.h"
+#include "BootMngr/BootManager.h"
+#include "String.h"
+
+
+//
+// These are the VFR compiler generated data representing our VFR data.
+//
+extern UINT8 FrontPageVfrBin[];
+
+extern EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2;
+
+extern UINTN gCallbackKey;
+extern BOOLEAN gConnectAllHappened;
+
+//
+// Boot video resolution and text mode.
+//
+extern UINT32 mBootHorizontalResolution;
+extern UINT32 mBootVerticalResolution;
+extern UINT32 mBootTextModeColumn;
+extern UINT32 mBootTextModeRow;
+//
+// BIOS setup video resolution and text mode.
+//
+extern UINT32 mSetupTextModeColumn;
+extern UINT32 mSetupTextModeRow;
+extern UINT32 mSetupHorizontalResolution;
+extern UINT32 mSetupVerticalResolution;
+
+
+#define ONE_SECOND 10000000
+
+///
+/// The size of a 3 character ISO639 language code.
+///
+#define ISO_639_2_ENTRY_SIZE 3
+
+//
+// This is the VFR compiler generated header file which defines the
+// string identifiers.
+//
+#define PRINTABLE_LANGUAGE_NAME_STRING_ID 0x0001
+
+//
+// These are defined as the same with vfr file
+//
+#define FRONT_PAGE_FORM_ID 0x1000
+
+#define FRONT_PAGE_KEY_CONTINUE 0x1000
+#define FRONT_PAGE_KEY_LANGUAGE 0x1234
+#define FRONT_PAGE_KEY_BOOT_MANAGER 0x1064
+#define FRONT_PAGE_KEY_DEVICE_MANAGER 0x8567
+#define FRONT_PAGE_KEY_BOOT_MAINTAIN 0x9876
+
+#define LABEL_SELECT_LANGUAGE 0x1000
+#define LABEL_END 0xffff
+
+#define FRONT_PAGE_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('F', 'P', 'C', 'B')
+
+typedef struct {
+ UINTN Signature;
+
+ //
+ // HII relative handles
+ //
+ EFI_HII_HANDLE HiiHandle;
+ EFI_HANDLE DriverHandle;
+ EFI_STRING_ID *LanguageToken;
+
+ //
+ // Produced protocols
+ //
+ EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess;
+} FRONT_PAGE_CALLBACK_DATA;
+
+#define EFI_FP_CALLBACK_DATA_FROM_THIS(a) \
+ CR (a, \
+ FRONT_PAGE_CALLBACK_DATA, \
+ ConfigAccess, \
+ FRONT_PAGE_CALLBACK_DATA_SIGNATURE \
+ )
+
+/**
+ This function allows a caller to extract the current configuration for one
+ or more named elements from the target driver.
+
+
+ @param This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Request - A null-terminated Unicode string in <ConfigRequest> format.
+ @param Progress - On return, points to a character in the Request string.
+ Points to the string's null terminator if request was successful.
+ Points to the most recent '&' before the first failing name/value
+ pair (or the beginning of the string if the failure is in the
+ first name/value pair) if the request was not successful.
+ @param Results - A null-terminated Unicode string in <ConfigAltResp> format which
+ has all values filled in for the names in the Request string.
+ String to be allocated by the called function.
+
+ @retval EFI_SUCCESS The Results is filled with the requested values.
+ @retval EFI_OUT_OF_RESOURCES Not enough memory to store the results.
+ @retval EFI_INVALID_PARAMETER Request is NULL, illegal syntax, or unknown name.
+ @retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
+
+**/
+EFI_STATUS
+EFIAPI
+FakeExtractConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Request,
+ OUT EFI_STRING *Progress,
+ OUT EFI_STRING *Results
+ );
+
+/**
+ This function processes the results of changes in configuration.
+
+
+ @param This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Configuration - A null-terminated Unicode string in <ConfigResp> format.
+ @param Progress - A pointer to a string filled in with the offset of the most
+ recent '&' before the first failing name/value pair (or the
+ beginning of the string if the failure is in the first
+ name/value pair) or the terminating NULL if all was successful.
+
+ @retval EFI_SUCCESS The Results is processed successfully.
+ @retval EFI_INVALID_PARAMETER Configuration is NULL.
+ @retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
+
+**/
+EFI_STATUS
+EFIAPI
+FakeRouteConfig (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN CONST EFI_STRING Configuration,
+ OUT EFI_STRING *Progress
+ );
+
+/**
+ This function processes the results of changes in configuration.
+
+
+ @param This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
+ @param Action - Specifies the type of action taken by the browser.
+ @param QuestionId - A unique value which is sent to the original exporting driver
+ so that it can identify the type of data to expect.
+ @param Type - The type of value for the question.
+ @param Value - A pointer to the data being sent to the original exporting driver.
+ @param ActionRequest - On return, points to the action requested by the callback function.
+
+ @retval EFI_SUCCESS The callback successfully handled the action.
+ @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
+ @retval EFI_DEVICE_ERROR The variable could not be saved.
+ @retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
+
+**/
+EFI_STATUS
+EFIAPI
+FrontPageCallback (
+ IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
+ IN EFI_BROWSER_ACTION Action,
+ IN EFI_QUESTION_ID QuestionId,
+ IN UINT8 Type,
+ IN EFI_IFR_TYPE_VALUE *Value,
+ OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
+ );
+
+/**
+ Initialize HII information for the FrontPage
+
+
+ @param InitializeHiiData TRUE if HII elements need to be initialized.
+
+ @retval EFI_SUCCESS The operation is successful.
+ @retval EFI_DEVICE_ERROR If the dynamic opcode creation failed.
+
+**/
+EFI_STATUS
+InitializeFrontPage (
+ IN BOOLEAN InitializeHiiData
+ );
+
+/**
+ Acquire the string associated with the ProducerGuid and return it.
+
+
+ @param ProducerGuid - The Guid to search the HII database for
+ @param Token - The token value of the string to extract
+ @param String - The string that is extracted
+
+ @retval EFI_SUCCESS The function returns EFI_SUCCESS always.
+
+**/
+EFI_STATUS
+GetProducerString (
+ IN EFI_GUID *ProducerGuid,
+ IN EFI_STRING_ID Token,
+ OUT CHAR16 **String
+ );
+
+/**
+ This function is the main entry of the platform setup entry.
+ The function will present the main menu of the system setup,
+ this is the platform reference part and can be customize.
+
+
+ @param TimeoutDefault - The fault time out value before the system
+ continue to boot.
+ @param ConnectAllHappened - The indicater to check if the connect all have
+ already happened.
+
+**/
+VOID
+PlatformBdsEnterFrontPage (
+ IN UINT16 TimeoutDefault,
+ IN BOOLEAN ConnectAllHappened
+ );
+
+/**
+ This function will change video resolution and text mode
+ according to defined setup mode or defined boot mode
+
+ @param IsSetupMode Indicate mode is changed to setup mode or boot mode.
+
+ @retval EFI_SUCCESS Mode is changed successfully.
+ @retval Others Mode failed to be changed.
+
+**/
+EFI_STATUS
+EFIAPI
+BdsSetConsoleMode (
+ BOOLEAN IsSetupMode
+ );
+
+#endif // _FRONT_PAGE_H_
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageStrings.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageStrings.uni
new file mode 100644
index 0000000000..84f8fb4770
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageStrings.uni
@@ -0,0 +1,70 @@
+///** @file
+//
+// String definitions for BdsPlatform formset.
+//
+// Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//**/
+
+/=#
+
+#langdef en-US "English"
+#langdef fr-FR "Français"
+#langdef en "Standard English"
+#langdef fr "Standard Français"
+
+#string STR_FRONT_PAGE_TITLE #language en-US "Front Page"
+ #language fr-FR "Front Page"
+#string STR_FRONT_PAGE_COMPUTER_MODEL #language en-US ""
+ #language fr-FR ""
+#string STR_FRONT_PAGE_CPU_MODEL #language en-US ""
+ #language fr-FR ""
+#string STR_FRONT_PAGE_CPU_SPEED #language en-US ""
+ #language fr-FR ""
+#string STR_FRONT_PAGE_MEMORY_SIZE #language en-US ""
+ #language fr-FR ""
+#string STR_FRONT_PAGE_BIOS_VERSION #language en-US ""
+ #language fr-FR ""
+#string STR_FRONT_PAGE_BANNER_0_LEFT #language en-US "Wonder Computer Model 1000Z Manufactured by Intel®"
+ #language fr-FR "Demander le Modèle d'Ordinateur 1000Z A Fabriqué par Intel®"
+#string STR_FRONT_PAGE_BANNER_0_RIGHT #language en-US "OK"
+ #language fr-FR "Bon"
+#string STR_FRONT_PAGE_BANNER_1_LEFT #language en-US "2 Pentium® X Xeon processors running at 800Thz"
+ #language fr-FR "2 Pentium® X les processeurs de Xeon courants à 800Thz"
+#string STR_FRONT_PAGE_BANNER_1_RIGHT #language en-US "24 TB System RAM"
+ #language fr-FR "24 TB RAM de Système"
+#string STR_FRONT_PAGE_BANNER_2_LEFT #language en-US "ACME® EFI BIOS Version 13.5 Release 1039.92"
+ #language fr-FR "ACME® EFI BIOS Version 13.5 Release 1039.92"
+#string STR_FRONT_PAGE_BANNER_3_LEFT #language en-US "Serial Number: 1Z123456789MARMAR (Need SMBIOS entries)"
+ #language fr-FR "Numéro de série: 1Z123456789MARMAR (Les entrées de SMBIOS de besoin)"
+#string STR_CONTINUE_PROMPT #language en-US "Continue"
+ #language fr-FR "Continuer"
+#string STR_CONTINUE_HELP #language en-US "This selection will direct the system to continue to booting process"
+ #language fr-FR "Cette sélection dirigera le système pour continuer au charger de procédé"
+#string STR_LANGUAGE_SELECT #language en-US "Select Language"
+ #language fr-FR "Choisir la Langue"
+#string STR_LANGUAGE_SELECT_HELP #language en-US "This is the option one adjusts to change the language for the current system"
+ #language fr-FR "Ceci est l'option que celui ajuste changer la langue pour le système actuel"
+#string STR_BOOT_MANAGER #language en-US "Boot Manager"
+ #language fr-FR "Charger le Directeur"
+#string STR_BOOT_MANAGER_HELP #language en-US "This selection will take you to the Boot Manager"
+ #language fr-FR "Cette sélection vous prendra au Directeur de Botte"
+#string STR_BOOT_MAINT_MANAGER #language en-US "Boot Maintenance Manager"
+ #language fr-FR "Directeur d'Entretien"
+#string STR_BOOT_MAINT_MANAGER_HELP #language en-US "This selection will take you to the Boot Maintenance Manager"
+ #language fr-FR "Cette sélection vous prendra au Directeur d'Entretien"
+#string STR_DEVICE_MANAGER #language en-US "Device Manager"
+ #language fr-FR "Directeur d'appareil"
+#string STR_DEVICE_MANAGER_HELP #language en-US "This selection will take you to the Device Manager"
+ #language fr-FR "Cette sélection vous prendra au Directeur d'Appareil"
+#string STR_TIME_OUT_PROMPT #language en-US "Boot process will continue in %d seconds"
+ #language fr-FR "Le procédé de botte continuera dans %d secondes"
+#string STR_MISSING_STRING #language en-US "Missing String"
+ #language fr-FR "Missing String"
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageVfr.Vfr b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageVfr.Vfr
new file mode 100644
index 0000000000..a2d92dff51
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/FrontPageVfr.Vfr
@@ -0,0 +1,137 @@
+///** @file
+//
+// Browser formset.
+//
+// Copyright (c) 2007 - 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.
+//
+//**/
+
+#include <Guid/BdsHii.h>
+
+#define FRONT_PAGE_CLASS 0x0000
+#define FRONT_PAGE_SUBCLASS 0x0002
+
+#define FRONT_PAGE_FORM_ID 0x1000
+
+#define FRONT_PAGE_ITEM_ONE 0x0001
+#define FRONT_PAGE_ITEM_TWO 0x0002
+#define FRONT_PAGE_ITEM_THREE 0x0003
+#define FRONT_PAGE_ITEM_FOUR 0x0004
+#define FRONT_PAGE_ITEM_FIVE 0x0005
+
+#define FRONT_PAGE_KEY_CONTINUE 0x1000
+#define FRONT_PAGE_KEY_LANGUAGE 0x1234
+#define FRONT_PAGE_KEY_BOOT_MANAGER 0x1064
+#define FRONT_PAGE_KEY_DEVICE_MANAGER 0x8567
+#define FRONT_PAGE_KEY_BOOT_MAINTAIN 0x9876
+
+#define LABEL_SELECT_LANGUAGE 0x1000
+#define LABEL_TIMEOUT 0x2000
+#define LABEL_END 0xffff
+
+formset
+ guid = FRONT_PAGE_FORMSET_GUID,
+ title = STRING_TOKEN(STR_FRONT_PAGE_TITLE),
+ help = STRING_TOKEN(STR_NULL_STRING),
+ classguid = FRONT_PAGE_FORMSET_GUID,
+
+ form formid = FRONT_PAGE_FORM_ID,
+ title = STRING_TOKEN(STR_FRONT_PAGE_TITLE);
+
+ banner
+ title = STRING_TOKEN(STR_FRONT_PAGE_COMPUTER_MODEL),
+ line 1,
+ align left;
+
+ banner
+ title = STRING_TOKEN(STR_FRONT_PAGE_CPU_MODEL),
+ line 2,
+ align left;
+
+ banner
+ title = STRING_TOKEN(STR_FRONT_PAGE_CPU_SPEED),
+ line 2,
+ align right;
+
+ banner
+ title = STRING_TOKEN(STR_FRONT_PAGE_BIOS_VERSION),
+ line 3,
+ align left;
+
+ banner
+ title = STRING_TOKEN(STR_FRONT_PAGE_MEMORY_SIZE),
+ line 3,
+ align right;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_0_LEFT),
+// line 0,
+// align left;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_0_RIGHT),
+// line 0,
+// align right;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_1_LEFT),
+// line 1,
+// align left;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_1_RIGHT),
+// line 1,
+// align right;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_2_LEFT),
+// line 2,
+// align left;
+
+// banner
+// title = STRING_TOKEN(STR_FRONT_PAGE_BANNER_3_LEFT),
+// line 3,
+// align left;
+
+
+ text
+ help = STRING_TOKEN(STR_CONTINUE_HELP),
+ text = STRING_TOKEN(STR_CONTINUE_PROMPT),
+ flags = INTERACTIVE,
+ key = FRONT_PAGE_KEY_CONTINUE;
+
+ label LABEL_SELECT_LANGUAGE;
+ //
+ // This is where we will dynamically add a OneOf type op-code to select
+ // Languages from the currently available choices
+ //
+ label LABEL_END;
+
+ goto FRONT_PAGE_ITEM_THREE,
+ prompt = STRING_TOKEN(STR_BOOT_MANAGER),
+ help = STRING_TOKEN(STR_BOOT_MANAGER_HELP),
+ flags = INTERACTIVE,
+ key = FRONT_PAGE_KEY_BOOT_MANAGER;
+
+ goto FRONT_PAGE_ITEM_FOUR,
+ prompt = STRING_TOKEN(STR_DEVICE_MANAGER),
+ help = STRING_TOKEN(STR_DEVICE_MANAGER_HELP),
+ flags = INTERACTIVE,
+ key = FRONT_PAGE_KEY_DEVICE_MANAGER;
+
+ goto FRONT_PAGE_ITEM_FIVE,
+ prompt = STRING_TOKEN(STR_BOOT_MAINT_MANAGER),
+ help = STRING_TOKEN(STR_BOOT_MAINT_MANAGER_HELP),
+ flags = INTERACTIVE,
+ key = FRONT_PAGE_KEY_BOOT_MAINTAIN;
+
+ endform;
+
+endformset;
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.c
new file mode 100644
index 0000000000..e061991ea2
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.c
@@ -0,0 +1,597 @@
+/** @file
+ Provides a way for 3rd party applications to register themselves for launch by the
+ Boot Manager based on hot key
+
+Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "Hotkey.h"
+
+
+LIST_ENTRY mHotkeyList = INITIALIZE_LIST_HEAD_VARIABLE (mHotkeyList);
+BDS_COMMON_OPTION *mHotkeyBootOption = NULL;
+EFI_EVENT mHotkeyEvent;
+VOID *mHotkeyRegistration;
+
+
+/**
+ Check if the Key Option is valid or not.
+
+ @param KeyOption The Hot Key Option to be checked.
+
+ @retval TRUE The Hot Key Option is valid.
+ @retval FALSE The Hot Key Option is invalid.
+
+**/
+BOOLEAN
+IsKeyOptionValid (
+ IN EFI_KEY_OPTION *KeyOption
+)
+{
+ UINT16 BootOptionName[10];
+ UINT8 *BootOptionVar;
+ UINTN BootOptionSize;
+ UINT32 Crc;
+
+ //
+ // Check whether corresponding Boot Option exist
+ //
+ UnicodeSPrint (BootOptionName, sizeof (BootOptionName), L"Boot%04x", KeyOption->BootOption);
+ BootOptionVar = BdsLibGetVariableAndSize (
+ BootOptionName,
+ &gEfiGlobalVariableGuid,
+ &BootOptionSize
+ );
+
+ if (BootOptionVar == NULL || BootOptionSize == 0) {
+ return FALSE;
+ }
+
+ //
+ // Check CRC for Boot Option
+ //
+ gBS->CalculateCrc32 (BootOptionVar, BootOptionSize, &Crc);
+ FreePool (BootOptionVar);
+
+ return (BOOLEAN) ((KeyOption->BootOptionCrc == Crc) ? TRUE : FALSE);
+}
+
+/**
+ Try to boot the boot option triggered by hotkey.
+ @retval EFI_SUCCESS There is HotkeyBootOption & it is processed
+ @retval EFI_NOT_FOUND There is no HotkeyBootOption
+**/
+EFI_STATUS
+HotkeyBoot (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN ExitDataSize;
+ CHAR16 *ExitData;
+
+ if (mHotkeyBootOption == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ BdsLibConnectDevicePath (mHotkeyBootOption->DevicePath);
+
+ //
+ // Clear the screen before launch this BootOption
+ //
+ gST->ConOut->Reset (gST->ConOut, FALSE);
+
+ Status = BdsLibBootViaBootOption (mHotkeyBootOption, mHotkeyBootOption->DevicePath, &ExitDataSize, &ExitData);
+
+ if (EFI_ERROR (Status)) {
+ //
+ // Call platform action to indicate the boot fail
+ //
+ mHotkeyBootOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_FAILED));
+ PlatformBdsBootFail (mHotkeyBootOption, Status, ExitData, ExitDataSize);
+ } else {
+ //
+ // Call platform action to indicate the boot success
+ //
+ mHotkeyBootOption->StatusString = GetStringById (STRING_TOKEN (STR_BOOT_SUCCEEDED));
+ PlatformBdsBootSuccess (mHotkeyBootOption);
+ }
+ FreePool (mHotkeyBootOption->Description);
+ FreePool (mHotkeyBootOption->DevicePath);
+ FreePool (mHotkeyBootOption->LoadOptions);
+ FreePool (mHotkeyBootOption);
+
+ mHotkeyBootOption = NULL;
+
+ return EFI_SUCCESS;
+}
+
+/**
+
+ This is the common notification function for HotKeys, it will be registered
+ with SimpleTextInEx protocol interface - RegisterKeyNotify() of ConIn handle.
+
+ @param KeyData A pointer to a buffer that is filled in with the keystroke
+ information for the key that was pressed.
+
+ @retval EFI_SUCCESS KeyData is successfully processed.
+ @return EFI_NOT_FOUND Fail to find boot option variable.
+**/
+EFI_STATUS
+EFIAPI
+HotkeyCallback (
+ IN EFI_KEY_DATA *KeyData
+)
+{
+ BOOLEAN HotkeyCatched;
+ LIST_ENTRY BootLists;
+ LIST_ENTRY *Link;
+ BDS_HOTKEY_OPTION *Hotkey;
+ UINT16 Buffer[10];
+ EFI_STATUS Status;
+ EFI_KEY_DATA *HotkeyData;
+
+ if (mHotkeyBootOption != NULL) {
+ //
+ // Do not process sequential hotkey stroke until the current boot option returns
+ //
+ return EFI_SUCCESS;
+ }
+
+ Status = EFI_SUCCESS;
+
+ for ( Link = GetFirstNode (&mHotkeyList)
+ ; !IsNull (&mHotkeyList, Link)
+ ; Link = GetNextNode (&mHotkeyList, Link)
+ ) {
+ HotkeyCatched = FALSE;
+ Hotkey = BDS_HOTKEY_OPTION_FROM_LINK (Link);
+
+ //
+ // Is this Key Stroke we are waiting for?
+ //
+ ASSERT (Hotkey->WaitingKey < (sizeof (Hotkey->KeyData) / sizeof (Hotkey->KeyData[0])));
+ HotkeyData = &Hotkey->KeyData[Hotkey->WaitingKey];
+ if ((KeyData->Key.ScanCode == HotkeyData->Key.ScanCode) &&
+ (KeyData->Key.UnicodeChar == HotkeyData->Key.UnicodeChar) &&
+ (((KeyData->KeyState.KeyShiftState & EFI_SHIFT_STATE_VALID) != 0) ?
+ (KeyData->KeyState.KeyShiftState == HotkeyData->KeyState.KeyShiftState) : TRUE
+ )
+ ) {
+ //
+ // For hotkey of key combination, transit to next waiting state
+ //
+ Hotkey->WaitingKey++;
+
+ if (Hotkey->WaitingKey == Hotkey->CodeCount) {
+ //
+ // Received the whole key stroke sequence
+ //
+ HotkeyCatched = TRUE;
+ }
+ } else {
+ //
+ // Receive an unexpected key stroke, reset to initial waiting state
+ //
+ Hotkey->WaitingKey = 0;
+ }
+
+ if (HotkeyCatched) {
+ //
+ // Reset to initial waiting state
+ //
+ Hotkey->WaitingKey = 0;
+
+ //
+ // Launch its BootOption
+ //
+ InitializeListHead (&BootLists);
+
+ UnicodeSPrint (Buffer, sizeof (Buffer), L"Boot%04x", Hotkey->BootOptionNumber);
+ mHotkeyBootOption = BdsLibVariableToOption (&BootLists, Buffer);
+ }
+ }
+
+ return Status;
+}
+
+/**
+ Register the common HotKey notify function to given SimpleTextInEx protocol instance.
+
+ @param SimpleTextInEx Simple Text Input Ex protocol instance
+
+ @retval EFI_SUCCESS Register hotkey notification function successfully.
+ @retval EFI_OUT_OF_RESOURCES Unable to allocate necessary data structures.
+
+**/
+EFI_STATUS
+HotkeyRegisterNotify (
+ IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleTextInEx
+)
+{
+ UINTN Index;
+ EFI_STATUS Status;
+ LIST_ENTRY *Link;
+ BDS_HOTKEY_OPTION *Hotkey;
+
+ //
+ // Register notification function for each hotkey
+ //
+ Link = GetFirstNode (&mHotkeyList);
+
+ while (!IsNull (&mHotkeyList, Link)) {
+ Hotkey = BDS_HOTKEY_OPTION_FROM_LINK (Link);
+
+ Index = 0;
+ do {
+ Status = SimpleTextInEx->RegisterKeyNotify (
+ SimpleTextInEx,
+ &Hotkey->KeyData[Index],
+ HotkeyCallback,
+ &Hotkey->NotifyHandle
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // some of the hotkey registry failed
+ //
+ return Status;
+ }
+ Index ++;
+ } while ((Index < Hotkey->CodeCount) && (Index < (sizeof (Hotkey->KeyData) / sizeof (EFI_KEY_DATA))));
+
+ Link = GetNextNode (&mHotkeyList, Link);
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Callback function for SimpleTextInEx protocol install events
+
+ @param Event the event that is signaled.
+ @param Context not used here.
+
+**/
+VOID
+EFIAPI
+HotkeyEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ EFI_HANDLE Handle;
+ EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleTextInEx;
+
+ while (TRUE) {
+ BufferSize = sizeof (EFI_HANDLE);
+ Status = gBS->LocateHandle (
+ ByRegisterNotify,
+ NULL,
+ mHotkeyRegistration,
+ &BufferSize,
+ &Handle
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // If no more notification events exist
+ //
+ return ;
+ }
+
+ Status = gBS->HandleProtocol (
+ Handle,
+ &gEfiSimpleTextInputExProtocolGuid,
+ (VOID **) &SimpleTextInEx
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ HotkeyRegisterNotify (SimpleTextInEx);
+ }
+}
+
+/**
+ Insert Key Option to hotkey list.
+
+ @param KeyOption The Hot Key Option to be added to hotkey list.
+
+ @retval EFI_SUCCESS Add to hotkey list success.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resource.
+**/
+EFI_STATUS
+HotkeyInsertList (
+ IN EFI_KEY_OPTION *KeyOption
+)
+{
+ BDS_HOTKEY_OPTION *HotkeyLeft;
+ BDS_HOTKEY_OPTION *HotkeyRight;
+ UINTN Index;
+ EFI_BOOT_KEY_DATA KeyOptions;
+ UINT32 KeyShiftStateLeft;
+ UINT32 KeyShiftStateRight;
+ EFI_INPUT_KEY *InputKey;
+ EFI_KEY_DATA *KeyData;
+
+ HotkeyLeft = AllocateZeroPool (sizeof (BDS_HOTKEY_OPTION));
+ if (HotkeyLeft == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ HotkeyLeft->Signature = BDS_HOTKEY_OPTION_SIGNATURE;
+ HotkeyLeft->BootOptionNumber = KeyOption->BootOption;
+
+ KeyOptions = KeyOption->KeyData;
+
+ HotkeyLeft->CodeCount = (UINT8) KeyOptions.Options.InputKeyCount;
+
+ //
+ // Map key shift state from KeyOptions to EFI_KEY_DATA.KeyState
+ //
+ KeyShiftStateRight = EFI_SHIFT_STATE_VALID;
+ if (KeyOptions.Options.ShiftPressed) {
+ KeyShiftStateRight |= EFI_RIGHT_SHIFT_PRESSED;
+ }
+ if (KeyOptions.Options.ControlPressed) {
+ KeyShiftStateRight |= EFI_RIGHT_CONTROL_PRESSED;
+ }
+ if (KeyOptions.Options.AltPressed) {
+ KeyShiftStateRight |= EFI_RIGHT_ALT_PRESSED;
+ }
+ if (KeyOptions.Options.LogoPressed) {
+ KeyShiftStateRight |= EFI_RIGHT_LOGO_PRESSED;
+ }
+ if (KeyOptions.Options.MenuPressed) {
+ KeyShiftStateRight |= EFI_MENU_KEY_PRESSED;
+ }
+ if (KeyOptions.Options.SysReqPressed) {
+ KeyShiftStateRight |= EFI_SYS_REQ_PRESSED;
+ }
+
+ KeyShiftStateLeft = (KeyShiftStateRight & 0xffffff00) | ((KeyShiftStateRight & 0xff) << 1);
+
+ InputKey = (EFI_INPUT_KEY *) (((UINT8 *) KeyOption) + sizeof (EFI_KEY_OPTION));
+
+ Index = 0;
+ KeyData = &HotkeyLeft->KeyData[0];
+ do {
+ //
+ // If Key CodeCount is 0, then only KeyData[0] is used;
+ // if Key CodeCount is n, then KeyData[0]~KeyData[n-1] are used
+ //
+ KeyData->Key.ScanCode = InputKey[Index].ScanCode;
+ KeyData->Key.UnicodeChar = InputKey[Index].UnicodeChar;
+ KeyData->KeyState.KeyShiftState = KeyShiftStateLeft;
+
+ Index++;
+ KeyData++;
+ } while (Index < HotkeyLeft->CodeCount);
+ InsertTailList (&mHotkeyList, &HotkeyLeft->Link);
+
+ if (KeyShiftStateLeft != KeyShiftStateRight) {
+ //
+ // Need an extra hotkey for shift key on right
+ //
+ HotkeyRight = AllocateCopyPool (sizeof (BDS_HOTKEY_OPTION), HotkeyLeft);
+ if (HotkeyRight == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Index = 0;
+ KeyData = &HotkeyRight->KeyData[0];
+ do {
+ //
+ // Key.ScanCode and Key.UnicodeChar have already been initialized,
+ // only need to update KeyState.KeyShiftState
+ //
+ KeyData->KeyState.KeyShiftState = KeyShiftStateRight;
+
+ Index++;
+ KeyData++;
+ } while (Index < HotkeyRight->CodeCount);
+ InsertTailList (&mHotkeyList, &HotkeyRight->Link);
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Return TRUE when the variable pointed by Name and Guid is a Key#### variable.
+
+ @param Name The name of the variable.
+ @param Guid The GUID of the variable.
+ @param OptionNumber Return the option number parsed from the Name.
+
+ @retval TRUE The variable pointed by Name and Guid is a Key#### variable.
+ @retval FALSE The variable pointed by Name and Guid isn't a Key#### variable.
+**/
+BOOLEAN
+IsKeyOptionVariable (
+ CHAR16 *Name,
+ EFI_GUID *Guid,
+ UINT16 *OptionNumber
+ )
+{
+ UINTN Index;
+
+ if (!CompareGuid (Guid, &gEfiGlobalVariableGuid) ||
+ (StrSize (Name) != sizeof (L"Key####")) ||
+ (StrnCmp (Name, L"Key", 3) != 0)
+ ) {
+ return FALSE;
+ }
+
+ *OptionNumber = 0;
+ for (Index = 3; Index < 7; Index++) {
+ if ((Name[Index] >= L'0') && (Name[Index] <= L'9')) {
+ *OptionNumber = *OptionNumber * 16 + Name[Index] - L'0';
+ } else if ((Name[Index] >= L'A') && (Name[Index] <= L'F')) {
+ *OptionNumber = *OptionNumber * 16 + Name[Index] - L'A' + 10;
+ } else {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+/**
+ Return an array of key option numbers.
+
+ @param Count Return the count of key option numbers.
+
+ @return UINT16* Pointer to an array of key option numbers;
+**/
+UINT16 *
+EFIAPI
+HotkeyGetOptionNumbers (
+ OUT UINTN *Count
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ CHAR16 *Name;
+ EFI_GUID Guid;
+ UINTN NameSize;
+ UINTN NewNameSize;
+ UINT16 *OptionNumbers;
+ UINT16 OptionNumber;
+
+ if (Count == NULL) {
+ return NULL;
+ }
+
+ *Count = 0;
+ OptionNumbers = NULL;
+
+ NameSize = sizeof (CHAR16);
+ Name = AllocateZeroPool (NameSize);
+ ASSERT (Name != NULL);
+ while (TRUE) {
+ NewNameSize = NameSize;
+ Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ Name = ReallocatePool (NameSize, NewNameSize, Name);
+ ASSERT (Name != NULL);
+ Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid);
+ NameSize = NewNameSize;
+ }
+
+ if (Status == EFI_NOT_FOUND) {
+ break;
+ }
+ ASSERT_EFI_ERROR (Status);
+
+ if (IsKeyOptionVariable (Name ,&Guid, &OptionNumber)) {
+ OptionNumbers = ReallocatePool (
+ *Count * sizeof (UINT16),
+ (*Count + 1) * sizeof (UINT16),
+ OptionNumbers
+ );
+ ASSERT (OptionNumbers != NULL);
+ for (Index = 0; Index < *Count; Index++) {
+ if (OptionNumber < OptionNumbers[Index]) {
+ break;
+ }
+ }
+ CopyMem (&OptionNumbers[Index + 1], &OptionNumbers[Index], (*Count - Index) * sizeof (UINT16));
+ OptionNumbers[Index] = OptionNumber;
+ (*Count)++;
+ }
+ }
+
+ FreePool (Name);
+
+ return OptionNumbers;
+}
+
+/**
+
+ Process all the "Key####" variables, associate Hotkeys with corresponding Boot Options.
+
+ @retval EFI_SUCCESS Hotkey services successfully initialized.
+**/
+EFI_STATUS
+InitializeHotkeyService (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT32 BootOptionSupport;
+ UINT16 *KeyOptionNumbers;
+ UINTN KeyOptionCount;
+ UINTN Index;
+ CHAR16 KeyOptionName[8];
+ EFI_KEY_OPTION *KeyOption;
+
+ //
+ // Export our capability - EFI_BOOT_OPTION_SUPPORT_KEY and EFI_BOOT_OPTION_SUPPORT_APP.
+ // with maximum number of key presses of 3
+ // Do not report the hotkey capability if PcdConInConnectOnDemand is enabled.
+ //
+ BootOptionSupport = EFI_BOOT_OPTION_SUPPORT_APP;
+ if (!PcdGetBool (PcdConInConnectOnDemand)) {
+ BootOptionSupport |= EFI_BOOT_OPTION_SUPPORT_KEY;
+ SET_BOOT_OPTION_SUPPORT_KEY_COUNT (BootOptionSupport, 3);
+ }
+
+ Status = gRT->SetVariable (
+ L"BootOptionSupport",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ sizeof (UINT32),
+ &BootOptionSupport
+ );
+ //
+ // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+
+ KeyOptionNumbers = HotkeyGetOptionNumbers (&KeyOptionCount);
+ for (Index = 0; Index < KeyOptionCount; Index ++) {
+ UnicodeSPrint (KeyOptionName, sizeof (KeyOptionName), L"Key%04x", KeyOptionNumbers[Index]);
+ GetEfiGlobalVariable2 (KeyOptionName, (VOID **) &KeyOption, NULL);
+ ASSERT (KeyOption != NULL);
+ if (IsKeyOptionValid (KeyOption)) {
+ HotkeyInsertList (KeyOption);
+ }
+ FreePool (KeyOption);
+ }
+
+ if (KeyOptionNumbers != NULL) {
+ FreePool (KeyOptionNumbers);
+ }
+
+ //
+ // Register Protocol notify for Hotkey service
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ HotkeyEvent,
+ NULL,
+ &mHotkeyEvent
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Register for protocol notifications on this event
+ //
+ Status = gBS->RegisterProtocolNotify (
+ &gEfiSimpleTextInputExProtocolGuid,
+ mHotkeyEvent,
+ &mHotkeyRegistration
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.h
new file mode 100644
index 0000000000..4ee5563a22
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Hotkey.h
@@ -0,0 +1,67 @@
+/** @file
+ Provides a way for 3rd party applications to register themselves for launch by the
+ Boot Manager based on hot key
+
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+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 _HOTKEY_H_
+#define _HOTKEY_H_
+
+#include "Bds.h"
+#include "String.h"
+
+#define SET_BOOT_OPTION_SUPPORT_KEY_COUNT(a, c) { \
+ (a) = ((a) & ~EFI_BOOT_OPTION_SUPPORT_COUNT) | (((c) << LowBitSet32 (EFI_BOOT_OPTION_SUPPORT_COUNT)) & EFI_BOOT_OPTION_SUPPORT_COUNT); \
+ }
+
+#define BDS_HOTKEY_OPTION_SIGNATURE SIGNATURE_32 ('B', 'd', 'K', 'O')
+
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Link;
+
+ VOID *NotifyHandle;
+ UINT16 BootOptionNumber;
+ UINT8 CodeCount;
+ UINT8 WaitingKey;
+ EFI_KEY_DATA KeyData[3];
+} BDS_HOTKEY_OPTION;
+
+#define BDS_HOTKEY_OPTION_FROM_LINK(a) CR (a, BDS_HOTKEY_OPTION, Link, BDS_HOTKEY_OPTION_SIGNATURE)
+
+/**
+
+ Process all the "Key####" variables, associate Hotkeys with corresponding Boot Options.
+
+
+ @param VOID
+
+ @retval EFI_SUCCESS Hotkey services successfully initialized.
+
+**/
+EFI_STATUS
+InitializeHotkeyService (
+ VOID
+ );
+
+/**
+ Try to boot the boot option triggered by hotkey.
+ @retval EFI_SUCCESS There is HotkeyBootOption & it is processed
+ @retval EFI_NOT_FOUND There is no HotkeyBootOption
+**/
+EFI_STATUS
+HotkeyBoot (
+ VOID
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.c
new file mode 100644
index 0000000000..ddb2f93980
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.c
@@ -0,0 +1,48 @@
+/** @file
+ Set the level of support for Hardware Error Record Persistence that is
+ implemented by the platform.
+
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "HwErrRecSupport.h"
+
+/**
+ Set the HwErrRecSupport variable contains a binary UINT16 that supplies the
+ level of support for Hardware Error Record Persistence that is implemented
+ by the platform.
+
+**/
+VOID
+InitializeHwErrRecSupport (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT16 HardwareErrorRecordLevel;
+
+ HardwareErrorRecordLevel = PcdGet16 (PcdHardwareErrorRecordLevel);
+
+ if (HardwareErrorRecordLevel != 0) {
+ //
+ // If level value equal 0, no need set to 0 to variable area because UEFI specification
+ // define same behavior between no value or 0 value for L"HwErrRecSupport".
+ //
+ Status = gRT->SetVariable (
+ L"HwErrRecSupport",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
+ sizeof (UINT16),
+ &HardwareErrorRecordLevel
+ );
+ ASSERT_EFI_ERROR(Status);
+ }
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.h
new file mode 100644
index 0000000000..0cf597acc7
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/HwErrRecSupport.h
@@ -0,0 +1,32 @@
+/** @file
+ Set the level of support for Hardware Error Record Persistence that is
+ implemented by the platform.
+
+Copyright (c) 2007 - 2008, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef _HW_ERR_REC_SUPPORT_H_
+#define _HW_ERR_REC_SUPPORT_H_
+
+#include "Bds.h"
+
+/**
+ Set the HwErrRecSupport variable contains a binary UINT16 that supplies the
+ level of support for Hardware Error Record Persistence that is implemented
+ by the platform.
+
+**/
+VOID
+InitializeHwErrRecSupport (
+ VOID
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.c
new file mode 100644
index 0000000000..39455e44da
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.c
@@ -0,0 +1,499 @@
+/** @file
+ Language settings
+
+Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "Language.h"
+#include "FrontPage.h"
+
+EFI_GUID mFontPackageGuid = {
+ 0x78941450, 0x90ab, 0x4fb1, {0xb7, 0x5f, 0x58, 0x92, 0x14, 0xe2, 0x4a, 0xc}
+};
+
+#define NARROW_GLYPH_NUMBER 8
+#define WIDE_GLYPH_NUMBER 75
+
+typedef struct {
+ ///
+ /// This 4-bytes total array length is required by HiiAddPackages()
+ ///
+ UINT32 Length;
+
+ //
+ // This is the Font package definition
+ //
+ EFI_HII_PACKAGE_HEADER Header;
+ UINT16 NumberOfNarrowGlyphs;
+ UINT16 NumberOfWideGlyphs;
+ EFI_NARROW_GLYPH NarrowArray[NARROW_GLYPH_NUMBER];
+ EFI_WIDE_GLYPH WideArray[WIDE_GLYPH_NUMBER];
+} FONT_PACK_BIN;
+
+FONT_PACK_BIN mFontBin = {
+ sizeof (FONT_PACK_BIN),
+ {
+ sizeof (FONT_PACK_BIN) - sizeof (UINT32),
+ EFI_HII_PACKAGE_SIMPLE_FONTS,
+ },
+ NARROW_GLYPH_NUMBER,
+ 0,
+ { // Narrow Glyphs
+ {
+ 0x05d0,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x4E,
+ 0x6E,
+ 0x62,
+ 0x32,
+ 0x32,
+ 0x3C,
+ 0x68,
+ 0x4C,
+ 0x4C,
+ 0x46,
+ 0x76,
+ 0x72,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d1,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x78,
+ 0x7C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x7E,
+ 0x7E,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d2,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x78,
+ 0x7C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x1C,
+ 0x3E,
+ 0x66,
+ 0x66,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d3,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x7E,
+ 0x7E,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d4,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x7C,
+ 0x7E,
+ 0x06,
+ 0x06,
+ 0x06,
+ 0x06,
+ 0x66,
+ 0x66,
+ 0x66,
+ 0x66,
+ 0x66,
+ 0x66,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d5,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x3C,
+ 0x3C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x0C,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x05d6,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x38,
+ 0x38,
+ 0x1E,
+ 0x1E,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x18,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ },
+ {
+ 0x0000,
+ 0x00,
+ {
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00
+ }
+ }
+ }
+};
+
+/**
+ Routine to export glyphs to the HII database. This is in addition to whatever is defined in the Graphics Console driver.
+
+**/
+VOID
+ExportFonts (
+ VOID
+ )
+{
+ EFI_HII_HANDLE HiiHandle;
+
+ HiiHandle = HiiAddPackages (
+ &mFontPackageGuid,
+ gImageHandle,
+ &mFontBin,
+ NULL
+ );
+ ASSERT (HiiHandle != NULL);
+}
+
+/**
+ Get next language from language code list (with separator ';').
+
+ If LangCode is NULL, then ASSERT.
+ If Lang is NULL, then ASSERT.
+
+ @param LangCode On input: point to first language in the list. On
+ output: point to next language in the list, or
+ NULL if no more language in the list.
+ @param Lang The first language in the list.
+
+**/
+VOID
+EFIAPI
+GetNextLanguage (
+ IN OUT CHAR8 **LangCode,
+ OUT CHAR8 *Lang
+ )
+{
+ UINTN Index;
+ CHAR8 *StringPtr;
+
+ ASSERT (LangCode != NULL);
+ ASSERT (*LangCode != NULL);
+ ASSERT (Lang != NULL);
+
+ Index = 0;
+ StringPtr = *LangCode;
+ while (StringPtr[Index] != 0 && StringPtr[Index] != ';') {
+ Index++;
+ }
+
+ CopyMem (Lang, StringPtr, Index);
+ Lang[Index] = 0;
+
+ if (StringPtr[Index] == ';') {
+ Index++;
+ }
+ *LangCode = StringPtr + Index;
+}
+
+/**
+ Check if lang is in supported language codes according to language string.
+
+ This code is used to check if lang is in in supported language codes. It can handle
+ RFC4646 and ISO639 language tags.
+ In ISO639 language tags, take 3-characters as a delimitation to find matched string.
+ In RFC4646 language tags, take semicolon as a delimitation to find matched string.
+
+ For example:
+ SupportedLang = "engfraengfra"
+ Iso639Language = TRUE
+ Lang = "eng", the return value is "TRUE", or
+ Lang = "chs", the return value is "FALSE".
+ Another example:
+ SupportedLang = "en;fr;en-US;fr-FR"
+ Iso639Language = FALSE
+ Lang = "en", the return value is "TRUE", or
+ Lang = "zh", the return value is "FALSE".
+
+ @param SupportedLang Platform supported language codes.
+ @param Lang Configured language.
+ @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646.
+
+ @retval TRUE lang is in supported language codes.
+ @retval FALSE lang is not in supported language codes.
+
+**/
+BOOLEAN
+IsLangInSupportedLangCodes(
+ IN CHAR8 *SupportedLang,
+ IN CHAR8 *Lang,
+ IN BOOLEAN Iso639Language
+ )
+{
+ UINTN Index;
+ UINTN CompareLength;
+ UINTN LanguageLength;
+
+ if (Iso639Language) {
+ CompareLength = ISO_639_2_ENTRY_SIZE;
+ for (Index = 0; Index < AsciiStrLen (SupportedLang); Index += CompareLength) {
+ if (AsciiStrnCmp (Lang, SupportedLang + Index, CompareLength) == 0) {
+ //
+ // Successfully find the Lang string in SupportedLang string.
+ //
+ return TRUE;
+ }
+ }
+ return FALSE;
+ } else {
+ //
+ // Compare RFC4646 language code
+ //
+ for (LanguageLength = 0; Lang[LanguageLength] != '\0'; LanguageLength++);
+
+ for (; *SupportedLang != '\0'; SupportedLang += CompareLength) {
+ //
+ // Skip ';' characters in SupportedLang
+ //
+ for (; *SupportedLang != '\0' && *SupportedLang == ';'; SupportedLang++);
+ //
+ // Determine the length of the next language code in SupportedLang
+ //
+ for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);
+
+ if ((CompareLength == LanguageLength) &&
+ (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {
+ //
+ // Successfully find the Lang string in SupportedLang string.
+ //
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+}
+
+/**
+ Initialize Lang or PlatformLang variable, if Lang or PlatformLang variable is not found,
+ or it has been set to an unsupported value(not one of platform supported language codes),
+ set the default language code to it.
+
+ @param LangName Language name, L"Lang" or L"PlatformLang".
+ @param SupportedLang Platform supported language codes.
+ @param DefaultLang Default language code.
+ @param Iso639Language A bool value to signify if the handler is operated on ISO639 or RFC4646,
+ TRUE for L"Lang" LangName or FALSE for L"PlatformLang" LangName.
+
+**/
+VOID
+InitializeLangVariable (
+ IN CHAR16 *LangName,
+ IN CHAR8 *SupportedLang,
+ IN CHAR8 *DefaultLang,
+ IN BOOLEAN Iso639Language
+ )
+{
+ CHAR8 *Lang;
+
+ //
+ // Find current Lang or PlatformLang from EFI Variable.
+ //
+ GetEfiGlobalVariable2 (LangName, (VOID **) &Lang, NULL);
+ //
+ // If Lang or PlatformLang variable is not found,
+ // or it has been set to an unsupported value(not one of the supported language codes),
+ // set the default language code to it.
+ //
+ if ((Lang == NULL) || !IsLangInSupportedLangCodes (SupportedLang, Lang, Iso639Language)) {
+ //
+ // The default language code should be one of the supported language codes.
+ //
+ ASSERT (IsLangInSupportedLangCodes (SupportedLang, DefaultLang, Iso639Language));
+ BdsDxeSetVariableAndReportStatusCodeOnError (
+ LangName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ AsciiStrSize (DefaultLang),
+ DefaultLang
+ );
+ }
+
+ if (Lang != NULL) {
+ FreePool (Lang);
+ }
+}
+
+/**
+ Determine the current language that will be used
+ based on language related EFI Variables.
+
+ @param LangCodesSettingRequired - If required to set LangCodes variable
+
+**/
+VOID
+InitializeLanguage (
+ BOOLEAN LangCodesSettingRequired
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *LangCodes;
+ CHAR8 *PlatformLangCodes;
+
+ ExportFonts ();
+
+ LangCodes = (CHAR8 *)PcdGetPtr (PcdUefiVariableDefaultLangCodes);
+ PlatformLangCodes = (CHAR8 *)PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes);
+ if (LangCodesSettingRequired) {
+ if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
+ //
+ // UEFI 2.0 depricated this variable so we support turning it off
+ //
+ Status = gRT->SetVariable (
+ L"LangCodes",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ AsciiStrSize (LangCodes),
+ LangCodes
+ );
+ //
+ // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ Status = gRT->SetVariable (
+ L"PlatformLangCodes",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ AsciiStrSize (PlatformLangCodes),
+ PlatformLangCodes
+ );
+ //
+ // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
+ //
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ if (!FeaturePcdGet (PcdUefiVariableDefaultLangDeprecate)) {
+ //
+ // UEFI 2.0 depricated this variable so we support turning it off
+ //
+ InitializeLangVariable (L"Lang", LangCodes, (CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultLang), TRUE);
+ }
+ InitializeLangVariable (L"PlatformLang", PlatformLangCodes, (CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLang), FALSE);
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.h
new file mode 100644
index 0000000000..31c65f1824
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Language.h
@@ -0,0 +1,51 @@
+/** @file
+ Language setting
+
+Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef _LANGUAGE_H_
+#define _LANGUAGE_H_
+
+#include "String.h"
+
+/**
+ Get next language from language code list (with separator ';').
+
+ If LangCode is NULL, then ASSERT.
+ If Lang is NULL, then ASSERT.
+
+ @param LangCode On input: point to first language in the list. On
+ output: point to next language in the list, or
+ NULL if no more language in the list.
+ @param Lang The first language in the list.
+
+**/
+VOID
+EFIAPI
+GetNextLanguage (
+ IN OUT CHAR8 **LangCode,
+ OUT CHAR8 *Lang
+ );
+
+/**
+ Determine the current language that will be used
+ based on language related EFI Variables.
+
+ @param LangCodesSettingRequired If required to set LangCode variable
+
+**/
+VOID
+InitializeLanguage (
+ BOOLEAN LangCodesSettingRequired
+ );
+
+#endif // _LANGUAGE_H_
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/MemoryTest.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/MemoryTest.c
new file mode 100644
index 0000000000..118808201d
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/MemoryTest.c
@@ -0,0 +1,436 @@
+/** @file
+ Perform the platform memory test
+
+Copyright (c) 2004 - 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.
+
+**/
+
+#include "Bds.h"
+#include "String.h"
+
+//
+// BDS Platform Functions
+//
+/**
+
+ Show progress bar with title above it. It only works in Graphics mode.
+
+
+ @param TitleForeground Foreground color for Title.
+ @param TitleBackground Background color for Title.
+ @param Title Title above progress bar.
+ @param ProgressColor Progress bar color.
+ @param Progress Progress (0-100)
+ @param PreviousValue The previous value of the progress.
+
+ @retval EFI_STATUS Success update the progress bar
+
+**/
+EFI_STATUS
+PlatformBdsShowProgress (
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground,
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground,
+ IN CHAR16 *Title,
+ IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor,
+ IN UINTN Progress,
+ IN UINTN PreviousValue
+ )
+{
+ EFI_STATUS Status;
+ EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;
+ EFI_UGA_DRAW_PROTOCOL *UgaDraw;
+ UINT32 SizeOfX;
+ UINT32 SizeOfY;
+ UINT32 ColorDepth;
+ UINT32 RefreshRate;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Color;
+ UINTN BlockHeight;
+ UINTN BlockWidth;
+ UINTN BlockNum;
+ UINTN PosX;
+ UINTN PosY;
+ UINTN Index;
+
+ if (Progress > 100) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ UgaDraw = NULL;
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiGraphicsOutputProtocolGuid,
+ (VOID **) &GraphicsOutput
+ );
+ if (EFI_ERROR (Status) && FeaturePcdGet (PcdUgaConsumeSupport)) {
+ GraphicsOutput = NULL;
+
+ Status = gBS->HandleProtocol (
+ gST->ConsoleOutHandle,
+ &gEfiUgaDrawProtocolGuid,
+ (VOID **) &UgaDraw
+ );
+ }
+ if (EFI_ERROR (Status)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ SizeOfX = 0;
+ SizeOfY = 0;
+ if (GraphicsOutput != NULL) {
+ SizeOfX = GraphicsOutput->Mode->Info->HorizontalResolution;
+ SizeOfY = GraphicsOutput->Mode->Info->VerticalResolution;
+ } else if (UgaDraw != NULL) {
+ Status = UgaDraw->GetMode (
+ UgaDraw,
+ &SizeOfX,
+ &SizeOfY,
+ &ColorDepth,
+ &RefreshRate
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_UNSUPPORTED;
+ }
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+
+ BlockWidth = SizeOfX / 100;
+ BlockHeight = SizeOfY / 50;
+
+ BlockNum = Progress;
+
+ PosX = 0;
+ PosY = SizeOfY * 48 / 50;
+
+ if (BlockNum == 0) {
+ //
+ // Clear progress area
+ //
+ SetMem (&Color, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
+
+ if (GraphicsOutput != NULL) {
+ Status = GraphicsOutput->Blt (
+ GraphicsOutput,
+ &Color,
+ EfiBltVideoFill,
+ 0,
+ 0,
+ 0,
+ PosY - EFI_GLYPH_HEIGHT - 1,
+ SizeOfX,
+ SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1),
+ SizeOfX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)
+ );
+ } else if (FeaturePcdGet (PcdUgaConsumeSupport)) {
+ Status = UgaDraw->Blt (
+ UgaDraw,
+ (EFI_UGA_PIXEL *) &Color,
+ EfiUgaVideoFill,
+ 0,
+ 0,
+ 0,
+ PosY - EFI_GLYPH_HEIGHT - 1,
+ SizeOfX,
+ SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1),
+ SizeOfX * sizeof (EFI_UGA_PIXEL)
+ );
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+ }
+ //
+ // Show progress by drawing blocks
+ //
+ for (Index = PreviousValue; Index < BlockNum; Index++) {
+ PosX = Index * BlockWidth;
+ if (GraphicsOutput != NULL) {
+ Status = GraphicsOutput->Blt (
+ GraphicsOutput,
+ &ProgressColor,
+ EfiBltVideoFill,
+ 0,
+ 0,
+ PosX,
+ PosY,
+ BlockWidth - 1,
+ BlockHeight,
+ (BlockWidth) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)
+ );
+ } else if (FeaturePcdGet (PcdUgaConsumeSupport)) {
+ Status = UgaDraw->Blt (
+ UgaDraw,
+ (EFI_UGA_PIXEL *) &ProgressColor,
+ EfiUgaVideoFill,
+ 0,
+ 0,
+ PosX,
+ PosY,
+ BlockWidth - 1,
+ BlockHeight,
+ (BlockWidth) * sizeof (EFI_UGA_PIXEL)
+ );
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+ }
+
+ PrintXY (
+ (SizeOfX - StrLen (Title) * EFI_GLYPH_WIDTH) / 2,
+ PosY - EFI_GLYPH_HEIGHT - 1,
+ &TitleForeground,
+ &TitleBackground,
+ Title
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Perform the memory test base on the memory test intensive level,
+ and update the memory resource.
+
+ @param Level The memory test intensive level.
+
+ @retval EFI_STATUS Success test all the system memory and update
+ the memory resource
+
+**/
+EFI_STATUS
+EFIAPI
+BdsMemoryTest (
+ IN EXTENDMEM_COVERAGE_LEVEL Level
+ )
+{
+ EFI_STATUS Status;
+ EFI_STATUS KeyStatus;
+ EFI_STATUS InitStatus;
+ EFI_STATUS ReturnStatus;
+ BOOLEAN RequireSoftECCInit;
+ EFI_GENERIC_MEMORY_TEST_PROTOCOL *GenMemoryTest;
+ UINT64 TestedMemorySize;
+ UINT64 TotalMemorySize;
+ UINTN TestPercent;
+ UINT64 PreviousValue;
+ BOOLEAN ErrorOut;
+ BOOLEAN TestAbort;
+ EFI_INPUT_KEY Key;
+ CHAR16 StrPercent[80];
+ CHAR16 *StrTotalMemory;
+ CHAR16 *Pos;
+ CHAR16 *TmpStr;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Foreground;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Background;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL Color;
+ BOOLEAN IsFirstBoot;
+ UINT32 TempData;
+ UINTN StrTotalMemorySize;
+
+ ReturnStatus = EFI_SUCCESS;
+ ZeroMem (&Key, sizeof (EFI_INPUT_KEY));
+
+ StrTotalMemorySize = 128;
+ Pos = AllocateZeroPool (StrTotalMemorySize);
+
+ if (Pos == NULL) {
+ return ReturnStatus;
+ }
+
+ StrTotalMemory = Pos;
+
+ TestedMemorySize = 0;
+ TotalMemorySize = 0;
+ PreviousValue = 0;
+ ErrorOut = FALSE;
+ TestAbort = FALSE;
+
+ SetMem (&Foreground, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);
+ SetMem (&Background, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
+ SetMem (&Color, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);
+
+ RequireSoftECCInit = FALSE;
+
+ Status = gBS->LocateProtocol (
+ &gEfiGenericMemTestProtocolGuid,
+ NULL,
+ (VOID **) &GenMemoryTest
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Pos);
+ return EFI_SUCCESS;
+ }
+
+ InitStatus = GenMemoryTest->MemoryTestInit (
+ GenMemoryTest,
+ Level,
+ &RequireSoftECCInit
+ );
+ if (InitStatus == EFI_NO_MEDIA) {
+ //
+ // The PEI codes also have the relevant memory test code to check the memory,
+ // it can select to test some range of the memory or all of them. If PEI code
+ // checks all the memory, this BDS memory test will has no not-test memory to
+ // do the test, and then the status of EFI_NO_MEDIA will be returned by
+ // "MemoryTestInit". So it does not need to test memory again, just return.
+ //
+ FreePool (Pos);
+ return EFI_SUCCESS;
+ }
+
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ TmpStr = GetStringById (STRING_TOKEN (STR_ESC_TO_SKIP_MEM_TEST));
+
+ if (TmpStr != NULL) {
+ PrintXY (10, 10, NULL, NULL, TmpStr);
+ FreePool (TmpStr);
+ }
+ } else {
+ DEBUG ((EFI_D_INFO, "Enter memory test.\n"));
+ }
+ do {
+ Status = GenMemoryTest->PerformMemoryTest (
+ GenMemoryTest,
+ &TestedMemorySize,
+ &TotalMemorySize,
+ &ErrorOut,
+ TestAbort
+ );
+ if (ErrorOut && (Status == EFI_DEVICE_ERROR)) {
+ TmpStr = GetStringById (STRING_TOKEN (STR_SYSTEM_MEM_ERROR));
+ if (TmpStr != NULL) {
+ PrintXY (10, 10, NULL, NULL, TmpStr);
+ FreePool (TmpStr);
+ }
+
+ ASSERT (0);
+ }
+
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ TempData = (UINT32) DivU64x32 (TotalMemorySize, 16);
+ TestPercent = (UINTN) DivU64x32 (
+ DivU64x32 (MultU64x32 (TestedMemorySize, 100), 16),
+ TempData
+ );
+ if (TestPercent != PreviousValue) {
+ UnicodeValueToStringS (StrPercent, sizeof (StrPercent), 0, TestPercent, 0);
+ TmpStr = GetStringById (STRING_TOKEN (STR_MEMORY_TEST_PERCENT));
+ if (TmpStr != NULL) {
+ //
+ // TmpStr size is 64, StrPercent is reserved to 16.
+ //
+ StrnCatS (
+ StrPercent,
+ sizeof (StrPercent) / sizeof (CHAR16),
+ TmpStr,
+ sizeof (StrPercent) / sizeof (CHAR16) - StrLen (StrPercent) - 1
+ );
+ PrintXY (10, 10, NULL, NULL, StrPercent);
+ FreePool (TmpStr);
+ }
+
+ TmpStr = GetStringById (STRING_TOKEN (STR_PERFORM_MEM_TEST));
+ if (TmpStr != NULL) {
+ PlatformBdsShowProgress (
+ Foreground,
+ Background,
+ TmpStr,
+ Color,
+ TestPercent,
+ (UINTN) PreviousValue
+ );
+ FreePool (TmpStr);
+ }
+ }
+
+ PreviousValue = TestPercent;
+ } else {
+ DEBUG ((EFI_D_INFO, "Perform memory test (ESC to skip).\n"));
+ }
+
+ if (!PcdGetBool (PcdConInConnectOnDemand)) {
+ KeyStatus = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
+ if (!EFI_ERROR (KeyStatus) && (Key.ScanCode == SCAN_ESC)) {
+ if (!RequireSoftECCInit) {
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ TmpStr = GetStringById (STRING_TOKEN (STR_PERFORM_MEM_TEST));
+ if (TmpStr != NULL) {
+ PlatformBdsShowProgress (
+ Foreground,
+ Background,
+ TmpStr,
+ Color,
+ 100,
+ (UINTN) PreviousValue
+ );
+ FreePool (TmpStr);
+ }
+
+ PrintXY (10, 10, NULL, NULL, L"100");
+ }
+ Status = GenMemoryTest->Finished (GenMemoryTest);
+ goto Done;
+ }
+
+ TestAbort = TRUE;
+ }
+ }
+ } while (Status != EFI_NOT_FOUND);
+
+ Status = GenMemoryTest->Finished (GenMemoryTest);
+
+Done:
+ if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
+ UnicodeValueToStringS (StrTotalMemory, StrTotalMemorySize, COMMA_TYPE, TotalMemorySize, 0);
+ if (StrTotalMemory[0] == L',') {
+ StrTotalMemory++;
+ StrTotalMemorySize -= sizeof (CHAR16);
+ }
+
+ TmpStr = GetStringById (STRING_TOKEN (STR_MEM_TEST_COMPLETED));
+ if (TmpStr != NULL) {
+ StrnCatS (
+ StrTotalMemory,
+ StrTotalMemorySize / sizeof (CHAR16),
+ TmpStr,
+ StrTotalMemorySize / sizeof (CHAR16) - StrLen (StrTotalMemory) - 1
+ );
+ FreePool (TmpStr);
+ }
+
+ PrintXY (10, 10, NULL, NULL, StrTotalMemory);
+ PlatformBdsShowProgress (
+ Foreground,
+ Background,
+ StrTotalMemory,
+ Color,
+ 100,
+ (UINTN) PreviousValue
+ );
+
+ } else {
+ DEBUG ((EFI_D_INFO, "%d bytes of system memory tested OK\r\n", TotalMemorySize));
+ }
+
+ FreePool (Pos);
+
+
+ //
+ // Use a DynamicHii type pcd to save the boot status, which is used to
+ // control configuration mode, such as FULL/MINIMAL/NO_CHANGES configuration.
+ //
+ IsFirstBoot = PcdGetBool(PcdBootState);
+ if (IsFirstBoot) {
+ Status = PcdSetBoolS(PcdBootState, FALSE);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((EFI_D_ERROR, "Set PcdBootState to FALSE failed.\n"));
+ }
+ }
+
+ return ReturnStatus;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.c b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.c
new file mode 100644
index 0000000000..d02001b4d1
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.c
@@ -0,0 +1,59 @@
+/** @file
+ String support
+
+Copyright (c) 2004 - 2010, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "Bds.h"
+#include "Language.h"
+#include "FrontPage.h"
+
+EFI_HII_HANDLE gStringPackHandle;
+
+EFI_GUID mBdsStringPackGuid = {
+ 0x7bac95d3, 0xddf, 0x42f3, {0x9e, 0x24, 0x7c, 0x64, 0x49, 0x40, 0x37, 0x9a}
+};
+
+/**
+ Initialize HII global accessor for string support.
+
+**/
+VOID
+InitializeStringSupport (
+ VOID
+ )
+{
+ gStringPackHandle = HiiAddPackages (
+ &mBdsStringPackGuid,
+ gImageHandle,
+ BdsDxeStrings,
+ NULL
+ );
+ ASSERT (gStringPackHandle != NULL);
+}
+
+/**
+ Get string by string id from HII Interface
+
+
+ @param Id String ID.
+
+ @retval CHAR16 * String from ID.
+ @retval NULL If error occurs.
+
+**/
+CHAR16 *
+GetStringById (
+ IN EFI_STRING_ID Id
+ )
+{
+ return HiiGetString (gStringPackHandle, Id, NULL);
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.h b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.h
new file mode 100644
index 0000000000..005b2bdbd2
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/String.h
@@ -0,0 +1,65 @@
+/** @file
+ String support
+
+Copyright (c) 2004 - 2009, 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 _STRING_H_
+#define _STRING_H_
+
+#include "Bds.h"
+
+extern EFI_HII_HANDLE gStringPackHandle;
+
+//
+// This is the VFR compiler generated header file which defines the
+// string identifiers.
+//
+
+extern UINT8 BdsDxeStrings[];
+
+/**
+ Get string by string id from HII Interface
+
+
+ @param Id String ID.
+
+ @retval CHAR16 * String from ID.
+ @retval NULL If error occurs.
+
+**/
+CHAR16 *
+GetStringById (
+ IN EFI_STRING_ID Id
+ );
+
+/**
+ Initialize HII global accessor for string support.
+
+**/
+VOID
+InitializeStringSupport (
+ VOID
+ );
+
+/**
+ Call the browser and display the front page
+
+ @return Status code that will be returned by
+ EFI_FORM_BROWSER2_PROTOCOL.SendForm ().
+
+**/
+EFI_STATUS
+CallFrontPage (
+ VOID
+ );
+
+#endif // _STRING_H_
diff --git a/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Strings.uni b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Strings.uni
new file mode 100644
index 0000000000..c0ada9535a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/BdsDxe/Strings.uni
@@ -0,0 +1,55 @@
+///** @file
+//
+// String definitions for BdsPlatform formset.
+//
+// Copyright (c) 2004 - 2010, 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.
+//
+//**/
+
+/=#
+
+#langdef en-US "English"
+#langdef fr-FR "Français"
+
+#string STR_INTERNAL_EFI_SHELL #language en-US "[Internal EFI Shell]"
+ #language fr-FR "[la Coquille interne de EFI]"
+#string STR_LEGACY_BOOT_A #language en-US "[Internal Legacy Boot A:]"
+ #language fr-FR "[Le Legs interne Charge A:]"
+#string STR_PROCESSED_ALL_BOOT_OPTIONS #language en-US "[ProcessedAllBootOptions(): Load shell from the FV]"
+ #language fr-FR "[ProcessedAllBootOptions() : la coquille de Chargement du FV]"
+#string STR_BOOT_FAILED #language en-US "Boot Failed. "
+ #language fr-FR "la Botte A. "
+#string STR_BOOT_SUCCEEDED #language en-US "Boot Succeeded - "
+ #language fr-FR "Charge Réussi - "
+#string STR_DEFAULT_TIMEOUT_BANNER #language en-US "Default boot selection will be booted in "
+ #language fr-FR "la sélection de botte de Défaut sera dans "
+#string STR_SECONDS #language en-US " seconds"
+ #language fr-FR " les secondes"
+#string STR_EXIT_DATA #language en-US "ExitData: "
+ #language fr-FR "ExitData: "
+#string STR_LOADING #language en-US "Loading: "
+ #language fr-FR "Chargement: "
+#string STR_ENTER_NORMAL_BOOT #language en-US "Entering Normal Boot Process..."
+ #language fr-FR "l'Entrer le Procédé de Botte Normal..."
+#string STR_PERFORM_MEM_TEST #language en-US "Perform memory test (ESC to skip)"
+ #language fr-FR "Exécute l'examen de mémoire (ESC pour sauter)"
+#string STR_MEMORY_TEST_PERCENT #language en-US "% of the system memory tested OK"
+ #language fr-FR "% de la mémoire de système essayée D'ACCORD"
+#string STR_ESC_TO_SKIP_MEM_TEST #language en-US "Press ESC key to skip memory test"
+ #language fr-FR "Appuie sur ESC sauter examen de mémoire"
+#string STR_MEM_TEST_COMPLETED #language en-US " bytes of system memory tested OK\r\n"
+ #language fr-FR "octets dela mémoire de système essayée D'ACCORD\r\n"
+#string STR_NO_EXT_MEM_FOUND #language en-US "Memory resource updated!"
+ #language fr-FR "la mémoire Non étendue trouvée!"
+#string STR_SYSTEM_MEM_ERROR #language en-US "System encounters memory errors"
+ #language fr-FR "le Système rencontre les erreurs de mémoire"
+#string STR_START_BOOT_OPTION #language en-US "Start boot option"
+ #language fr-FR "l'option de botte de Début"
+ \ No newline at end of file
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/ComponentName.c b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/ComponentName.c
new file mode 100644
index 0000000000..d637decb94
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/ComponentName.c
@@ -0,0 +1,167 @@
+/** @file
+ UEFI Component Name(2) protocol implementation for VGA Class Driver.
+
+Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "VgaClass.h"
+
+//
+// EFI Component Name Protocol
+//
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gVgaClassComponentName = {
+ VgaClassComponentNameGetDriverName,
+ VgaClassComponentNameGetControllerName,
+ "eng"
+};
+
+//
+// EFI Component Name 2 Protocol
+//
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gVgaClassComponentName2 = {
+ (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) VgaClassComponentNameGetDriverName,
+ (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) VgaClassComponentNameGetControllerName,
+ "en"
+};
+
+
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mVgaClassDriverNameTable[] = {
+ {
+ "eng;en",
+ L"VGA Class Driver"
+ },
+ {
+ NULL,
+ NULL
+ }
+};
+
+/**
+ Retrieves a Unicode string that is the user readable name of the driver.
+
+ This function retrieves the user readable name of a driver in the form of a
+ Unicode string. If the driver specified by This has a user readable name in
+ the language specified by Language, then a pointer to the driver name is
+ returned in DriverName, and EFI_SUCCESS is returned. If the driver specified
+ by This does not support the language specified by Language,
+ then EFI_UNSUPPORTED is returned.
+
+ @param This A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
+ EFI_COMPONENT_NAME_PROTOCOL instance.
+ @param Language A pointer to a Null-terminated ASCII string
+ array indicating the language. This is the
+ language of the driver name that the caller is
+ requesting, and it must match one of the
+ languages specified in SupportedLanguages. The
+ number of languages supported by a driver is up
+ to the driver writer. Language is specified
+ in RFC 4646 or ISO 639-2 language code format.
+ @param DriverName A pointer to the Unicode string to return.
+ This Unicode string is the name of the
+ driver specified by This in the language
+ specified by Language.
+
+ @retval EFI_SUCCESS The Unicode string for the Driver specified by
+ This and the language specified by Language was
+ returned in DriverName.
+ @retval EFI_INVALID_PARAMETER Language is NULL.
+ @retval EFI_INVALID_PARAMETER DriverName is NULL.
+ @retval EFI_UNSUPPORTED The driver specified by This does not support
+ the language specified by Language.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassComponentNameGetDriverName (
+ IN EFI_COMPONENT_NAME_PROTOCOL *This,
+ IN CHAR8 *Language,
+ OUT CHAR16 **DriverName
+ )
+{
+ return LookupUnicodeString2 (
+ Language,
+ This->SupportedLanguages,
+ mVgaClassDriverNameTable,
+ DriverName,
+ (BOOLEAN)(This == &gVgaClassComponentName)
+ );
+}
+
+/**
+ Retrieves a Unicode string that is the user readable name of the controller
+ that is being managed by a driver.
+
+ This function retrieves the user readable name of the controller specified by
+ ControllerHandle and ChildHandle in the form of a Unicode string. If the
+ driver specified by This has a user readable name in the language specified by
+ Language, then a pointer to the controller name is returned in ControllerName,
+ and EFI_SUCCESS is returned. If the driver specified by This is not currently
+ managing the controller specified by ControllerHandle and ChildHandle,
+ then EFI_UNSUPPORTED is returned. If the driver specified by This does not
+ support the language specified by Language, then EFI_UNSUPPORTED is returned.
+
+ @param This A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
+ EFI_COMPONENT_NAME_PROTOCOL instance.
+ @param ControllerHandle The handle of a controller that the driver
+ specified by This is managing. This handle
+ specifies the controller whose name is to be
+ returned.
+ @param ChildHandle The handle of the child controller to retrieve
+ the name of. This is an optional parameter that
+ may be NULL. It will be NULL for device
+ drivers. It will also be NULL for a bus drivers
+ that wish to retrieve the name of the bus
+ controller. It will not be NULL for a bus
+ driver that wishes to retrieve the name of a
+ child controller.
+ @param Language A pointer to a Null-terminated ASCII string
+ array indicating the language. This is the
+ language of the driver name that the caller is
+ requesting, and it must match one of the
+ languages specified in SupportedLanguages. The
+ number of languages supported by a driver is up
+ to the driver writer. Language is specified in
+ RFC 4646 or ISO 639-2 language code format.
+ @param ControllerName A pointer to the Unicode string to return.
+ This Unicode string is the name of the
+ controller specified by ControllerHandle and
+ ChildHandle in the language specified by
+ Language from the point of view of the driver
+ specified by This.
+
+ @retval EFI_SUCCESS The Unicode string for the user readable name in
+ the language specified by Language for the
+ driver specified by This was returned in
+ DriverName.
+ @retval EFI_INVALID_PARAMETER ControllerHandle is NULL.
+ @retval EFI_INVALID_PARAMETER ChildHandle is not NULL and it is not a valid
+ EFI_HANDLE.
+ @retval EFI_INVALID_PARAMETER Language is NULL.
+ @retval EFI_INVALID_PARAMETER ControllerName is NULL.
+ @retval EFI_UNSUPPORTED The driver specified by This is not currently
+ managing the controller specified by
+ ControllerHandle and ChildHandle.
+ @retval EFI_UNSUPPORTED The driver specified by This does not support
+ the language specified by Language.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassComponentNameGetControllerName (
+ IN EFI_COMPONENT_NAME_PROTOCOL *This,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle OPTIONAL,
+ IN CHAR8 *Language,
+ OUT CHAR16 **ControllerName
+ )
+{
+ return EFI_UNSUPPORTED;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.c b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.c
new file mode 100644
index 0000000000..2d672797fa
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.c
@@ -0,0 +1,1288 @@
+/** @file
+ VGA Class Driver that managers VGA devices and produces Simple Text Output Protocol.
+
+Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "VgaClass.h"
+
+//
+// EFI Driver Binding Protocol for the VGA Class Driver
+//
+EFI_DRIVER_BINDING_PROTOCOL gVgaClassDriverBinding = {
+ VgaClassDriverBindingSupported,
+ VgaClassDriverBindingStart,
+ VgaClassDriverBindingStop,
+ 0xa,
+ NULL,
+ NULL
+};
+
+//
+// Local variables
+//
+CHAR16 CrLfString[3] = { CHAR_CARRIAGE_RETURN, CHAR_LINEFEED, CHAR_NULL };
+
+//
+// This list is used to define the valid extend chars.
+// It also provides a mapping from Unicode to PCANSI or
+// ASCII. The ASCII mapping we just made up.
+//
+//
+UNICODE_TO_CHAR UnicodeToPcAnsiOrAscii[] = {
+ {
+ BOXDRAW_HORIZONTAL,
+ 0xc4,
+ L'-'
+ },
+ {
+ BOXDRAW_VERTICAL,
+ 0xb3,
+ L'|'
+ },
+ {
+ BOXDRAW_DOWN_RIGHT,
+ 0xda,
+ L'/'
+ },
+ {
+ BOXDRAW_DOWN_LEFT,
+ 0xbf,
+ L'\\'
+ },
+ {
+ BOXDRAW_UP_RIGHT,
+ 0xc0,
+ L'\\'
+ },
+ {
+ BOXDRAW_UP_LEFT,
+ 0xd9,
+ L'/'
+ },
+ {
+ BOXDRAW_VERTICAL_RIGHT,
+ 0xc3,
+ L'|'
+ },
+ {
+ BOXDRAW_VERTICAL_LEFT,
+ 0xb4,
+ L'|'
+ },
+ {
+ BOXDRAW_DOWN_HORIZONTAL,
+ 0xc2,
+ L'+'
+ },
+ {
+ BOXDRAW_UP_HORIZONTAL,
+ 0xc1,
+ L'+'
+ },
+ {
+ BOXDRAW_VERTICAL_HORIZONTAL,
+ 0xc5,
+ L'+'
+ },
+ {
+ BOXDRAW_DOUBLE_HORIZONTAL,
+ 0xcd,
+ L'-'
+ },
+ {
+ BOXDRAW_DOUBLE_VERTICAL,
+ 0xba,
+ L'|'
+ },
+ {
+ BOXDRAW_DOWN_RIGHT_DOUBLE,
+ 0xd5,
+ L'/'
+ },
+ {
+ BOXDRAW_DOWN_DOUBLE_RIGHT,
+ 0xd6,
+ L'/'
+ },
+ {
+ BOXDRAW_DOUBLE_DOWN_RIGHT,
+ 0xc9,
+ L'/'
+ },
+ {
+ BOXDRAW_DOWN_LEFT_DOUBLE,
+ 0xb8,
+ L'\\'
+ },
+ {
+ BOXDRAW_DOWN_DOUBLE_LEFT,
+ 0xb7,
+ L'\\'
+ },
+ {
+ BOXDRAW_DOUBLE_DOWN_LEFT,
+ 0xbb,
+ L'\\'
+ },
+ {
+ BOXDRAW_UP_RIGHT_DOUBLE,
+ 0xd4,
+ L'\\'
+ },
+ {
+ BOXDRAW_UP_DOUBLE_RIGHT,
+ 0xd3,
+ L'\\'
+ },
+ {
+ BOXDRAW_DOUBLE_UP_RIGHT,
+ 0xc8,
+ L'\\'
+ },
+ {
+ BOXDRAW_UP_LEFT_DOUBLE,
+ 0xbe,
+ L'/'
+ },
+ {
+ BOXDRAW_UP_DOUBLE_LEFT,
+ 0xbd,
+ L'/'
+ },
+ {
+ BOXDRAW_DOUBLE_UP_LEFT,
+ 0xbc,
+ L'/'
+ },
+ {
+ BOXDRAW_VERTICAL_RIGHT_DOUBLE,
+ 0xc6,
+ L'|'
+ },
+ {
+ BOXDRAW_VERTICAL_DOUBLE_RIGHT,
+ 0xc7,
+ L'|'
+ },
+ {
+ BOXDRAW_DOUBLE_VERTICAL_RIGHT,
+ 0xcc,
+ L'|'
+ },
+ {
+ BOXDRAW_VERTICAL_LEFT_DOUBLE,
+ 0xb5,
+ L'|'
+ },
+ {
+ BOXDRAW_VERTICAL_DOUBLE_LEFT,
+ 0xb6,
+ L'|'
+ },
+ {
+ BOXDRAW_DOUBLE_VERTICAL_LEFT,
+ 0xb9,
+ L'|'
+ },
+ {
+ BOXDRAW_DOWN_HORIZONTAL_DOUBLE,
+ 0xd1,
+ L'+'
+ },
+ {
+ BOXDRAW_DOWN_DOUBLE_HORIZONTAL,
+ 0xd2,
+ L'+'
+ },
+ {
+ BOXDRAW_DOUBLE_DOWN_HORIZONTAL,
+ 0xcb,
+ L'+'
+ },
+ {
+ BOXDRAW_UP_HORIZONTAL_DOUBLE,
+ 0xcf,
+ L'+'
+ },
+ {
+ BOXDRAW_UP_DOUBLE_HORIZONTAL,
+ 0xd0,
+ L'+'
+ },
+ {
+ BOXDRAW_DOUBLE_UP_HORIZONTAL,
+ 0xca,
+ L'+'
+ },
+ {
+ BOXDRAW_VERTICAL_HORIZONTAL_DOUBLE,
+ 0xd8,
+ L'+'
+ },
+ {
+ BOXDRAW_VERTICAL_DOUBLE_HORIZONTAL,
+ 0xd7,
+ L'+'
+ },
+ {
+ BOXDRAW_DOUBLE_VERTICAL_HORIZONTAL,
+ 0xce,
+ L'+'
+ },
+
+ {
+ BLOCKELEMENT_FULL_BLOCK,
+ 0xdb,
+ L'*'
+ },
+ {
+ BLOCKELEMENT_LIGHT_SHADE,
+ 0xb0,
+ L'+'
+ },
+
+ {
+ GEOMETRICSHAPE_UP_TRIANGLE,
+ 0x1e,
+ L'^'
+ },
+ {
+ GEOMETRICSHAPE_RIGHT_TRIANGLE,
+ 0x10,
+ L'>'
+ },
+ {
+ GEOMETRICSHAPE_DOWN_TRIANGLE,
+ 0x1f,
+ L'v'
+ },
+ {
+ GEOMETRICSHAPE_LEFT_TRIANGLE,
+ 0x11,
+ L'<'
+ },
+
+ {
+ ARROW_LEFT,
+ 0x3c,
+ L'<'
+ },
+
+ {
+ ARROW_UP,
+ 0x18,
+ L'^'
+ },
+
+ {
+ ARROW_RIGHT,
+ 0x3e,
+ L'>'
+ },
+
+ {
+ ARROW_DOWN,
+ 0x19,
+ L'v'
+ },
+
+ {
+ 0x0000,
+ 0x00,
+ 0x00
+ }
+};
+
+/**
+ Entrypoint of this VGA Class Driver.
+
+ This function is the entrypoint of this VGA Class Driver. It installs Driver Binding
+ Protocols together with Component Name Protocols.
+
+ @param ImageHandle The firmware allocated handle for the EFI image.
+ @param SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+InitializeVgaClass(
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Install driver model protocol(s).
+ //
+ Status = EfiLibInstallDriverBindingComponentName2 (
+ ImageHandle,
+ SystemTable,
+ &gVgaClassDriverBinding,
+ ImageHandle,
+ &gVgaClassComponentName,
+ &gVgaClassComponentName2
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Internal worker function to program CRTC register via PCI I/O Protocol.
+
+ @param VgaClassDev device instance object
+ @param Address Address of register to write
+ @param Data Data to write to register.
+
+**/
+VOID
+WriteCrtc (
+ IN VGA_CLASS_DEV *VgaClassDev,
+ IN UINT16 Address,
+ IN UINT8 Data
+ )
+{
+ VgaClassDev->PciIo->Io.Write (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthUint8,
+ VgaClassDev->VgaMiniPort->CrtcAddressRegisterBar,
+ VgaClassDev->VgaMiniPort->CrtcAddressRegisterOffset,
+ 1,
+ &Address
+ );
+
+ VgaClassDev->PciIo->Io.Write (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthUint8,
+ VgaClassDev->VgaMiniPort->CrtcDataRegisterBar,
+ VgaClassDev->VgaMiniPort->CrtcDataRegisterOffset,
+ 1,
+ &Data
+ );
+}
+
+/**
+ Internal worker function to set cursor's position to VgaClass device
+
+ @param VgaClassDev Private data structure for device instance.
+ @param Column Colomn of position to set cursor to.
+ @param Row Row of position to set cursor to.
+ @param MaxColumn Max value of column.
+
+**/
+VOID
+SetVideoCursorPosition (
+ IN VGA_CLASS_DEV *VgaClassDev,
+ IN UINTN Column,
+ IN UINTN Row,
+ IN UINTN MaxColumn
+ )
+{
+ Column = Column & 0xff;
+ Row = Row & 0xff;
+ MaxColumn = MaxColumn & 0xff;
+
+ WriteCrtc (
+ VgaClassDev,
+ CRTC_CURSOR_LOCATION_HIGH,
+ (UINT8) ((Row * MaxColumn + Column) >> 8)
+ );
+ WriteCrtc (
+ VgaClassDev,
+ CRTC_CURSOR_LOCATION_LOW,
+ (UINT8) ((Row * MaxColumn + Column) & 0xff)
+ );
+}
+
+/**
+ Internal worker function to detect if a Unicode char is for Box Drawing text graphics.
+
+ @param Graphic Unicode char to test.
+ @param PcAnsi Pointer to PCANSI equivalent of Graphic for output.
+ If NULL, then PCANSI value is not returned.
+ @param Ascii Pointer to ASCII equivalent of Graphic for output.
+ If NULL, then ASCII value is not returned.
+
+ @retval TRUE Gpaphic is a supported Unicode Box Drawing character.
+ @retval FALSE Gpaphic is not a supported Unicode Box Drawing character.
+
+**/
+BOOLEAN
+LibIsValidTextGraphics (
+ IN CHAR16 Graphic,
+ OUT CHAR8 *PcAnsi, OPTIONAL
+ OUT CHAR8 *Ascii OPTIONAL
+ )
+{
+ UNICODE_TO_CHAR *Table;
+
+ //
+ // Unicode drawing code charts are all in the 0x25xx range, arrows are 0x21xx.
+ // So first filter out values not in these 2 ranges.
+ //
+ if ((((Graphic & 0xff00) != 0x2500) && ((Graphic & 0xff00) != 0x2100))) {
+ return FALSE;
+ }
+
+ //
+ // Search UnicodeToPcAnsiOrAscii table for matching entry.
+ //
+ for (Table = UnicodeToPcAnsiOrAscii; Table->Unicode != 0x0000; Table++) {
+ if (Graphic == Table->Unicode) {
+ if (PcAnsi != NULL) {
+ *PcAnsi = Table->PcAnsi;
+ }
+
+ if (Ascii != NULL) {
+ *Ascii = Table->Ascii;
+ }
+
+ return TRUE;
+ }
+ }
+
+ //
+ // If value is not found in UnicodeToPcAnsiOrAscii table, then return FALSE.
+ //
+ return FALSE;
+}
+
+/**
+ Internal worker function to check whether input value is an ASCII char.
+
+ @param Char Character to check.
+
+ @retval TRUE Input value is an ASCII char.
+ @retval FALSE Input value is not an ASCII char.
+
+**/
+BOOLEAN
+IsValidAscii (
+ IN CHAR16 Char
+ )
+{
+ if ((Char >= 0x20) && (Char <= 0x7f)) {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/**
+ Internal worker function to check whether input value is a unicode control char.
+
+ @param Char Character to check.
+
+ @retval TRUE Input value is a unicode control char.
+ @retval FALSE Input value is not a unicode control char.
+
+**/
+BOOLEAN
+IsValidEfiCntlChar (
+ IN CHAR16 Char
+ )
+{
+ if (Char == CHAR_NULL || Char == CHAR_BACKSPACE || Char == CHAR_LINEFEED || Char == CHAR_CARRIAGE_RETURN) {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/**
+ Tests to see if this driver supports a given controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Supported().
+ It Checks if this driver supports the controller specified. Any Controller
+ with VgaMiniPort Protocol and Pci I/O protocol can be supported.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle Handle of device to test
+ @param RemainingDevicePath Optional parameter use to pick a specific child
+ device to start.
+
+ @retval EFI_SUCCESS This driver supports this device.
+ @retval EFI_ALREADY_STARTED This driver is already running on this device.
+ @retval EFI_UNSUPPORTED This driver does not support this device.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingSupported (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Checks if Abstraction(s) needed to perform the supported test
+ //
+ Status = gBS->OpenProtocol (
+ Controller,
+ &gEfiVgaMiniPortProtocolGuid,
+ NULL,
+ This->DriverBindingHandle,
+ Controller,
+ EFI_OPEN_PROTOCOL_TEST_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Open the IO Abstraction(s) needed to perform the supported test
+ //
+ Status = gBS->OpenProtocol (
+ Controller,
+ &gEfiPciIoProtocolGuid,
+ NULL,
+ This->DriverBindingHandle,
+ Controller,
+ EFI_OPEN_PROTOCOL_TEST_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ return Status;
+}
+
+/**
+ Starts the device controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Start().
+ It starts the device specified by Controller with the driver based on PCI I/O Protocol
+ and VgaMiniPort Protocol. It creates context for device instance and install EFI_SIMPLE_TEXT_OUT_PROTOCOL.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle Handle of device to bind driver to
+ @param RemainingDevicePath Optional parameter use to pick a specific child
+ device to start.
+
+ @retval EFI_SUCCESS The device was started.
+ @retval other Fail to start the device.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingStart (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+ EFI_VGA_MINI_PORT_PROTOCOL *VgaMiniPort;
+ EFI_PCI_IO_PROTOCOL *PciIo;
+ VGA_CLASS_DEV *VgaClassPrivate;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+
+ Status = gBS->HandleProtocol (
+ Controller,
+ &gEfiDevicePathProtocolGuid,
+ (VOID **) &DevicePath
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Report that VGA Class driver is being enabled
+ //
+ REPORT_STATUS_CODE_WITH_DEVICE_PATH (
+ EFI_PROGRESS_CODE,
+ EFI_PERIPHERAL_LOCAL_CONSOLE | EFI_P_PC_ENABLE,
+ DevicePath
+ );
+
+ //
+ // Open the PCI I/O Protocol
+ //
+ Status = gBS->OpenProtocol (
+ Controller,
+ &gEfiPciIoProtocolGuid,
+ (VOID **) &PciIo,
+ This->DriverBindingHandle,
+ Controller,
+ EFI_OPEN_PROTOCOL_GET_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Open the VGA Mini Port Protocol
+ //
+ Status = gBS->OpenProtocol (
+ Controller,
+ &gEfiVgaMiniPortProtocolGuid,
+ (VOID **) &VgaMiniPort,
+ This->DriverBindingHandle,
+ Controller,
+ EFI_OPEN_PROTOCOL_BY_DRIVER
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Allocate the private device structure
+ //
+ VgaClassPrivate = AllocateZeroPool (sizeof (VGA_CLASS_DEV));
+ ASSERT (VgaClassPrivate != NULL);
+
+ //
+ // Initialize the private device structure
+ //
+ VgaClassPrivate->Signature = VGA_CLASS_DEV_SIGNATURE;
+ VgaClassPrivate->Handle = Controller;
+ VgaClassPrivate->VgaMiniPort = VgaMiniPort;
+ VgaClassPrivate->PciIo = PciIo;
+
+ VgaClassPrivate->SimpleTextOut.Reset = VgaClassReset;
+ VgaClassPrivate->SimpleTextOut.OutputString = VgaClassOutputString;
+ VgaClassPrivate->SimpleTextOut.TestString = VgaClassTestString;
+ VgaClassPrivate->SimpleTextOut.ClearScreen = VgaClassClearScreen;
+ VgaClassPrivate->SimpleTextOut.SetAttribute = VgaClassSetAttribute;
+ VgaClassPrivate->SimpleTextOut.SetCursorPosition = VgaClassSetCursorPosition;
+ VgaClassPrivate->SimpleTextOut.EnableCursor = VgaClassEnableCursor;
+ VgaClassPrivate->SimpleTextOut.QueryMode = VgaClassQueryMode;
+ VgaClassPrivate->SimpleTextOut.SetMode = VgaClassSetMode;
+
+ VgaClassPrivate->SimpleTextOut.Mode = &VgaClassPrivate->SimpleTextOutputMode;
+ VgaClassPrivate->SimpleTextOutputMode.MaxMode = VgaMiniPort->MaxMode;
+ VgaClassPrivate->DevicePath = DevicePath;
+
+ //
+ // Initialize the VGA device.
+ //
+ Status = VgaClassPrivate->SimpleTextOut.SetAttribute (
+ &VgaClassPrivate->SimpleTextOut,
+ EFI_TEXT_ATTR (EFI_WHITE, EFI_BLACK)
+ );
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+
+ Status = VgaClassPrivate->SimpleTextOut.Reset (
+ &VgaClassPrivate->SimpleTextOut,
+ FALSE
+ );
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+
+ Status = VgaClassPrivate->SimpleTextOut.EnableCursor (
+ &VgaClassPrivate->SimpleTextOut,
+ TRUE
+ );
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Controller,
+ &gEfiSimpleTextOutProtocolGuid,
+ &VgaClassPrivate->SimpleTextOut,
+ NULL
+ );
+
+ return Status;
+
+ErrorExit:
+ REPORT_STATUS_CODE_WITH_DEVICE_PATH (
+ EFI_ERROR_CODE | EFI_ERROR_MINOR,
+ EFI_PERIPHERAL_LOCAL_CONSOLE | EFI_P_EC_CONTROLLER_ERROR,
+ DevicePath
+ );
+
+ return Status;
+
+}
+
+/**
+ Starts the device controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Stop().
+ It stops this driver on Controller. Support stopping any child handles
+ created by this driver.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle A handle to the device being stopped.
+ @param NumberOfChildren The number of child device handles in ChildHandleBuffer.
+ @param ChildHandleBuffer An array of child handles to be freed.
+
+ @retval EFI_SUCCESS This driver is removed ControllerHandle
+ @retval other This driver was not removed from this device
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingStop (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN UINTN NumberOfChildren,
+ IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut;
+ VGA_CLASS_DEV *VgaClassPrivate;
+
+ Status = gBS->OpenProtocol (
+ Controller,
+ &gEfiSimpleTextOutProtocolGuid,
+ (VOID **) &SimpleTextOut,
+ This->DriverBindingHandle,
+ Controller,
+ EFI_OPEN_PROTOCOL_GET_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ VgaClassPrivate = VGA_CLASS_DEV_FROM_THIS (SimpleTextOut);
+
+ //
+ // Report that VGA Class driver is being disabled
+ //
+ REPORT_STATUS_CODE_WITH_DEVICE_PATH (
+ EFI_PROGRESS_CODE,
+ EFI_PERIPHERAL_LOCAL_CONSOLE | EFI_P_PC_DISABLE,
+ VgaClassPrivate->DevicePath
+ );
+
+ Status = gBS->UninstallProtocolInterface (
+ Controller,
+ &gEfiSimpleTextOutProtocolGuid,
+ &VgaClassPrivate->SimpleTextOut
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Release PCI I/O and VGA Mini Port Protocols on the controller handle.
+ //
+ gBS->CloseProtocol (
+ Controller,
+ &gEfiPciIoProtocolGuid,
+ This->DriverBindingHandle,
+ Controller
+ );
+
+ gBS->CloseProtocol (
+ Controller,
+ &gEfiVgaMiniPortProtocolGuid,
+ This->DriverBindingHandle,
+ Controller
+ );
+
+ FreePool (VgaClassPrivate);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Resets the text output device hardware.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.Reset().
+ It resets the text output device hardware. The cursor position is set to (0, 0),
+ and the screen is cleared to the default background color for the output device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ExtendedVerification Indicates that the driver may perform a more exhaustive
+ verification operation of the device during reset.
+
+ @retval EFI_SUCCESS The text output device was reset.
+ @retval EFI_DEVICE_ERROR The text output device is not functioning correctly and could not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassReset (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ )
+{
+ EFI_STATUS Status;
+ VGA_CLASS_DEV *VgaClassPrivate;
+
+ VgaClassPrivate = VGA_CLASS_DEV_FROM_THIS (This);
+
+ REPORT_STATUS_CODE_WITH_DEVICE_PATH (
+ EFI_PROGRESS_CODE,
+ EFI_PERIPHERAL_LOCAL_CONSOLE | EFI_P_PC_RESET,
+ VgaClassPrivate->DevicePath
+ );
+
+ This->SetAttribute (This, EFI_TEXT_ATTR (This->Mode->Attribute & 0x0F, EFI_BACKGROUND_BLACK));
+
+ Status = This->SetMode (This, 0);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ return This->ClearScreen (This);
+}
+
+/**
+ Writes a Unicode string to the output device.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.OutputString().
+ It writes a Unicode string to the output device. This is the most basic output mechanism
+ on an output device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param String The Null-terminated Unicode string to be displayed on the output device(s).
+
+ @retval EFI_SUCCESS The string was output to the device.
+ @retval EFI_DEVICE_ERROR The device reported an error while attempting to output the text.
+ @retval EFI_UNSUPPORTED The output device's mode is not currently in a defined text mode.
+ @retval EFI_WARN_UNKNOWN_GLYPH This warning code indicates that some of the characters in
+ the Unicode string could not be rendered and were skipped.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassOutputString (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN CHAR16 *String
+ )
+{
+ EFI_STATUS Status;
+ VGA_CLASS_DEV *VgaClassDev;
+ EFI_SIMPLE_TEXT_OUTPUT_MODE *Mode;
+ UINTN MaxColumn;
+ UINTN MaxRow;
+ UINT32 VideoChar;
+ CHAR8 GraphicChar;
+
+ VgaClassDev = VGA_CLASS_DEV_FROM_THIS (This);
+ Mode = This->Mode;
+
+ Status = This->QueryMode (
+ This,
+ Mode->Mode,
+ &MaxColumn,
+ &MaxRow
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Parse each character of the string to output
+ //
+ for (; *String != CHAR_NULL; String++) {
+
+ switch (*String) {
+ case CHAR_BACKSPACE:
+ if (Mode->CursorColumn > 0) {
+ Mode->CursorColumn--;
+ }
+ break;
+
+ case CHAR_LINEFEED:
+ if (Mode->CursorRow == (INT32) (MaxRow - 1)) {
+ //
+ // Scroll the screen by copying the contents
+ // of the VGA display up one line
+ //
+ VgaClassDev->PciIo->CopyMem (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthUint32,
+ VgaClassDev->VgaMiniPort->VgaMemoryBar,
+ VgaClassDev->VgaMiniPort->VgaMemoryOffset,
+ VgaClassDev->VgaMiniPort->VgaMemoryBar,
+ VgaClassDev->VgaMiniPort->VgaMemoryOffset + MaxColumn * 2,
+ ((MaxRow - 1) * MaxColumn) >> 1
+ );
+
+ //
+ // Print Blank Line of spaces with the current color attributes
+ //
+ VideoChar = (Mode->Attribute << 8) | ' ';
+ VideoChar = (VideoChar << 16) | VideoChar;
+ VgaClassDev->PciIo->Mem.Write (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthFillUint32,
+ VgaClassDev->VgaMiniPort->VgaMemoryBar,
+ VgaClassDev->VgaMiniPort->VgaMemoryOffset + (MaxRow - 1) * MaxColumn * 2,
+ MaxColumn >> 1,
+ &VideoChar
+ );
+ }
+
+ if (Mode->CursorRow < (INT32) (MaxRow - 1)) {
+ Mode->CursorRow++;
+ }
+ break;
+
+ case CHAR_CARRIAGE_RETURN:
+ Mode->CursorColumn = 0;
+ break;
+
+ default:
+ if (!LibIsValidTextGraphics (*String, &GraphicChar, NULL)) {
+ //
+ // If this character is not ,Box Drawing text graphics, then convert it to ASCII.
+ //
+ GraphicChar = (CHAR8) *String;
+ if (!IsValidAscii (GraphicChar)) {
+ //
+ // If not valid ASCII char, convert it to "?"
+ //
+ GraphicChar = '?';
+ }
+ }
+
+ VideoChar = (Mode->Attribute << 8) | GraphicChar;
+ VgaClassDev->PciIo->Mem.Write (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthUint16,
+ VgaClassDev->VgaMiniPort->VgaMemoryBar,
+ VgaClassDev->VgaMiniPort->VgaMemoryOffset + ((Mode->CursorRow * MaxColumn + Mode->CursorColumn) * 2),
+ 1,
+ &VideoChar
+ );
+
+ if (Mode->CursorColumn >= (INT32) (MaxColumn - 1)) {
+ This->OutputString (This, CrLfString);
+ } else {
+ Mode->CursorColumn++;
+ }
+ break;
+ }
+ }
+
+ SetVideoCursorPosition (
+ VgaClassDev,
+ (UINTN) Mode->CursorColumn,
+ (UINTN) Mode->CursorRow,
+ MaxColumn
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Verifies that all characters in a Unicode string can be output to the target device.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.TestString().
+ It verifies that all characters in a Unicode string can be output to the target device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param String The Null-terminated Unicode string to be examined for the output device(s).
+
+ @retval EFI_SUCCESS The device(s) are capable of rendering the output string.
+ @retval EFI_UNSUPPORTED Some of the characters in the Unicode string cannot be rendered by
+ one or more of the output devices mapped by the EFI handle.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassTestString (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN CHAR16 *String
+ )
+{
+ while (*String != CHAR_NULL) {
+ if (!(IsValidAscii (*String) || IsValidEfiCntlChar (*String) || LibIsValidTextGraphics (*String, NULL, NULL))) {
+ return EFI_UNSUPPORTED;
+ }
+
+ String++;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Clears the output device(s) display to the currently selected background color.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.ClearScreen().
+ The ClearScreen() function clears the output device(s) display to the currently
+ selected background color. The cursor position is set to (0, 0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+
+ @retval EFI_SUCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The output device is not in a valid text mode.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassClearScreen (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This
+ )
+{
+ EFI_STATUS Status;
+ VGA_CLASS_DEV *VgaClassDev;
+ UINTN MaxRow;
+ UINTN MaxColumn;
+ UINT32 VideoChar;
+
+ VgaClassDev = VGA_CLASS_DEV_FROM_THIS (This);
+
+ Status = This->QueryMode (
+ This,
+ This->Mode->Mode,
+ &MaxColumn,
+ &MaxRow
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ VideoChar = (This->Mode->Attribute << 8) | ' ';
+ VideoChar = (VideoChar << 16) | VideoChar;
+ VgaClassDev->PciIo->Mem.Write (
+ VgaClassDev->PciIo,
+ EfiPciIoWidthFillUint32,
+ VgaClassDev->VgaMiniPort->VgaMemoryBar,
+ VgaClassDev->VgaMiniPort->VgaMemoryOffset,
+ (MaxRow * MaxColumn) >> 1,
+ &VideoChar
+ );
+
+ This->SetCursorPosition (This, 0, 0);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets the background and foreground colors for theOutputString() and ClearScreen() functions.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.SetAttribute().
+ It sets the background and foreground colors for the OutputString() and ClearScreen() functions.
+ The color mask can be set even when the device is in an invalid text mode.
+ Devices supporting a different number of text colors are required to emulate the above colors
+ to the best of the device's capabilities.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Attribute The attribute to set.
+ Bits 0..3 are the foreground color,
+ and bits 4..6 are the background color.
+
+ @retval EFI_SUCCESS The requested attributes were set.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetAttribute (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN Attribute
+ )
+{
+ if (Attribute <= EFI_MAX_ATTRIBUTE) {
+ This->Mode->Attribute = (INT32) Attribute;
+ return EFI_SUCCESS;
+ }
+
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Sets the current coordinates of the cursor position.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.SetCursorPosition().
+ It sets the current coordinates of the cursor position.
+ The upper left corner of the screen is defined as coordinate (0, 0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Column Column of position to set the cursor to.
+ @param Row Row of position to set the cursor to.
+
+ @retval EFI_SUCCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The output device is not in a valid text mode, or the cursor
+ position is invalid for the current mode.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetCursorPosition (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN Column,
+ IN UINTN Row
+ )
+{
+ EFI_STATUS Status;
+ VGA_CLASS_DEV *VgaClassDev;
+ UINTN MaxColumn;
+ UINTN MaxRow;
+
+ VgaClassDev = VGA_CLASS_DEV_FROM_THIS (This);
+
+ Status = This->QueryMode (
+ This,
+ This->Mode->Mode,
+ &MaxColumn,
+ &MaxRow
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ if (Column >= MaxColumn || Row >= MaxRow) {
+ return EFI_UNSUPPORTED;
+ }
+
+ SetVideoCursorPosition (VgaClassDev, Column, Row, MaxColumn);
+
+ This->Mode->CursorColumn = (INT32) Column;
+ This->Mode->CursorRow = (INT32) Row;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Makes the cursor visible or invisible.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.EnableCursor().
+ It makes the cursor visible or invisible.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Visible If TRUE, the cursor is set to be visible.
+ If FALSE, the cursor is set to be invisible.
+
+ @retval EFI_SUCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request or the
+ device does not support changing the cursor mode.
+ @retval EFI_UNSUPPORTED The output device does not support visibility control of the cursor.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassEnableCursor (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN BOOLEAN Visible
+ )
+{
+ VGA_CLASS_DEV *VgaClassDev;
+
+ VgaClassDev = VGA_CLASS_DEV_FROM_THIS (This);
+ if (Visible) {
+ if (This->Mode->Mode == 1) {
+ //
+ // 80 * 50
+ //
+ WriteCrtc (VgaClassDev, CRTC_CURSOR_START, 0x06);
+ WriteCrtc (VgaClassDev, CRTC_CURSOR_END, 0x07);
+ } else {
+ //
+ // 80 * 25
+ //
+ WriteCrtc (VgaClassDev, CRTC_CURSOR_START, 0x0e);
+ WriteCrtc (VgaClassDev, CRTC_CURSOR_END, 0x0f);
+ }
+ } else {
+ WriteCrtc (VgaClassDev, CRTC_CURSOR_START, 0x20);
+ }
+
+ This->Mode->CursorVisible = Visible;
+ return EFI_SUCCESS;
+}
+
+/**
+ Returns information for an available text mode that the output device(s) supports.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.QueryMode().
+ It returns information for an available text mode that the output device(s) supports.
+ It is required that all output devices support at least 80x25 text mode. This mode is defined to be mode 0.
+ If the output devices support 80x50, that is defined to be mode 1.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ModeNumber The mode number to return information on.
+ @param Columns Columen in current mode number
+ @param Rows Row in current mode number.
+
+ @retval EFI_SUCCESS The requested mode information was returned.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The mode number was not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassQueryMode (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN ModeNumber,
+ OUT UINTN *Columns,
+ OUT UINTN *Rows
+ )
+{
+ if ((INT32) ModeNumber >= This->Mode->MaxMode) {
+ *Columns = 0;
+ *Rows = 0;
+ return EFI_UNSUPPORTED;
+ }
+
+ switch (ModeNumber) {
+ case 0:
+ *Columns = 80;
+ *Rows = 25;
+ break;
+
+ case 1:
+ *Columns = 80;
+ *Rows = 50;
+ break;
+
+ default:
+ *Columns = 0;
+ *Rows = 0;
+ return EFI_UNSUPPORTED;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets the output device(s) to a specified mode.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.QueryMode().
+ It sets the output device(s) to the requested mode.
+ On success the device is in the geometry for the requested mode,
+ and the device has been cleared to the current background color with the cursor at (0,0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ModeNumber The text mode to set.
+
+ @retval EFI_SUCCESS The requested text mode was set.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The mode number was not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetMode (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN ModeNumber
+ )
+{
+ VGA_CLASS_DEV *VgaClassDev;
+
+ VgaClassDev = VGA_CLASS_DEV_FROM_THIS (This);
+
+ if ((INT32) ModeNumber >= This->Mode->MaxMode) {
+ return EFI_UNSUPPORTED;
+ }
+
+ This->ClearScreen (This);
+
+ This->Mode->Mode = (INT32) ModeNumber;
+
+ return VgaClassDev->VgaMiniPort->SetMode (VgaClassDev->VgaMiniPort, ModeNumber);
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.h b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.h
new file mode 100644
index 0000000000..8ecd4c068b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClass.h
@@ -0,0 +1,484 @@
+/** @file
+ Internal include file of the VGA Class Driver.
+
+Copyright (c) 2006 - 2011, 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 _VGA_CLASS_H__
+#define _VGA_CLASS_H__
+
+#include <FrameworkDxe.h>
+
+#include <Protocol/SimpleTextOut.h>
+#include <Protocol/PciIo.h>
+#include <Protocol/VgaMiniPort.h>
+#include <Protocol/DevicePath.h>
+
+#include <Library/DebugLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/ReportStatusCodeLib.h>
+
+#include <IndustryStandard/Pci.h>
+
+//
+// Global Variables
+//
+extern EFI_DRIVER_BINDING_PROTOCOL gVgaClassDriverBinding;
+extern EFI_COMPONENT_NAME_PROTOCOL gVgaClassComponentName;
+extern EFI_COMPONENT_NAME2_PROTOCOL gVgaClassComponentName2;
+
+
+//
+// Structure for tuple containing mapping among uniocde, PC Ansi and ASCII code.
+//
+typedef struct {
+ CHAR16 Unicode;
+ CHAR8 PcAnsi;
+ CHAR8 Ascii;
+} UNICODE_TO_CHAR;
+
+//
+// VGA specific registers
+//
+#define CRTC_CURSOR_START 0xA
+#define CRTC_CURSOR_END 0xB
+
+#define CRTC_CURSOR_LOCATION_HIGH 0xE
+#define CRTC_CURSOR_LOCATION_LOW 0xF
+
+#define EFI_MAX_ATTRIBUTE 0x7f
+
+//
+// VGA Class Device Structure
+//
+#define VGA_CLASS_DEV_SIGNATURE SIGNATURE_32 ('V', 'G', 'A', 'C')
+
+typedef struct {
+ UINTN Signature;
+ EFI_HANDLE Handle;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL SimpleTextOut;
+ EFI_SIMPLE_TEXT_OUTPUT_MODE SimpleTextOutputMode;
+ EFI_VGA_MINI_PORT_PROTOCOL *VgaMiniPort;
+ EFI_PCI_IO_PROTOCOL *PciIo;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+} VGA_CLASS_DEV;
+
+#define VGA_CLASS_DEV_FROM_THIS(a) CR (a, VGA_CLASS_DEV, SimpleTextOut, VGA_CLASS_DEV_SIGNATURE)
+
+//
+// Driver Binding Protocol functions
+//
+
+/**
+ Tests to see if this driver supports a given controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Supported().
+ It Checks if this driver supports the controller specified. Any Controller
+ with VgaMiniPort Protocol and Pci I/O protocol can be supported.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle Handle of device to test
+ @param RemainingDevicePath Optional parameter use to pick a specific child
+ device to start.
+
+ @retval EFI_SUCCESS This driver supports this device.
+ @retval EFI_ALREADY_STARTED This driver is already running on this device.
+ @retval EFI_UNSUPPORTED This driver does not support this device.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingSupported (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
+ );
+
+/**
+ Starts the device controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Start().
+ It starts the device specified by Controller with the driver based on PCI I/O Protocol
+ and VgaMiniPort Protocol. It creates context for device instance and install EFI_SIMPLE_TEXT_OUT_PROTOCOL.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle Handle of device to bind driver to
+ @param RemainingDevicePath Optional parameter use to pick a specific child
+ device to start.
+
+ @retval EFI_SUCCESS The device was started.
+ @retval other Fail to start the device.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingStart (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
+ );
+
+/**
+ Starts the device controller.
+
+ This function implments EFI_DRIVER_BINDING_PROTOCOL.Stop().
+ It stops this driver on Controller. Support stopping any child handles
+ created by this driver.
+
+ @param This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
+ @param ControllerHandle A handle to the device being stopped.
+ @param NumberOfChildren The number of child device handles in ChildHandleBuffer.
+ @param ChildHandleBuffer An array of child handles to be freed.
+
+ @retval EFI_SUCCESS This driver is removed ControllerHandle
+ @retval other This driver was not removed from this device
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassDriverBindingStop (
+ IN EFI_DRIVER_BINDING_PROTOCOL *This,
+ IN EFI_HANDLE Controller,
+ IN UINTN NumberOfChildren,
+ IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
+ );
+
+//
+// EFI Component Name Functions
+//
+
+/**
+ Retrieves a Unicode string that is the user readable name of the driver.
+
+ This function retrieves the user readable name of a driver in the form of a
+ Unicode string. If the driver specified by This has a user readable name in
+ the language specified by Language, then a pointer to the driver name is
+ returned in DriverName, and EFI_SUCCESS is returned. If the driver specified
+ by This does not support the language specified by Language,
+ then EFI_UNSUPPORTED is returned.
+
+ @param This A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
+ EFI_COMPONENT_NAME_PROTOCOL instance.
+ @param Language A pointer to a Null-terminated ASCII string
+ array indicating the language. This is the
+ language of the driver name that the caller is
+ requesting, and it must match one of the
+ languages specified in SupportedLanguages. The
+ number of languages supported by a driver is up
+ to the driver writer. Language is specified
+ in RFC 4646 or ISO 639-2 language code format.
+ @param DriverName A pointer to the Unicode string to return.
+ This Unicode string is the name of the
+ driver specified by This in the language
+ specified by Language.
+
+ @retval EFI_SUCCESS The Unicode string for the Driver specified by
+ This and the language specified by Language was
+ returned in DriverName.
+ @retval EFI_INVALID_PARAMETER Language is NULL.
+ @retval EFI_INVALID_PARAMETER DriverName is NULL.
+ @retval EFI_UNSUPPORTED The driver specified by This does not support
+ the language specified by Language.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassComponentNameGetDriverName (
+ IN EFI_COMPONENT_NAME_PROTOCOL *This,
+ IN CHAR8 *Language,
+ OUT CHAR16 **DriverName
+ );
+
+/**
+ Retrieves a Unicode string that is the user readable name of the controller
+ that is being managed by a driver.
+
+ This function retrieves the user readable name of the controller specified by
+ ControllerHandle and ChildHandle in the form of a Unicode string. If the
+ driver specified by This has a user readable name in the language specified by
+ Language, then a pointer to the controller name is returned in ControllerName,
+ and EFI_SUCCESS is returned. If the driver specified by This is not currently
+ managing the controller specified by ControllerHandle and ChildHandle,
+ then EFI_UNSUPPORTED is returned. If the driver specified by This does not
+ support the language specified by Language, then EFI_UNSUPPORTED is returned.
+
+ @param This A pointer to the EFI_COMPONENT_NAME2_PROTOCOL or
+ EFI_COMPONENT_NAME_PROTOCOL instance.
+ @param ControllerHandle The handle of a controller that the driver
+ specified by This is managing. This handle
+ specifies the controller whose name is to be
+ returned.
+ @param ChildHandle The handle of the child controller to retrieve
+ the name of. This is an optional parameter that
+ may be NULL. It will be NULL for device
+ drivers. It will also be NULL for a bus drivers
+ that wish to retrieve the name of the bus
+ controller. It will not be NULL for a bus
+ driver that wishes to retrieve the name of a
+ child controller.
+ @param Language A pointer to a Null-terminated ASCII string
+ array indicating the language. This is the
+ language of the driver name that the caller is
+ requesting, and it must match one of the
+ languages specified in SupportedLanguages. The
+ number of languages supported by a driver is up
+ to the driver writer. Language is specified in
+ RFC 4646 or ISO 639-2 language code format.
+ @param ControllerName A pointer to the Unicode string to return.
+ This Unicode string is the name of the
+ controller specified by ControllerHandle and
+ ChildHandle in the language specified by
+ Language from the point of view of the driver
+ specified by This.
+
+ @retval EFI_SUCCESS The Unicode string for the user readable name in
+ the language specified by Language for the
+ driver specified by This was returned in
+ DriverName.
+ @retval EFI_INVALID_PARAMETER ControllerHandle is NULL.
+ @retval EFI_INVALID_PARAMETER ChildHandle is not NULL and it is not a valid
+ EFI_HANDLE.
+ @retval EFI_INVALID_PARAMETER Language is NULL.
+ @retval EFI_INVALID_PARAMETER ControllerName is NULL.
+ @retval EFI_UNSUPPORTED The driver specified by This is not currently
+ managing the controller specified by
+ ControllerHandle and ChildHandle.
+ @retval EFI_UNSUPPORTED The driver specified by This does not support
+ the language specified by Language.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassComponentNameGetControllerName (
+ IN EFI_COMPONENT_NAME_PROTOCOL *This,
+ IN EFI_HANDLE ControllerHandle,
+ IN EFI_HANDLE ChildHandle OPTIONAL,
+ IN CHAR8 *Language,
+ OUT CHAR16 **ControllerName
+ );
+
+//
+// Simple Text Output Protocol functions
+//
+/**
+ Resets the text output device hardware.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.Reset().
+ It resets the text output device hardware. The cursor position is set to (0, 0),
+ and the screen is cleared to the default background color for the output device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ExtendedVerification Indicates that the driver may perform a more exhaustive
+ verification operation of the device during reset.
+
+ @retval EFI_SUCCESS The text output device was reset.
+ @retval EFI_DEVICE_ERROR The text output device is not functioning correctly and could not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassReset (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ );
+
+/**
+ Writes a Unicode string to the output device.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.OutputString().
+ It writes a Unicode string to the output device. This is the most basic output mechanism
+ on an output device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param String The Null-terminated Unicode string to be displayed on the output device(s).
+
+ @retval EFI_SUCCESS The string was output to the device.
+ @retval EFI_DEVICE_ERROR The device reported an error while attempting to output the text.
+ @retval EFI_UNSUPPORTED The output device's mode is not currently in a defined text mode.
+ @retval EFI_WARN_UNKNOWN_GLYPH This warning code indicates that some of the characters in
+ the Unicode string could not be rendered and were skipped.
+**/
+EFI_STATUS
+EFIAPI
+VgaClassOutputString (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN CHAR16 *String
+ );
+
+/**
+ Verifies that all characters in a Unicode string can be output to the target device.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.TestString().
+ It verifies that all characters in a Unicode string can be output to the target device.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param String The Null-terminated Unicode string to be examined for the output device(s).
+
+ @retval EFI_SUCCESS The device(s) are capable of rendering the output string.
+ @retval EFI_UNSUPPORTED Some of the characters in the Unicode string cannot be rendered by
+ one or more of the output devices mapped by the EFI handle.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassTestString (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN CHAR16 *String
+ );
+
+/**
+ Clears the output device(s) display to the currently selected background color.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.ClearScreen().
+ The ClearScreen() function clears the output device(s) display to the currently
+ selected background color. The cursor position is set to (0, 0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+
+ @retval EFI_SUCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The output device is not in a valid text mode.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassClearScreen (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This
+ );
+
+/**
+ Sets the background and foreground colors for theOutputString() and ClearScreen() functions.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.SetAttribute().
+ It sets the background and foreground colors for the OutputString() and ClearScreen() functions.
+ The color mask can be set even when the device is in an invalid text mode.
+ Devices supporting a different number of text colors are required to emulate the above colors
+ to the best of the device's capabilities.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Attribute The attribute to set.
+ Bits 0..3 are the foreground color,
+ and bits 4..6 are the background color.
+
+ @retval EFI_SUCCESS The requested attributes were set.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetAttribute (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN Attribute
+ );
+
+/**
+ Sets the current coordinates of the cursor position.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.SetCursorPosition().
+ It sets the current coordinates of the cursor position.
+ The upper left corner of the screen is defined as coordinate (0, 0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Column Column of position to set the cursor to.
+ @param Row Row of position to set the cursor to.
+
+ @retval EFI_SUCCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The output device is not in a valid text mode, or the cursor
+ position is invalid for the current mode.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetCursorPosition (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN Column,
+ IN UINTN Row
+ );
+
+/**
+ Makes the cursor visible or invisible.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.EnableCursor().
+ It makes the cursor visible or invisible.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param Visible If TRUE, the cursor is set to be visible.
+ If FALSE, the cursor is set to be invisible.
+
+ @retval EFI_SUCESS The operation completed successfully.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request or the
+ device does not support changing the cursor mode.
+ @retval EFI_UNSUPPORTED The output device does not support visibility control of the cursor.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassEnableCursor (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN BOOLEAN Visible
+ );
+
+/**
+ Returns information for an available text mode that the output device(s) supports.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.QueryMode().
+ It returns information for an available text mode that the output device(s) supports.
+ It is required that all output devices support at least 80x25 text mode. This mode is defined to be mode 0.
+ If the output devices support 80x50, that is defined to be mode 1.
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ModeNumber The mode number to return information on.
+ @param Columns Columen in current mode number
+ @param Rows Row in current mode number.
+
+ @retval EFI_SUCCESS The requested mode information was returned.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The mode number was not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassQueryMode (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN ModeNumber,
+ OUT UINTN *Columns,
+ OUT UINTN *Rows
+ );
+
+/**
+ Sets the output device(s) to a specified mode.
+
+ This function implements EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.QueryMode().
+ It sets the output device(s) to the requested mode.
+ On success the device is in the geometry for the requested mode,
+ and the device has been cleared to the current background color with the cursor at (0,0).
+
+ @param This Pointer to EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
+ @param ModeNumber The text mode to set.
+
+ @retval EFI_SUCCESS The requested text mode was set.
+ @retval EFI_DEVICE_ERROR The device had an error and could not complete the request.
+ @retval EFI_UNSUPPORTED The mode number was not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+VgaClassSetMode (
+ IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
+ IN UINTN ModeNumber
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.inf b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.inf
new file mode 100644
index 0000000000..2faba9d6f7
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.inf
@@ -0,0 +1,64 @@
+## @file
+# VGA Class Driver that managers VGA devices and produces Simple Text Output Protocol.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = VgaClassDxe
+ MODULE_UNI_FILE = VgaClassDxe.uni
+ FILE_GUID = BF89F10D-B205-474f-96E3-7A7BB1B4A407
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = InitializeVgaClass
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+# DRIVER_BINDING = gVgaClassDriverBinding
+# COMPONENT_NAME = gVgaClassComponentName
+# COMPONENT_NAME2 = gVgaClassComponentName2
+#
+
+[Sources]
+ ComponentName.c
+ VgaClass.h
+ VgaClass.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+
+[LibraryClasses]
+ ReportStatusCodeLib
+ UefiBootServicesTableLib
+ MemoryAllocationLib
+ UefiLib
+ UefiDriverEntryPoint
+ DebugLib
+
+
+[Protocols]
+ gEfiSimpleTextOutProtocolGuid ## BY_START
+ gEfiVgaMiniPortProtocolGuid ## TO_START
+ gEfiPciIoProtocolGuid ## TO_START
+ gEfiDevicePathProtocolGuid ## TO_START
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ VgaClassDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.uni b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.uni
new file mode 100644
index 0000000000..b019ae789a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxe.uni
@@ -0,0 +1,22 @@
+// /** @file
+// VGA Class Driver that managers VGA devices and produces Simple Text Output Protocol.
+//
+// The VGA Class Driver that manages VGA devices and produces Simple Text Output Protocol.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Manages VGA devices and produces Simple Text Output Protocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The VGA Class Driver that manages VGA devices and produces Simple Text Output Protocol."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxeExtra.uni
new file mode 100644
index 0000000000..16dcb9e012
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/Console/VgaClassDxe/VgaClassDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// VgaClassDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"VGA Class DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.c b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.c
new file mode 100644
index 0000000000..9474606e20
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.c
@@ -0,0 +1,588 @@
+/** @file
+ Uses the services of the I/O Library to produce the CPU I/O Protocol
+
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
+
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "CpuIo.h"
+
+//
+// Handle for the CPU I/O Protocol
+//
+EFI_HANDLE mHandle = NULL;
+
+//
+// CPU I/O Protocol inatance
+//
+EFI_CPU_IO_PROTOCOL mCpuIo = {
+ {
+ CpuMemoryServiceRead,
+ CpuMemoryServiceWrite
+ },
+ {
+ CpuIoServiceRead,
+ CpuIoServiceWrite
+ }
+};
+
+//
+// Lookup table for increment values based on transfer widths
+//
+UINT8 mInStride[] = {
+ 1, // EfiCpuIoWidthUint8
+ 2, // EfiCpuIoWidthUint16
+ 4, // EfiCpuIoWidthUint32
+ 8, // EfiCpuIoWidthUint64
+ 0, // EfiCpuIoWidthFifoUint8
+ 0, // EfiCpuIoWidthFifoUint16
+ 0, // EfiCpuIoWidthFifoUint32
+ 0, // EfiCpuIoWidthFifoUint64
+ 1, // EfiCpuIoWidthFillUint8
+ 2, // EfiCpuIoWidthFillUint16
+ 4, // EfiCpuIoWidthFillUint32
+ 8 // EfiCpuIoWidthFillUint64
+};
+
+//
+// Lookup table for increment values based on transfer widths
+//
+UINT8 mOutStride[] = {
+ 1, // EfiCpuIoWidthUint8
+ 2, // EfiCpuIoWidthUint16
+ 4, // EfiCpuIoWidthUint32
+ 8, // EfiCpuIoWidthUint64
+ 1, // EfiCpuIoWidthFifoUint8
+ 2, // EfiCpuIoWidthFifoUint16
+ 4, // EfiCpuIoWidthFifoUint32
+ 8, // EfiCpuIoWidthFifoUint64
+ 0, // EfiCpuIoWidthFillUint8
+ 0, // EfiCpuIoWidthFillUint16
+ 0, // EfiCpuIoWidthFillUint32
+ 0 // EfiCpuIoWidthFillUint64
+};
+
+/**
+ Check parameters to a CPU I/O Protocol service request.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ @param[in] MmioOperation TRUE for an MMIO operation, FALSE for I/O Port operation.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[in] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The parameters for this request pass the checks.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+CpuIoCheckParameter (
+ IN BOOLEAN MmioOperation,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ UINT64 MaxCount;
+ UINT64 Limit;
+
+ //
+ // Check to see if Buffer is NULL
+ //
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Check to see if Width is in the valid range
+ //
+ if ((UINT32)Width >= EfiCpuIoWidthMaximum) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // For FIFO type, the target address won't increase during the access,
+ // so treat Count as 1
+ //
+ if (Width >= EfiCpuIoWidthFifoUint8 && Width <= EfiCpuIoWidthFifoUint64) {
+ Count = 1;
+ }
+
+ //
+ // Check to see if Width is in the valid range for I/O Port operations
+ //
+ Width = (EFI_CPU_IO_PROTOCOL_WIDTH) (Width & 0x03);
+ if (!MmioOperation && (Width == EfiCpuIoWidthUint64)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Check to see if Address is aligned
+ //
+ if ((Address & ((UINT64)mInStride[Width] - 1)) != 0) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //
+ // Check to see if any address associated with this transfer exceeds the maximum
+ // allowed address. The maximum address implied by the parameters passed in is
+ // Address + Size * Count. If the following condition is met, then the transfer
+ // is not supported.
+ //
+ // Address + Size * Count > (MmioOperation ? MAX_ADDRESS : MAX_IO_PORT_ADDRESS) + 1
+ //
+ // Since MAX_ADDRESS can be the maximum integer value supported by the CPU and Count
+ // can also be the maximum integer value supported by the CPU, this range
+ // check must be adjusted to avoid all overflow conditions.
+ //
+ // The following form of the range check is equivalent but assumes that
+ // MAX_ADDRESS and MAX_IO_PORT_ADDRESS are of the form (2^n - 1).
+ //
+ Limit = (MmioOperation ? MAX_ADDRESS : MAX_IO_PORT_ADDRESS);
+ if (Count == 0) {
+ if (Address > Limit) {
+ return EFI_UNSUPPORTED;
+ }
+ } else {
+ MaxCount = RShiftU64 (Limit, Width);
+ if (MaxCount < (Count - 1)) {
+ return EFI_UNSUPPORTED;
+ }
+ if (Address > LShiftU64 (MaxCount - Count + 1, Width)) {
+ return EFI_UNSUPPORTED;
+ }
+ }
+
+ //
+ // Check to see if Buffer is aligned
+ // (IA-32 allows UINT64 and INT64 data types to be 32-bit aligned.)
+ //
+ if (((UINTN)Buffer & ((MIN (sizeof (UINTN), mInStride[Width]) - 1))) != 0) {
+ return EFI_UNSUPPORTED;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Reads memory-mapped registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[out] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceRead (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT8 InStride;
+ UINT8 OutStride;
+ EFI_CPU_IO_PROTOCOL_WIDTH OperationWidth;
+ UINT8 *Uint8Buffer;
+
+ Status = CpuIoCheckParameter (TRUE, Width, Address, Count, Buffer);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Select loop based on the width of the transfer
+ //
+ InStride = mInStride[Width];
+ OutStride = mOutStride[Width];
+ OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH) (Width & 0x03);
+ for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+ if (OperationWidth == EfiCpuIoWidthUint8) {
+ *Uint8Buffer = MmioRead8 ((UINTN)Address);
+ } else if (OperationWidth == EfiCpuIoWidthUint16) {
+ *((UINT16 *)Uint8Buffer) = MmioRead16 ((UINTN)Address);
+ } else if (OperationWidth == EfiCpuIoWidthUint32) {
+ *((UINT32 *)Uint8Buffer) = MmioRead32 ((UINTN)Address);
+ } else if (OperationWidth == EfiCpuIoWidthUint64) {
+ *((UINT64 *)Uint8Buffer) = MmioRead64 ((UINTN)Address);
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Writes memory-mapped registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[in] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceWrite (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT8 InStride;
+ UINT8 OutStride;
+ EFI_CPU_IO_PROTOCOL_WIDTH OperationWidth;
+ UINT8 *Uint8Buffer;
+
+ Status = CpuIoCheckParameter (TRUE, Width, Address, Count, Buffer);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Select loop based on the width of the transfer
+ //
+ InStride = mInStride[Width];
+ OutStride = mOutStride[Width];
+ OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH) (Width & 0x03);
+ for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+ if (OperationWidth == EfiCpuIoWidthUint8) {
+ MmioWrite8 ((UINTN)Address, *Uint8Buffer);
+ } else if (OperationWidth == EfiCpuIoWidthUint16) {
+ MmioWrite16 ((UINTN)Address, *((UINT16 *)Uint8Buffer));
+ } else if (OperationWidth == EfiCpuIoWidthUint32) {
+ MmioWrite32 ((UINTN)Address, *((UINT32 *)Uint8Buffer));
+ } else if (OperationWidth == EfiCpuIoWidthUint64) {
+ MmioWrite64 ((UINTN)Address, *((UINT64 *)Uint8Buffer));
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+ Reads I/O registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[out] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceRead (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT8 InStride;
+ UINT8 OutStride;
+ EFI_CPU_IO_PROTOCOL_WIDTH OperationWidth;
+ UINT8 *Uint8Buffer;
+
+ Status = CpuIoCheckParameter (FALSE, Width, Address, Count, Buffer);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Select loop based on the width of the transfer
+ //
+ InStride = mInStride[Width];
+ OutStride = mOutStride[Width];
+ OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH) (Width & 0x03);
+
+ //
+ // Fifo operations supported for (mInStride[Width] == 0)
+ //
+ if (InStride == 0) {
+ switch (OperationWidth) {
+ case EfiCpuIoWidthUint8:
+ IoReadFifo8 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ case EfiCpuIoWidthUint16:
+ IoReadFifo16 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ case EfiCpuIoWidthUint32:
+ IoReadFifo32 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ default:
+ //
+ // The CpuIoCheckParameter call above will ensure that this
+ // path is not taken.
+ //
+ ASSERT (FALSE);
+ break;
+ }
+ }
+
+ for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+ if (OperationWidth == EfiCpuIoWidthUint8) {
+ *Uint8Buffer = IoRead8 ((UINTN)Address);
+ } else if (OperationWidth == EfiCpuIoWidthUint16) {
+ *((UINT16 *)Uint8Buffer) = IoRead16 ((UINTN)Address);
+ } else if (OperationWidth == EfiCpuIoWidthUint32) {
+ *((UINT32 *)Uint8Buffer) = IoRead32 ((UINTN)Address);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write I/O registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[in] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceWrite (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT8 InStride;
+ UINT8 OutStride;
+ EFI_CPU_IO_PROTOCOL_WIDTH OperationWidth;
+ UINT8 *Uint8Buffer;
+
+ //
+ // Make sure the parameters are valid
+ //
+ Status = CpuIoCheckParameter (FALSE, Width, Address, Count, Buffer);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Select loop based on the width of the transfer
+ //
+ InStride = mInStride[Width];
+ OutStride = mOutStride[Width];
+ OperationWidth = (EFI_CPU_IO_PROTOCOL_WIDTH) (Width & 0x03);
+
+ //
+ // Fifo operations supported for (mInStride[Width] == 0)
+ //
+ if (InStride == 0) {
+ switch (OperationWidth) {
+ case EfiCpuIoWidthUint8:
+ IoWriteFifo8 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ case EfiCpuIoWidthUint16:
+ IoWriteFifo16 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ case EfiCpuIoWidthUint32:
+ IoWriteFifo32 ((UINTN)Address, Count, Buffer);
+ return EFI_SUCCESS;
+ default:
+ //
+ // The CpuIoCheckParameter call above will ensure that this
+ // path is not taken.
+ //
+ ASSERT (FALSE);
+ break;
+ }
+ }
+
+ for (Uint8Buffer = (UINT8 *)Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) {
+ if (OperationWidth == EfiCpuIoWidthUint8) {
+ IoWrite8 ((UINTN)Address, *Uint8Buffer);
+ } else if (OperationWidth == EfiCpuIoWidthUint16) {
+ IoWrite16 ((UINTN)Address, *((UINT16 *)Uint8Buffer));
+ } else if (OperationWidth == EfiCpuIoWidthUint32) {
+ IoWrite32 ((UINTN)Address, *((UINT32 *)Uint8Buffer));
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The user Entry Point for module CpuIo. The user code starts with this function.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+ @retval other Some error occurs when executing this entry point.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuIoInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiCpuIoProtocolGuid);
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &mHandle,
+ &gEfiCpuIoProtocolGuid, &mCpuIo,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.h b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.h
new file mode 100644
index 0000000000..6eba9c09e7
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIo.h
@@ -0,0 +1,226 @@
+/** @file
+ Internal include file of CPU I/O DXE Driver.
+
+ Copyright (c) 2004 - 2010, 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 __CPU_IO_DXE_H__
+#define __CPU_IO_DXE_H__
+
+
+#include <PiDxe.h>
+
+#include <Protocol/CpuIo.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#define MAX_IO_PORT_ADDRESS 0xFFFF
+
+/**
+ Reads memory-mapped registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[out] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceRead (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes memory-mapped registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[in] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuMemoryServiceWrite (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+/**
+ Reads I/O registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[out] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceRead (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Write I/O registers.
+
+ The I/O operations are carried out exactly as requested. The caller is responsible
+ for satisfying any alignment and I/O width restrictions that a PI System on a
+ platform might require. For example on some platforms, width requests of
+ EfiCpuIoWidthUint64 do not work. Misaligned buffers, on the other hand, will
+ be handled by the driver.
+
+ If Width is EfiCpuIoWidthUint8, EfiCpuIoWidthUint16, EfiCpuIoWidthUint32,
+ or EfiCpuIoWidthUint64, then both Address and Buffer are incremented for
+ each of the Count operations that is performed.
+
+ If Width is EfiCpuIoWidthFifoUint8, EfiCpuIoWidthFifoUint16,
+ EfiCpuIoWidthFifoUint32, or EfiCpuIoWidthFifoUint64, then only Buffer is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times on the same Address.
+
+ If Width is EfiCpuIoWidthFillUint8, EfiCpuIoWidthFillUint16,
+ EfiCpuIoWidthFillUint32, or EfiCpuIoWidthFillUint64, then only Address is
+ incremented for each of the Count operations that is performed. The read or
+ write operation is performed Count times from the first element of Buffer.
+
+ @param[in] This A pointer to the EFI_CPU_IO_PROTOCOL instance.
+ @param[in] Width Signifies the width of the I/O or Memory operation.
+ @param[in] Address The base address of the I/O operation.
+ @param[in] Count The number of I/O operations to perform. The number of
+ bytes moved is Width size * Count, starting at Address.
+ @param[in] Buffer For read operations, the destination buffer to store the results.
+ For write operations, the source buffer from which to write data.
+
+ @retval EFI_SUCCESS The data was read from or written to the PI system.
+ @retval EFI_INVALID_PARAMETER Width is invalid for this PI system.
+ @retval EFI_INVALID_PARAMETER Buffer is NULL.
+ @retval EFI_UNSUPPORTED The Buffer is not aligned for the given Width.
+ @retval EFI_UNSUPPORTED The address range specified by Address, Width,
+ and Count is not valid for this PI system.
+
+**/
+EFI_STATUS
+EFIAPI
+CpuIoServiceWrite (
+ IN EFI_CPU_IO_PROTOCOL *This,
+ IN EFI_CPU_IO_PROTOCOL_WIDTH Width,
+ IN UINT64 Address,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.inf b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.inf
new file mode 100644
index 0000000000..368fa75bbb
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.inf
@@ -0,0 +1,51 @@
+## @file
+# Module that produces the Framework CPU I/O Protocol using the services of the I/O Library
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CpuIoDxe
+ MODULE_UNI_FILE = CpuIoDxe.uni
+ FILE_GUID = BAE7599F-3C6B-43b7-BDF0-9CE07AA91AA6
+ MODULE_TYPE = DXE_RUNTIME_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = CpuIoInitialize
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ CpuIo.c
+ CpuIo.h
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+
+[LibraryClasses]
+ UefiDriverEntryPoint
+ BaseLib
+ DebugLib
+ IoLib
+ UefiBootServicesTableLib
+
+[Protocols]
+ gEfiCpuIoProtocolGuid ## PRODUCES
+
+[Depex]
+ TRUE
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ CpuIoDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.uni b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.uni
new file mode 100644
index 0000000000..bd2610afe4
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxe.uni
@@ -0,0 +1,21 @@
+// /** @file
+// Module that produces the Framework CPU I/O Protocol using the services of the I/O Library
+//
+// The module that produces the Framework CPU I/O Protocol using the services of the I/O Library.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces the Framework CPU I/O Protocol using the services of the I/O Library"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The module that produces the Framework CPU I/O Protocol using the services of the I/O Library."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxeExtra.uni
new file mode 100644
index 0000000000..af1ae5df1b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/CpuIoDxe/CpuIoDxeExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// CpuIoDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Processor I/O DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.c b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.c
new file mode 100644
index 0000000000..9a193d5ff0
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.c
@@ -0,0 +1,587 @@
+/** @file
+ This code produces the Data Hub protocol. It preloads the data hub
+ with status information copied in from PEI HOBs.
+
+Copyright (c) 2006 - 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.
+
+**/
+
+#include "DataHub.h"
+
+//
+// Since this driver will only ever produce one instance of the Logging Hub
+// protocol you are not required to dynamically allocate the PrivateData.
+//
+DATA_HUB_INSTANCE mPrivateData;
+
+/**
+ Log data record into the data logging hub
+
+ @param This Protocol instance structure
+ @param DataRecordGuid GUID that defines record contents
+ @param ProducerName GUID that defines the name of the producer of the data
+ @param DataRecordClass Class that defines generic record type
+ @param RawData Data Log record as defined by DataRecordGuid
+ @param RawDataSize Size of Data Log data in bytes
+
+ @retval EFI_SUCCESS If data was logged
+ @retval EFI_OUT_OF_RESOURCES If data was not logged due to lack of system
+ resources.
+**/
+EFI_STATUS
+EFIAPI
+DataHubLogData (
+ IN EFI_DATA_HUB_PROTOCOL *This,
+ IN EFI_GUID *DataRecordGuid,
+ IN EFI_GUID *ProducerName,
+ IN UINT64 DataRecordClass,
+ IN VOID *RawData,
+ IN UINT32 RawDataSize
+ )
+{
+ EFI_STATUS Status;
+ DATA_HUB_INSTANCE *Private;
+ EFI_DATA_ENTRY *LogEntry;
+ UINT32 TotalSize;
+ UINT32 RecordSize;
+ EFI_DATA_RECORD_HEADER *Record;
+ VOID *Raw;
+ DATA_HUB_FILTER_DRIVER *FilterEntry;
+ LIST_ENTRY *Link;
+ LIST_ENTRY *Head;
+ EFI_TIME LogTime;
+
+ Private = DATA_HUB_INSTANCE_FROM_THIS (This);
+
+ //
+ // Combine the storage for the internal structs and a copy of the log record.
+ // Record follows PrivateLogEntry. The consumer will be returned a pointer
+ // to Record so we don't what it to be the thing that was allocated from
+ // pool, so the consumer can't free an data record by mistake.
+ //
+ RecordSize = sizeof (EFI_DATA_RECORD_HEADER) + RawDataSize;
+ TotalSize = sizeof (EFI_DATA_ENTRY) + RecordSize;
+
+ //
+ // First try to get log time at TPL level <= TPL_CALLBACK.
+ //
+ ZeroMem (&LogTime, sizeof (LogTime));
+ if (EfiGetCurrentTpl() <= TPL_CALLBACK) {
+ gRT->GetTime (&LogTime, NULL);
+ }
+
+ //
+ // The Logging action is the critical section, so it is locked.
+ // The MTC asignment & update and logging must be an
+ // atomic operation, so use the lock.
+ //
+ Status = EfiAcquireLockOrFail (&Private->DataLock);
+ if (EFI_ERROR (Status)) {
+ //
+ // Reentrancy detected so exit!
+ //
+ return Status;
+ }
+
+ LogEntry = AllocatePool (TotalSize);
+
+ if (LogEntry == NULL) {
+ EfiReleaseLock (&Private->DataLock);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ ZeroMem (LogEntry, TotalSize);
+
+ Record = (EFI_DATA_RECORD_HEADER *) (LogEntry + 1);
+ Raw = (VOID *) (Record + 1);
+
+ //
+ // Build Standard Log Header
+ //
+ Record->Version = EFI_DATA_RECORD_HEADER_VERSION;
+ Record->HeaderSize = (UINT16) sizeof (EFI_DATA_RECORD_HEADER);
+ Record->RecordSize = RecordSize;
+ CopyMem (&Record->DataRecordGuid, DataRecordGuid, sizeof (EFI_GUID));
+ CopyMem (&Record->ProducerName, ProducerName, sizeof (EFI_GUID));
+ Record->DataRecordClass = DataRecordClass;
+
+ //
+ // Ensure LogMonotonicCount is not zero
+ //
+ Record->LogMonotonicCount = ++Private->GlobalMonotonicCount;
+
+ CopyMem (&Record->LogTime, &LogTime, sizeof (LogTime));
+
+ //
+ // Insert log into the internal linked list.
+ //
+ LogEntry->Signature = EFI_DATA_ENTRY_SIGNATURE;
+ LogEntry->Record = Record;
+ LogEntry->RecordSize = sizeof (EFI_DATA_ENTRY) + RawDataSize;
+ InsertTailList (&Private->DataListHead, &LogEntry->Link);
+
+ CopyMem (Raw, RawData, RawDataSize);
+
+ EfiReleaseLock (&Private->DataLock);
+
+ //
+ // Send Signal to all the filter drivers which are interested
+ // in the record's class and guid.
+ //
+ Head = &Private->FilterDriverListHead;
+ for (Link = GetFirstNode(Head); Link != Head; Link = GetNextNode(Head, Link)) {
+ FilterEntry = FILTER_ENTRY_FROM_LINK (Link);
+ if (((FilterEntry->ClassFilter & DataRecordClass) != 0) &&
+ (IsZeroGuid (&FilterEntry->FilterDataRecordGuid) ||
+ CompareGuid (&FilterEntry->FilterDataRecordGuid, DataRecordGuid))) {
+ gBS->SignalEvent (FilterEntry->Event);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Search the Head doubly linked list for the passed in MTC. Return the
+ matching element in Head and the MTC on the next entry.
+
+ @param Head Head of Data Log linked list.
+ @param ClassFilter Only match the MTC if it is in the same Class as the
+ ClassFilter.
+ @param PtrCurrentMTC On IN contians MTC to search for. On OUT contians next
+ MTC in the data log list or zero if at end of the list.
+
+ @retval EFI_DATA_LOG_ENTRY Return pointer to data log data from Head list.
+ @retval NULL If no data record exists.
+
+**/
+EFI_DATA_RECORD_HEADER *
+GetNextDataRecord (
+ IN LIST_ENTRY *Head,
+ IN UINT64 ClassFilter,
+ IN OUT UINT64 *PtrCurrentMTC
+ )
+
+{
+ EFI_DATA_ENTRY *LogEntry;
+ LIST_ENTRY *Link;
+ BOOLEAN ReturnFirstEntry;
+ EFI_DATA_RECORD_HEADER *Record;
+ EFI_DATA_ENTRY *NextLogEntry;
+
+ //
+ // If MonotonicCount == 0 just return the first one
+ //
+ ReturnFirstEntry = (BOOLEAN) (*PtrCurrentMTC == 0);
+
+ Record = NULL;
+ for (Link = GetFirstNode(Head); Link != Head; Link = GetNextNode(Head, Link)) {
+ LogEntry = DATA_ENTRY_FROM_LINK (Link);
+ if ((LogEntry->Record->DataRecordClass & ClassFilter) == 0) {
+ //
+ // Skip any entry that does not have the correct ClassFilter
+ //
+ continue;
+ }
+
+ if ((LogEntry->Record->LogMonotonicCount == *PtrCurrentMTC) || ReturnFirstEntry) {
+ //
+ // Return record to the user
+ //
+ Record = LogEntry->Record;
+
+ //
+ // Calculate the next MTC value. If there is no next entry set
+ // MTC to zero.
+ //
+ *PtrCurrentMTC = 0;
+ for (Link = GetNextNode(Head, Link); Link != Head; Link = GetNextNode(Head, Link)) {
+ NextLogEntry = DATA_ENTRY_FROM_LINK (Link);
+ if ((NextLogEntry->Record->DataRecordClass & ClassFilter) != 0) {
+ //
+ // Return the MTC of the next thing to search for if found
+ //
+ *PtrCurrentMTC = NextLogEntry->Record->LogMonotonicCount;
+ break;
+ }
+ }
+ //
+ // Record found exit loop and return
+ //
+ break;
+ }
+ }
+
+ return Record;
+}
+
+/**
+ Search the Head list for a EFI_DATA_HUB_FILTER_DRIVER member that
+ represents Event and return it.
+
+ @param Head Pointer to head of dual linked list of EFI_DATA_HUB_FILTER_DRIVER structures.
+ @param Event Event to be search for in the Head list.
+
+ @retval EFI_DATA_HUB_FILTER_DRIVER Returned if Event stored in the Head doubly linked list.
+ @retval NULL If Event is not in the list
+
+**/
+DATA_HUB_FILTER_DRIVER *
+FindFilterDriverByEvent (
+ IN LIST_ENTRY *Head,
+ IN EFI_EVENT Event
+ )
+{
+ DATA_HUB_FILTER_DRIVER *FilterEntry;
+ LIST_ENTRY *Link;
+
+ for (Link = GetFirstNode(Head); Link != Head; Link = GetNextNode(Head, Link)) {
+ FilterEntry = FILTER_ENTRY_FROM_LINK (Link);
+ if (FilterEntry->Event == Event) {
+ return FilterEntry;
+ }
+ }
+
+ return NULL;
+}
+
+/**
+
+ Get a previously logged data record and the MonotonicCount for the next
+ available Record. This allows all records or all records later
+ than a give MonotonicCount to be returned. If an optional FilterDriverEvent
+ is passed in with a MonotonicCout of zero return the first record
+ not yet read by the filter driver. If FilterDriverEvent is NULL and
+ MonotonicCount is zero return the first data record.
+
+ @param This Pointer to the EFI_DATA_HUB_PROTOCOL instance.
+ @param MonotonicCount Specifies the Record to return. On input, zero means
+ return the first record. On output, contains the next
+ record to available. Zero indicates no more records.
+ @param FilterDriverEvent If FilterDriverEvent is not passed in a MonotonicCount
+ of zero, it means to return the first data record.
+ If FilterDriverEvent is passed in, then a MonotonicCount
+ of zero means to return the first data not yet read by
+ FilterDriverEvent.
+ @param Record Returns a dynamically allocated memory buffer with a data
+ record that matches MonotonicCount.
+
+ @retval EFI_SUCCESS Data was returned in Record.
+ @retval EFI_INVALID_PARAMETER FilterDriverEvent was passed in but does not exist.
+ @retval EFI_NOT_FOUND MonotonicCount does not match any data record in the
+ system. If a MonotonicCount of zero was passed in, then
+ no data records exist in the system.
+ @retval EFI_OUT_OF_RESOURCES Record was not returned due to lack of system resources.
+
+**/
+EFI_STATUS
+EFIAPI
+DataHubGetNextRecord (
+ IN EFI_DATA_HUB_PROTOCOL *This,
+ IN OUT UINT64 *MonotonicCount,
+ IN EFI_EVENT *FilterDriverEvent, OPTIONAL
+ OUT EFI_DATA_RECORD_HEADER **Record
+ )
+{
+ DATA_HUB_INSTANCE *Private;
+ DATA_HUB_FILTER_DRIVER *FilterDriver;
+ UINT64 ClassFilter;
+
+ Private = DATA_HUB_INSTANCE_FROM_THIS (This);
+
+ FilterDriver = NULL;
+ ClassFilter = EFI_DATA_RECORD_CLASS_DEBUG |
+ EFI_DATA_RECORD_CLASS_ERROR |
+ EFI_DATA_RECORD_CLASS_DATA |
+ EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+
+ //
+ // If FilterDriverEvent is NULL, then return the next record
+ //
+ if (FilterDriverEvent == NULL) {
+ *Record = GetNextDataRecord (&Private->DataListHead, ClassFilter, MonotonicCount);
+ if (*Record == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ return EFI_SUCCESS;
+ }
+
+ //
+ // For events the beginning is the last unread record. This info is
+ // stored in the instance structure, so we must look up the event
+ // to get the data.
+ //
+ FilterDriver = FindFilterDriverByEvent (
+ &Private->FilterDriverListHead,
+ *FilterDriverEvent
+ );
+ if (FilterDriver == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ //
+ // Use the Class filter the event was created with.
+ //
+ ClassFilter = FilterDriver->ClassFilter;
+
+ //
+ // Retrieve the next record or the first record.
+ //
+ if (*MonotonicCount != 0 || FilterDriver->GetNextMonotonicCount == 0) {
+ *Record = GetNextDataRecord (&Private->DataListHead, ClassFilter, MonotonicCount);
+ if (*Record == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ if (*MonotonicCount != 0) {
+ //
+ // If this was not the last record then update the count associated with the filter
+ //
+ FilterDriver->GetNextMonotonicCount = *MonotonicCount;
+ } else {
+ //
+ // Save the MonotonicCount of the last record which has been read
+ //
+ FilterDriver->GetNextMonotonicCount = (*Record)->LogMonotonicCount;
+ }
+ return EFI_SUCCESS;
+ }
+
+ //
+ // This is a request to read the first record that has not been read yet.
+ // Set MonotoicCount to the last record successfuly read
+ //
+ *MonotonicCount = FilterDriver->GetNextMonotonicCount;
+
+ //
+ // Retrieve the last record successfuly read again, but do not return it since
+ // it has already been returned before.
+ //
+ *Record = GetNextDataRecord (&Private->DataListHead, ClassFilter, MonotonicCount);
+ if (*Record == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ if (*MonotonicCount != 0) {
+ //
+ // Update the count associated with the filter
+ //
+ FilterDriver->GetNextMonotonicCount = *MonotonicCount;
+
+ //
+ // Retrieve the record after the last record successfuly read
+ //
+ *Record = GetNextDataRecord (&Private->DataListHead, ClassFilter, MonotonicCount);
+ if (*Record == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function registers the data hub filter driver that is represented
+ by FilterEvent. Only one instance of each FilterEvent can be registered.
+ After the FilterEvent is registered, it will be signaled so it can sync
+ with data records that have been recorded prior to the FilterEvent being
+ registered.
+
+ @param This Pointer to The EFI_DATA_HUB_PROTOCOL instance.
+ @param FilterEvent The EFI_EVENT to signal whenever data that matches
+ FilterClass is logged in the system.
+ @param FilterTpl The maximum EFI_TPL at which FilterEvent can be
+ signaled. It is strongly recommended that you use the
+ lowest EFI_TPL possible.
+ @param FilterClass FilterEvent will be signaled whenever a bit in
+ EFI_DATA_RECORD_HEADER.DataRecordClass is also set in
+ FilterClass. If FilterClass is zero, no class-based
+ filtering will be performed.
+ @param FilterDataRecordGuid FilterEvent will be signaled whenever FilterDataRecordGuid
+ matches EFI_DATA_RECORD_HEADER.DataRecordGuid. If
+ FilterDataRecordGuid is NULL, then no GUID-based filtering
+ will be performed.
+
+ @retval EFI_SUCCESS The filter driver event was registered.
+ @retval EFI_ALREADY_STARTED FilterEvent was previously registered and cannot be
+ registered again.
+ @retval EFI_OUT_OF_RESOURCES The filter driver event was not registered due to lack of
+ system resources.
+
+**/
+EFI_STATUS
+EFIAPI
+DataHubRegisterFilterDriver (
+ IN EFI_DATA_HUB_PROTOCOL * This,
+ IN EFI_EVENT FilterEvent,
+ IN EFI_TPL FilterTpl,
+ IN UINT64 FilterClass,
+ IN EFI_GUID * FilterDataRecordGuid OPTIONAL
+ )
+
+{
+ DATA_HUB_INSTANCE *Private;
+ DATA_HUB_FILTER_DRIVER *FilterDriver;
+
+ Private = DATA_HUB_INSTANCE_FROM_THIS (This);
+
+ FilterDriver = (DATA_HUB_FILTER_DRIVER *) AllocateZeroPool (sizeof (DATA_HUB_FILTER_DRIVER));
+ if (FilterDriver == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Initialize filter driver info
+ //
+ FilterDriver->Signature = EFI_DATA_HUB_FILTER_DRIVER_SIGNATURE;
+ FilterDriver->Event = FilterEvent;
+ FilterDriver->Tpl = FilterTpl;
+ FilterDriver->GetNextMonotonicCount = 0;
+ if (FilterClass == 0) {
+ FilterDriver->ClassFilter = EFI_DATA_RECORD_CLASS_DEBUG |
+ EFI_DATA_RECORD_CLASS_ERROR |
+ EFI_DATA_RECORD_CLASS_DATA |
+ EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+ } else {
+ FilterDriver->ClassFilter = FilterClass;
+ }
+
+ if (FilterDataRecordGuid != NULL) {
+ CopyMem (&FilterDriver->FilterDataRecordGuid, FilterDataRecordGuid, sizeof (EFI_GUID));
+ }
+ //
+ // Search for duplicate entries
+ //
+ if (FindFilterDriverByEvent (&Private->FilterDriverListHead, FilterEvent) != NULL) {
+ FreePool (FilterDriver);
+ return EFI_ALREADY_STARTED;
+ }
+ //
+ // Make insertion an atomic operation with the lock.
+ //
+ EfiAcquireLock (&Private->DataLock);
+ InsertTailList (&Private->FilterDriverListHead, &FilterDriver->Link);
+ EfiReleaseLock (&Private->DataLock);
+
+ //
+ // Signal the Filter driver we just loaded so they will recieve all the
+ // previous history. If we did not signal here we would have to wait until
+ // the next data was logged to get the history. In a case where no next
+ // data was logged we would never get synced up.
+ //
+ gBS->SignalEvent (FilterEvent);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Remove a Filter Driver, so it no longer gets called when data
+ information is logged.
+
+ @param This Protocol instance structure
+
+ @param FilterEvent Event that represents a filter driver that is to be
+ Unregistered.
+
+ @retval EFI_SUCCESS If FilterEvent was unregistered
+ @retval EFI_NOT_FOUND If FilterEvent does not exist
+**/
+EFI_STATUS
+EFIAPI
+DataHubUnregisterFilterDriver (
+ IN EFI_DATA_HUB_PROTOCOL *This,
+ IN EFI_EVENT FilterEvent
+ )
+{
+ DATA_HUB_INSTANCE *Private;
+ DATA_HUB_FILTER_DRIVER *FilterDriver;
+
+ Private = DATA_HUB_INSTANCE_FROM_THIS (This);
+
+ //
+ // Search for duplicate entries
+ //
+ FilterDriver = FindFilterDriverByEvent (
+ &Private->FilterDriverListHead,
+ FilterEvent
+ );
+ if (FilterDriver == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Make removal an atomic operation with the lock
+ //
+ EfiAcquireLock (&Private->DataLock);
+ RemoveEntryList (&FilterDriver->Link);
+ EfiReleaseLock (&Private->DataLock);
+
+ return EFI_SUCCESS;
+}
+
+
+
+/**
+ Driver's Entry point routine that install Driver to produce Data Hub protocol.
+
+ @param ImageHandle Module's image handle
+ @param SystemTable Pointer of EFI_SYSTEM_TABLE
+
+ @retval EFI_SUCCESS Logging Hub protocol installed
+ @retval Other No protocol installed, unload driver.
+
+**/
+EFI_STATUS
+EFIAPI
+DataHubInstall (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HighMontonicCount;
+
+ mPrivateData.Signature = DATA_HUB_INSTANCE_SIGNATURE;
+ mPrivateData.DataHub.LogData = DataHubLogData;
+ mPrivateData.DataHub.GetNextRecord = DataHubGetNextRecord;
+ mPrivateData.DataHub.RegisterFilterDriver = DataHubRegisterFilterDriver;
+ mPrivateData.DataHub.UnregisterFilterDriver = DataHubUnregisterFilterDriver;
+
+ //
+ // Initialize Private Data in CORE_LOGGING_HUB_INSTANCE that is
+ // required by this protocol
+ //
+ InitializeListHead (&mPrivateData.DataListHead);
+ InitializeListHead (&mPrivateData.FilterDriverListHead);
+
+ EfiInitializeLock (&mPrivateData.DataLock, TPL_NOTIFY);
+
+ //
+ // Make sure we get a bigger MTC number on every boot!
+ //
+ Status = gRT->GetNextHighMonotonicCount (&HighMontonicCount);
+ if (EFI_ERROR (Status)) {
+ //
+ // if system service fails pick a sane value.
+ //
+ mPrivateData.GlobalMonotonicCount = 0;
+ } else {
+ mPrivateData.GlobalMonotonicCount = LShiftU64 ((UINT64) HighMontonicCount, 32);
+ }
+ //
+ // Make a new handle and install the protocol
+ //
+ mPrivateData.Handle = NULL;
+ Status = gBS->InstallProtocolInterface (
+ &mPrivateData.Handle,
+ &gEfiDataHubProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &mPrivateData.DataHub
+ );
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.h b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.h
new file mode 100644
index 0000000000..7770c438da
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHub.h
@@ -0,0 +1,129 @@
+/** @file
+ This code supports a the private implementation
+ of the Data Hub protocol
+
+Copyright (c) 2006 - 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.
+
+**/
+
+#ifndef _DATA_HUB_H_
+#define _DATA_HUB_H_
+
+
+#include <FrameworkDxe.h>
+
+#include <Protocol/DataHub.h>
+
+#include <Library/DebugLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+
+#define DATA_HUB_INSTANCE_SIGNATURE SIGNATURE_32 ('D', 'H', 'u', 'b')
+typedef struct {
+ UINT32 Signature;
+
+ EFI_HANDLE Handle;
+
+ //
+ // Produced protocol(s)
+ //
+ EFI_DATA_HUB_PROTOCOL DataHub;
+
+ //
+ // Private Data
+ //
+ //
+ // Updates to GlobalMonotonicCount, LogListHead, and FilterDriverListHead
+ // must be locked.
+ //
+ EFI_LOCK DataLock;
+
+ //
+ // Runing Monotonic Count to use for each error record.
+ // Increment AFTER use in an error record.
+ //
+ UINT64 GlobalMonotonicCount;
+
+ //
+ // List of EFI_DATA_ENTRY structures. This is the data log! The list
+ // must be in assending order of LogMonotonicCount.
+ //
+ LIST_ENTRY DataListHead;
+
+ //
+ // List of EFI_DATA_HUB_FILTER_DRIVER structures. Represents all
+ // the registered filter drivers.
+ //
+ LIST_ENTRY FilterDriverListHead;
+
+} DATA_HUB_INSTANCE;
+
+#define DATA_HUB_INSTANCE_FROM_THIS(this) CR (this, DATA_HUB_INSTANCE, DataHub, DATA_HUB_INSTANCE_SIGNATURE)
+
+//
+// Private data structure to contain the data log. One record per
+// structure. Head pointer to the list is the Log member of
+// EFI_DATA_ENTRY. Record is a copy of the data passed in.
+//
+#define EFI_DATA_ENTRY_SIGNATURE SIGNATURE_32 ('D', 'r', 'e', 'c')
+typedef struct {
+ UINT32 Signature;
+ LIST_ENTRY Link;
+
+ EFI_DATA_RECORD_HEADER *Record;
+
+ UINTN RecordSize;
+
+} EFI_DATA_ENTRY;
+
+#define DATA_ENTRY_FROM_LINK(link) CR (link, EFI_DATA_ENTRY, Link, EFI_DATA_ENTRY_SIGNATURE)
+
+//
+// Private data to contain the filter driver Event and it's
+// associated EFI_TPL.
+//
+#define EFI_DATA_HUB_FILTER_DRIVER_SIGNATURE SIGNATURE_32 ('D', 'h', 'F', 'd')
+
+typedef struct {
+ UINT32 Signature;
+ LIST_ENTRY Link;
+
+ //
+ // Store Filter Driver Event and Tpl level it can be Signaled at.
+ //
+ EFI_EVENT Event;
+ EFI_TPL Tpl;
+
+ //
+ // Monotonic count on the get next operation for Event.
+ // Zero indicates get next has not been called for this event yet.
+ //
+ UINT64 GetNextMonotonicCount;
+
+ //
+ // Filter driver will register what class filter should be used.
+ //
+ UINT64 ClassFilter;
+
+ //
+ // Filter driver will register what record guid filter should be used.
+ //
+ EFI_GUID FilterDataRecordGuid;
+
+} DATA_HUB_FILTER_DRIVER;
+
+#define FILTER_ENTRY_FROM_LINK(link) CR (link, DATA_HUB_FILTER_DRIVER, Link, EFI_DATA_HUB_FILTER_DRIVER_SIGNATURE)
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.inf b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.inf
new file mode 100644
index 0000000000..0b93f719bb
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.inf
@@ -0,0 +1,81 @@
+## @file
+# This driver initializes and installs the Data Hub protocol.
+#
+# The data hub is a volatile database that is intended as the major focus for the accumulation of
+# manageability data.T he hub is fed by "producers" with chunks of data in a defined format.
+# Consumers may then extract the data in temporal "log" order.As an example, progress codes might
+# be recorded in the data hub for future processing.Ot her data contributed to the data hub might
+# include, for example, statistics on enumerated items such as memory, add-in buses, and add-in
+# cards and data on errors encountered during boot (for example, the system did not boot off the
+# network because the cable was not plugged in).
+# Some classes of data have defined formats.For example, the amount of memory in the system is
+# reported in a standard format so that consumers can be written to extract the data.O ther data is
+# system specific.For example, additional detail on errors might be specific to the driver that
+# discovered the error.The consumer might be a driver that tabularizes data from the data hub,
+# providing a mechanism for the raw data to be made available to the OS for post-processing by
+# OS-based applications.
+# The intent of the data hub is for drivers that enumerate and configure parts of the system to report
+# their discoveries to the data hub.This data can then be extracted by other drivers that report those
+# discoveries using standard manageability interfaces such as SMBIOS and Intelligent Platform
+# Management Interface (IPMI).The alternative to a data-hub-like architecture is to require all
+# drivers to be aware of all reporting formats.
+# For more information, please ref http://www.intel.com/technology/framework/
+#
+# Copyright (c) 2006 - 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.
+#
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DataHubDxe
+ MODULE_UNI_FILE = DataHubDxe.uni
+ FILE_GUID = 53BCC14F-C24F-434C-B294-8ED2D4CC1860
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DataHubInstall
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ DataHub.h
+ DataHub.c
+
+
+[Packages]
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+
+
+[LibraryClasses]
+ UefiRuntimeServicesTableLib
+ UefiBootServicesTableLib
+ MemoryAllocationLib
+ BaseMemoryLib
+ BaseLib
+ UefiLib
+ UefiDriverEntryPoint
+ DebugLib
+
+
+[Protocols]
+ gEfiDataHubProtocolGuid ## PRODUCES
+
+
+[Depex]
+ TRUE
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ DataHubDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.uni b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.uni
new file mode 100644
index 0000000000..8f1c2f53f7
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxe.uni
@@ -0,0 +1,39 @@
+// /** @file
+// This driver initializes and installs the Data Hub protocol.
+//
+// The data hub is a volatile database that is intended as the major focus for the accumulation of
+// manageability data.T he hub is fed by "producers" with chunks of data in a defined format.
+// Consumers may then extract the data in temporal "log" order.As an example, progress codes might
+// be recorded in the data hub for future processing.Ot her data contributed to the data hub might
+// include, for example, statistics on enumerated items such as memory, add-in buses, and add-in
+// cards and data on errors encountered during boot (for example, the system did not boot off the
+// network because the cable was not plugged in).
+// Some classes of data have defined formats.For example, the amount of memory in the system is
+// reported in a standard format so that consumers can be written to extract the data.O ther data is
+// system specific.For example, additional detail on errors might be specific to the driver that
+// discovered the error.The consumer might be a driver that tabularizes data from the data hub,
+// providing a mechanism for the raw data to be made available to the OS for post-processing by
+// OS-based applications.
+// The intent of the data hub is for drivers that enumerate and configure parts of the system to report
+// their discoveries to the data hub.This data can then be extracted by other drivers that report those
+// discoveries using standard manageability interfaces such as SMBIOS and Intelligent Platform
+// Management Interface (IPMI).The alternative to a data-hub-like architecture is to require all
+// drivers to be aware of all reporting formats.
+// For more information, please ref http://www.intel.com/technology/framework/
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Initializes and installs the Data Hub protocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The data hub is a volatile database that is intended as the major focus for the accumulation of manageability data. The hub is fed by \"producers\" with chunks of data in a defined format. Consumers may then extract the data in a temporal \"log\" order. As an example, progress codes might be recorded in the data hub for future processing. For example, other data contributed to the data hub might include, statistics on enumerated items such as memory, add-in buses, and add-in cards, and data on errors encountered during boot (such as, the system did not boot off the network because the cable was not plugged in). Some classes of data have defined formats. For example, the amount of memory in the system is reported in a standard format so that consumers can be written to extract the data. Other data is system specific. For example, additional detail on errors might be specific to the driver that discovered the error. The consumer might be a driver that tabularizes data from the data hub, providing a mechanism for the raw data to be made available to the OS for post-processing by OS-based applications. The intent of the data hub is for drivers that enumerate and configure parts of the system to report their discoveries to the data hub. This data can then be extracted by other drivers that report those discoveries using standard manageability interfaces such as SMBIOS and Intelligent Platform Management Interface (IPMI). The alternative to a data-hub-like architecture is to require all drivers to be aware of all reporting formats. For more information, refer to http://www.intel.com/technology/framework/ ."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxeExtra.uni
new file mode 100644
index 0000000000..8c973db27a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubDxe/DataHubDxeExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// DataHubDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Data Hub DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErr.c b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErr.c
new file mode 100644
index 0000000000..f64c5411db
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErr.c
@@ -0,0 +1,151 @@
+/** @file
+ Data Hub filter driver that takes DEBUG () info from Data Hub and writes it
+ to StdErr if it exists.
+
+Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <FrameworkDxe.h>
+#include <Guid/DataHubStatusCodeRecord.h>
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/StatusCodeDataTypeDebug.h>
+#include <Protocol/DataHub.h>
+#include <Protocol/SimpleTextOut.h>
+
+#include <Library/DebugLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+EFI_DATA_HUB_PROTOCOL *mDataHub = NULL;
+
+EFI_EVENT mDataHubStdErrEvent;
+
+/**
+ Event handler registered with the Data Hub to parse EFI_DEBUG_CODE. This
+ handler reads the Data Hub and sends any DEBUG info to StdErr.
+
+ @param Event The event that occured, not used
+ @param Context DataHub Protocol Pointer
+**/
+VOID
+EFIAPI
+DataHubStdErrEventHandler (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+ EFI_DATA_HUB_PROTOCOL *DataHub;
+ EFI_DATA_RECORD_HEADER *Record;
+ DATA_HUB_STATUS_CODE_DATA_RECORD *DataRecord;
+ UINT64 Mtc;
+ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *Sto;
+ INT32 OldAttribute;
+
+ DataHub = (EFI_DATA_HUB_PROTOCOL *) Context;
+
+ //
+ // If StdErr is not yet initialized just return a DEBUG print in the BDS
+ // after consoles are connect will make sure data gets flushed properly
+ // when StdErr is available.
+ //
+ if (gST == NULL) {
+ return ;
+ }
+
+ if (gST->StdErr == NULL) {
+ return ;
+ }
+
+ //
+ // Mtc of zero means return the next record that has not been read by the
+ // event handler.
+ //
+ Mtc = 0;
+ do {
+ Status = DataHub->GetNextRecord (DataHub, &Mtc, &mDataHubStdErrEvent, &Record);
+ if (!EFI_ERROR (Status)) {
+ if (CompareGuid (&Record->DataRecordGuid, &gEfiDataHubStatusCodeRecordGuid)) {
+ DataRecord = (DATA_HUB_STATUS_CODE_DATA_RECORD *) (((CHAR8 *) Record) + Record->HeaderSize);
+
+ if (DataRecord->Data.HeaderSize > 0) {
+ if (CompareGuid (&DataRecord->Data.Type, &gEfiStatusCodeDataTypeDebugGuid)) {
+ //
+ // If the Data record is from a DEBUG () then send it to Standard Error
+ //
+ Sto = gST->StdErr;
+ OldAttribute = Sto->Mode->Attribute;
+ Sto->SetAttribute (Sto, EFI_TEXT_ATTR (EFI_MAGENTA, EFI_BLACK));
+ Sto->OutputString (Sto, (CHAR16 *) (DataRecord + 1));
+ Sto->SetAttribute (Sto, OldAttribute);
+ }
+ }
+ }
+ }
+ } while ((Mtc != 0) && !EFI_ERROR (Status));
+}
+
+/**
+ Register an event handler with the Data Hub to parse EFI_DEBUG_CODE. This
+ handler reads the Data Hub and sends any DEBUG info to StdErr.
+
+ @param ImageHandle Image handle of this driver.
+ @param SystemTable Pointer to EFI system table.
+
+ @retval EFI_SUCCESS The event handler was registered.
+ @retval EFI_OUT_OF_RESOURCES The event hadler was not registered due to lack of system resources.
+**/
+EFI_STATUS
+EFIAPI
+DataHubStdErrInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ UINT64 DataClass;
+
+ gBS->LocateProtocol (&gEfiDataHubProtocolGuid, NULL, (VOID **) &mDataHub);
+ //
+ // Should never fail due to Depex grammer.
+ //
+ ASSERT (mDataHub != NULL);
+
+ //
+ // Create an event and register it with the filter driver
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ DataHubStdErrEventHandler,
+ mDataHub,
+ &mDataHubStdErrEvent
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ DataClass = EFI_DATA_RECORD_CLASS_DEBUG | EFI_DATA_RECORD_CLASS_ERROR;
+ Status = mDataHub->RegisterFilterDriver (
+ mDataHub,
+ mDataHubStdErrEvent,
+ TPL_CALLBACK,
+ DataClass,
+ NULL
+ );
+ if (EFI_ERROR (Status)) {
+ gBS->CloseEvent (mDataHubStdErrEvent);
+ }
+
+ return Status;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.inf b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.inf
new file mode 100644
index 0000000000..f9dede864c
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.inf
@@ -0,0 +1,57 @@
+## @file
+# This driver takes DEBUG info from Data Hub and writes it to StdErr if it exists.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DataHubStdErrDxe
+ MODULE_UNI_FILE = DataHubStdErrDxe.uni
+ FILE_GUID = CA515306-00CE-4032-874E-11B755FF6866
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DataHubStdErrInitialize
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ DataHubStdErr.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ UefiBootServicesTableLib
+ BaseMemoryLib
+ UefiDriverEntryPoint
+ DebugLib
+
+[Guids]
+ gEfiStatusCodeDataTypeDebugGuid ## SOMETIMES_CONSUMES ## UNDEFINED # DataRecord Date Type
+ gEfiDataHubStatusCodeRecordGuid ## SOMETIMES_CONSUMES ## UNDEFINED # DataRecordGuid
+
+
+[Protocols]
+ gEfiDataHubProtocolGuid ## CONSUMES
+
+[Depex]
+ gEfiDataHubProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ DataHubStdErrDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.uni b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.uni
new file mode 100644
index 0000000000..23e4ef9a15
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxe.uni
@@ -0,0 +1,21 @@
+// /** @file
+// This driver takes DEBUG info from Data Hub and writes it to StdErr if it exists.
+//
+// This driver takes DEBUG info from a Data Hub and writes it to StdErr if it exists.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Takes DEBUG information from a Data Hub; writes it to StdErr if it exists"
+
+#string STR_MODULE_DESCRIPTION #language en-US "This driver takes DEBUG info from a Data Hub and writes it to StdErr if it exists."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxeExtra.uni
new file mode 100644
index 0000000000..487291b831
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/DataHubStdErrDxe/DataHubStdErrDxeExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// DataHubStdErrDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Data Hub stderr DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/Ffs.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/Ffs.c
new file mode 100644
index 0000000000..12508b4335
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/Ffs.c
@@ -0,0 +1,608 @@
+/** @file
+ FFS file access utilities.
+
+ Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "FwVolDriver.h"
+
+#define PHYSICAL_ADDRESS_TO_POINTER(Address) ((VOID *) ((UINTN) Address))
+
+/**
+ Set File State in the FfsHeader.
+
+ @param State File state to be set into FFS header.
+ @param FfsHeader Points to the FFS file header
+
+**/
+VOID
+SetFileState (
+ IN UINT8 State,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ //
+ // Set File State in the FfsHeader
+ //
+ FfsHeader->State = (EFI_FFS_FILE_STATE) (FfsHeader->State ^ State);
+ return ;
+}
+
+/**
+ Get the FFS file state by checking the highest bit set in the header's state field.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param FfsHeader Points to the FFS file header
+
+ @return FFS File state
+
+**/
+EFI_FFS_FILE_STATE
+GetFileState (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ EFI_FFS_FILE_STATE FileState;
+ UINT8 HighestBit;
+
+ FileState = FfsHeader->State;
+
+ if (ErasePolarity != 0) {
+ FileState = (EFI_FFS_FILE_STATE)~FileState;
+ }
+
+ HighestBit = 0x80;
+ while (HighestBit != 0 && ((HighestBit & FileState) == 0)) {
+ HighestBit >>= 1;
+ }
+
+ return (EFI_FFS_FILE_STATE) HighestBit;
+}
+
+/**
+ Convert the Buffer Address to LBA Entry Address.
+
+ @param FvDevice Cached FvDevice
+ @param BufferAddress Address of Buffer
+ @param LbaListEntry Pointer to the got LBA entry that contains the address.
+
+ @retval EFI_NOT_FOUND Buffer address is out of FvDevice.
+ @retval EFI_SUCCESS LBA entry is found for Buffer address.
+
+**/
+EFI_STATUS
+Buffer2LbaEntry (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_PHYSICAL_ADDRESS BufferAddress,
+ OUT LBA_ENTRY **LbaListEntry
+ )
+{
+ LBA_ENTRY *LbaEntry;
+ LIST_ENTRY *Link;
+
+ Link = FvDevice->LbaHeader.ForwardLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+
+ //
+ // Locate LBA which contains the address
+ //
+ while (&LbaEntry->Link != &FvDevice->LbaHeader) {
+ if ((EFI_PHYSICAL_ADDRESS) (UINTN) (LbaEntry->StartingAddress) > BufferAddress) {
+ break;
+ }
+
+ Link = LbaEntry->Link.ForwardLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+ }
+
+ if (&LbaEntry->Link == &FvDevice->LbaHeader) {
+ return EFI_NOT_FOUND;
+ }
+
+ Link = LbaEntry->Link.BackLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+
+ if (&LbaEntry->Link == &FvDevice->LbaHeader) {
+ return EFI_NOT_FOUND;
+ }
+
+ *LbaListEntry = LbaEntry;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Convert the Buffer Address to LBA Address & Offset.
+
+ @param FvDevice Cached FvDevice
+ @param BufferAddress Address of Buffer
+ @param Lba Pointer to the gob Lba value
+ @param Offset Pointer to the got Offset
+
+ @retval EFI_NOT_FOUND Buffer address is out of FvDevice.
+ @retval EFI_SUCCESS LBA and Offset is found for Buffer address.
+
+**/
+EFI_STATUS
+Buffer2Lba (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_PHYSICAL_ADDRESS BufferAddress,
+ OUT EFI_LBA *Lba,
+ OUT UINTN *Offset
+ )
+{
+ LBA_ENTRY *LbaEntry;
+ EFI_STATUS Status;
+
+ LbaEntry = NULL;
+
+ Status = Buffer2LbaEntry (
+ FvDevice,
+ BufferAddress,
+ &LbaEntry
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ *Lba = LbaEntry->LbaIndex;
+ *Offset = (UINTN) BufferAddress - (UINTN) LbaEntry->StartingAddress;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Check if a block of buffer is erased.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param Buffer The buffer to be checked
+ @param BufferSize Size of the buffer in bytes
+
+ @retval TRUE The block of buffer is erased
+ @retval FALSE The block of buffer is not erased
+
+**/
+BOOLEAN
+IsBufferErased (
+ IN UINT8 ErasePolarity,
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize
+ )
+{
+ UINTN Count;
+ UINT8 EraseByte;
+
+ if (ErasePolarity == 1) {
+ EraseByte = 0xFF;
+ } else {
+ EraseByte = 0;
+ }
+
+ for (Count = 0; Count < BufferSize; Count++) {
+ if (Buffer[Count] != EraseByte) {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+/**
+ Verify checksum of the firmware volume header.
+
+ @param FvHeader Points to the firmware volume header to be checked
+
+ @retval TRUE Checksum verification passed
+ @retval FALSE Checksum verification failed
+
+**/
+BOOLEAN
+VerifyFvHeaderChecksum (
+ IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader
+ )
+{
+ UINT16 Checksum;
+
+ Checksum = CalculateSum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength);
+
+ if (Checksum == 0) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Verify checksum of the FFS file header.
+
+ @param FfsHeader Points to the FFS file header to be checked
+
+ @retval TRUE Checksum verification passed
+ @retval FALSE Checksum verification failed
+
+**/
+BOOLEAN
+VerifyHeaderChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ UINT8 HeaderChecksum;
+
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ HeaderChecksum = CalculateSum8 ((UINT8 *) FfsHeader, sizeof (EFI_FFS_FILE_HEADER2));
+ } else {
+ HeaderChecksum = CalculateSum8 ((UINT8 *) FfsHeader, sizeof (EFI_FFS_FILE_HEADER));
+ }
+ HeaderChecksum = (UINT8) (HeaderChecksum - FfsHeader->State - FfsHeader->IntegrityCheck.Checksum.File);
+
+ if (HeaderChecksum == 0) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Verify checksum of the FFS file data.
+
+ @param FfsHeader Points to the FFS file header to be checked
+
+ @retval TRUE Checksum verification passed
+ @retval FALSE Checksum verification failed
+
+**/
+BOOLEAN
+VerifyFileChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ UINT8 FileChecksum;
+ EFI_FV_FILE_ATTRIBUTES Attributes;
+
+ Attributes = FfsHeader->Attributes;
+
+ if ((Attributes & FFS_ATTRIB_CHECKSUM) != 0) {
+
+ //
+ // Check checksum of FFS data
+ //
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ FileChecksum = CalculateSum8 ((UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER2), FFS_FILE2_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER2));
+ } else {
+ FileChecksum = CalculateSum8 ((UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER), FFS_FILE_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER));
+ }
+ FileChecksum = (UINT8) (FileChecksum + FfsHeader->IntegrityCheck.Checksum.File);
+
+ if (FileChecksum == 0) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+
+ } else {
+
+ if (FfsHeader->IntegrityCheck.Checksum.File != FFS_FIXED_CHECKSUM) {
+ return FALSE;
+ } else {
+ return TRUE;
+ }
+ }
+
+}
+
+/**
+ Check if it's a valid FFS file header.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param FfsHeader Points to the FFS file header to be checked
+
+ @retval TRUE Valid FFS file header
+ @retval FALSE Invalid FFS file header
+
+**/
+BOOLEAN
+IsValidFFSHeader (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ EFI_FFS_FILE_STATE FileState;
+
+ //
+ // Check if it is a free space
+ //
+ if (IsBufferErased (
+ ErasePolarity,
+ (UINT8 *) FfsHeader,
+ sizeof (EFI_FFS_FILE_HEADER)
+ )) {
+ return FALSE;
+ }
+
+ FileState = GetFileState (ErasePolarity, FfsHeader);
+
+ switch (FileState) {
+ case EFI_FILE_HEADER_CONSTRUCTION:
+ //
+ // fall through
+ //
+ case EFI_FILE_HEADER_INVALID:
+ return FALSE;
+
+ case EFI_FILE_HEADER_VALID:
+ //
+ // fall through
+ //
+ case EFI_FILE_DATA_VALID:
+ //
+ // fall through
+ //
+ case EFI_FILE_MARKED_FOR_UPDATE:
+ //
+ // fall through
+ //
+ case EFI_FILE_DELETED:
+ //
+ // Here we need to verify header checksum
+ //
+ if (!VerifyHeaderChecksum (FfsHeader)) {
+ return FALSE;
+ }
+ break;
+
+ default:
+ //
+ // return
+ //
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/**
+ Get next possible of Firmware File System Header.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param FfsHeader Points to the FFS file header to be skipped.
+
+ @return Pointer to next FFS header.
+
+**/
+EFI_PHYSICAL_ADDRESS
+GetNextPossibleFileHeader (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ UINT32 FileLength;
+ UINT32 SkipLength;
+
+ if (!IsValidFFSHeader (ErasePolarity, FfsHeader)) {
+ //
+ // Skip this header
+ //
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ return (EFI_PHYSICAL_ADDRESS) (UINTN) FfsHeader + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ return (EFI_PHYSICAL_ADDRESS) (UINTN) FfsHeader + sizeof (EFI_FFS_FILE_HEADER);
+ }
+ }
+
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ FileLength = FFS_FILE2_SIZE (FfsHeader);
+ } else {
+ FileLength = FFS_FILE_SIZE (FfsHeader);
+ }
+
+ //
+ // Since FileLength is not multiple of 8, we need skip some bytes
+ // to get next possible header
+ //
+ SkipLength = FileLength;
+ while ((SkipLength & 0x07) != 0) {
+ SkipLength++;
+ }
+
+ return (EFI_PHYSICAL_ADDRESS) (UINTN) FfsHeader + SkipLength;
+}
+
+/**
+ Search FFS file with the same FFS name in FV Cache.
+
+ @param FvDevice Cached FV image.
+ @param FfsHeader Points to the FFS file header to be skipped.
+ @param StateBit FFS file state bit to be checked.
+
+ @return Pointer to next found FFS header. NULL will return if no found.
+
+**/
+EFI_FFS_FILE_HEADER *
+DuplicateFileExist (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_FFS_FILE_HEADER *FfsHeader,
+ IN EFI_FFS_FILE_STATE StateBit
+ )
+{
+ UINT8 *Ptr;
+ EFI_FFS_FILE_HEADER *NextFfsFile;
+
+ //
+ // Search duplicate file, not from the beginning of FV,
+ // just search the next ocurrence of this file
+ //
+ NextFfsFile = FfsHeader;
+
+ do {
+ Ptr = (UINT8 *) PHYSICAL_ADDRESS_TO_POINTER (
+ GetNextPossibleFileHeader (FvDevice->ErasePolarity,
+ NextFfsFile)
+ );
+ NextFfsFile = (EFI_FFS_FILE_HEADER *) Ptr;
+
+ if ((UINT8 *) PHYSICAL_ADDRESS_TO_POINTER (FvDevice->CachedFv) + FvDevice->FwVolHeader->FvLength - Ptr <
+ sizeof (EFI_FFS_FILE_HEADER)
+ ) {
+ break;
+ }
+
+ if (!IsValidFFSHeader (FvDevice->ErasePolarity, NextFfsFile)) {
+ continue;
+ }
+
+ if (!VerifyFileChecksum (NextFfsFile)) {
+ continue;
+ }
+
+ if (CompareGuid (&NextFfsFile->Name, &FfsHeader->Name)) {
+ if (GetFileState (FvDevice->ErasePolarity, NextFfsFile) == StateBit) {
+ return NextFfsFile;
+ }
+ }
+ } while (Ptr < (UINT8 *) PHYSICAL_ADDRESS_TO_POINTER (FvDevice->CachedFv) + FvDevice->FwVolHeader->FvLength);
+
+ return NULL;
+}
+
+/**
+ Change FFS file header state and write to FV.
+
+ @param FvDevice Cached FV image.
+ @param FfsHeader Points to the FFS file header to be updated.
+ @param State FFS file state to be set.
+
+ @retval EFI_SUCCESS File state is writen into FV.
+ @retval others File state can't be writen into FV.
+
+**/
+EFI_STATUS
+UpdateHeaderBit (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_FFS_FILE_HEADER *FfsHeader,
+ IN EFI_FFS_FILE_STATE State
+ )
+{
+ EFI_STATUS Status;
+ EFI_LBA Lba;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+
+ Lba = 0;
+ Offset = 0;
+
+ SetFileState (State, FfsHeader);
+
+ Buffer2Lba (
+ FvDevice,
+ (EFI_PHYSICAL_ADDRESS) (UINTN) (&FfsHeader->State),
+ &Lba,
+ &Offset
+ );
+ //
+ // Write the state byte into FV
+ //
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvDevice->Fvb->Write (
+ FvDevice->Fvb,
+ Lba,
+ Offset,
+ &NumBytesWritten,
+ &FfsHeader->State
+ );
+ return Status;
+}
+
+/**
+ Check if it's a valid FFS file.
+ Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first.
+
+ @param FvDevice Cached FV image.
+ @param FfsHeader Points to the FFS file to be checked
+
+ @retval TRUE Valid FFS file
+ @retval FALSE Invalid FFS file
+
+**/
+BOOLEAN
+IsValidFFSFile (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ EFI_FFS_FILE_STATE FileState;
+ UINT8 ErasePolarity;
+
+ ErasePolarity = FvDevice->ErasePolarity;
+
+ FileState = GetFileState (ErasePolarity, FfsHeader);
+
+ switch (FileState) {
+ case EFI_FILE_DATA_VALID:
+ if (!VerifyFileChecksum (FfsHeader)) {
+ return FALSE;
+ }
+
+ if (FfsHeader->Type == EFI_FV_FILETYPE_FFS_PAD) {
+ break;
+ }
+ //
+ // Check if there is another duplicated file with the EFI_FILE_DATA_VALID
+ //
+ if (DuplicateFileExist (FvDevice, FfsHeader, EFI_FILE_DATA_VALID) != NULL) {
+ return FALSE;
+ }
+
+ break;
+
+ case EFI_FILE_MARKED_FOR_UPDATE:
+ if (!VerifyFileChecksum (FfsHeader)) {
+ return FALSE;
+ }
+
+ if (FfsHeader->Type == EFI_FV_FILETYPE_FFS_PAD) {
+ //
+ // since its data area is not unperturbed, it cannot be reclaimed,
+ // marked it as deleted
+ //
+ UpdateHeaderBit (FvDevice, FfsHeader, EFI_FILE_DELETED);
+ return TRUE;
+
+ } else if (DuplicateFileExist (FvDevice, FfsHeader, EFI_FILE_DATA_VALID) != NULL) {
+ //
+ // Here the found file is more recent than this file,
+ // mark it as deleted
+ //
+ UpdateHeaderBit (FvDevice, FfsHeader, EFI_FILE_DELETED);
+ return TRUE;
+
+ } else {
+ return TRUE;
+ }
+
+ break;
+
+ case EFI_FILE_DELETED:
+ if (!VerifyFileChecksum (FfsHeader)) {
+ return FALSE;
+ }
+
+ break;
+
+ default:
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwPadFile.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwPadFile.c
new file mode 100644
index 0000000000..8d53d879bd
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwPadFile.c
@@ -0,0 +1,1228 @@
+/** @file
+ Implements functions to pad firmware file.
+
+ Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "FwVolDriver.h"
+
+/**
+ Calculate the checksum for a PAD file.
+
+ @param PadFileHeader The Pad File to be caculeted the checksum.
+
+**/
+VOID
+SetPadFileChecksum (
+ IN EFI_FFS_FILE_HEADER *PadFileHeader
+ )
+{
+ if ((PadFileHeader->Attributes & FFS_ATTRIB_CHECKSUM) != 0) {
+
+ if (IS_FFS_FILE2 (PadFileHeader)) {
+ //
+ // Calculate checksum of Pad File Data
+ //
+ PadFileHeader->IntegrityCheck.Checksum.File =
+ CalculateCheckSum8 ((UINT8 *) PadFileHeader + sizeof (EFI_FFS_FILE_HEADER2), FFS_FILE2_SIZE (PadFileHeader) - sizeof (EFI_FFS_FILE_HEADER2));
+
+ } else {
+ //
+ // Calculate checksum of Pad File Data
+ //
+ PadFileHeader->IntegrityCheck.Checksum.File =
+ CalculateCheckSum8 ((UINT8 *) PadFileHeader + sizeof (EFI_FFS_FILE_HEADER), FFS_FILE_SIZE (PadFileHeader) - sizeof (EFI_FFS_FILE_HEADER));
+ }
+
+ } else {
+
+ PadFileHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
+
+ }
+
+ return ;
+}
+
+/**
+ Create a PAD File in the Free Space.
+
+ @param FvDevice Firmware Volume Device.
+ @param FreeSpaceEntry Indicating in which Free Space(Cache) the Pad file will be inserted.
+ @param Size Pad file Size, not include the header.
+ @param PadFileEntry The Ffs File Entry that points to this Pad File.
+
+ @retval EFI_SUCCESS Successfully create a PAD file.
+ @retval EFI_OUT_OF_RESOURCES No enough free space to create a PAD file.
+ @retval EFI_INVALID_PARAMETER Size is not 8 byte alignment.
+ @retval EFI_DEVICE_ERROR Free space is not erased.
+**/
+EFI_STATUS
+FvCreatePadFileInFreeSpace (
+ IN FV_DEVICE *FvDevice,
+ IN FREE_SPACE_ENTRY *FreeSpaceEntry,
+ IN UINTN Size,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ )
+{
+ EFI_STATUS Status;
+ EFI_FFS_FILE_HEADER *PadFileHeader;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+ UINTN StateOffset;
+ UINT8 *StartPos;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ UINTN HeaderSize;
+ UINTN FileSize;
+
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ FileSize = Size + HeaderSize;
+ if (FileSize > 0x00FFFFFF) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ FileSize = Size + HeaderSize;
+ }
+
+ if (FreeSpaceEntry->Length < FileSize) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ if ((Size & 0x07) != 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ StartPos = FreeSpaceEntry->StartingAddress;
+
+ //
+ // First double check the space
+ //
+ if (!IsBufferErased (
+ FvDevice->ErasePolarity,
+ StartPos,
+ FileSize
+ )) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) StartPos;
+
+ //
+ // Create File Step 1
+ //
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, PadFileHeader);
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &PadFileHeader->State - (UINT8 *) PadFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &PadFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, PadFileHeader);
+ return Status;
+ }
+ //
+ // Update Free Space Entry, since header is allocated
+ //
+ FreeSpaceEntry->Length -= HeaderSize;
+ FreeSpaceEntry->StartingAddress += HeaderSize;
+
+ //
+ // Fill File Name Guid, here we assign a NULL-GUID to Pad files
+ //
+ ZeroMem (&PadFileHeader->Name, sizeof (EFI_GUID));
+
+ //
+ // Fill File Type, checksum(0), Attributes(0), Size
+ //
+ PadFileHeader->Type = EFI_FV_FILETYPE_FFS_PAD;
+ PadFileHeader->Attributes = 0;
+ if ((FileSize) > 0x00FFFFFF) {
+ ((EFI_FFS_FILE_HEADER2 *) PadFileHeader)->ExtendedSize = (UINT32) FileSize;
+ *(UINT32 *) PadFileHeader->Size &= 0xFF000000;
+ PadFileHeader->Attributes |= FFS_ATTRIB_LARGE_FILE;
+ } else {
+ *(UINT32 *) PadFileHeader->Size &= 0xFF000000;
+ *(UINT32 *) PadFileHeader->Size |= FileSize;
+ }
+
+ SetHeaderChecksum (PadFileHeader);
+ SetPadFileChecksum (PadFileHeader);
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+
+ NumBytesWritten = HeaderSize;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ (UINT8 *) PadFileHeader
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Step 2, then Mark header valid, since no data write,
+ // mark the data valid at the same time.
+ //
+ SetFileState (EFI_FILE_HEADER_VALID, PadFileHeader);
+ SetFileState (EFI_FILE_DATA_VALID, PadFileHeader);
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &PadFileHeader->State - (UINT8 *) PadFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &PadFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ SetFileState (EFI_FILE_HEADER_VALID, PadFileHeader);
+ SetFileState (EFI_FILE_DATA_VALID, PadFileHeader);
+ return Status;
+ }
+ //
+ // Update Free Space Entry, since header is allocated
+ //
+ FreeSpaceEntry->Length -= Size;
+ FreeSpaceEntry->StartingAddress += Size;
+
+ //
+ // If successfully, insert an FfsFileEntry at the end of ffs file list
+ //
+ FfsFileEntry = AllocateZeroPool (sizeof (FFS_FILE_LIST_ENTRY));
+ ASSERT (FfsFileEntry != NULL);
+
+ FfsFileEntry->FfsHeader = (UINT8 *) (UINTN) StartPos;
+ InsertTailList (&FvDevice->FfsFileListHeader, &FfsFileEntry->Link);
+
+ *PadFileEntry = FfsFileEntry;
+ FvDevice->CurrentFfsFile = FfsFileEntry;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Fill pad file header within firmware cache.
+
+ @param PadFileHeader The start of the Pad File Buffer.
+ @param PadFileLength The length of the pad file including the header.
+
+**/
+VOID
+FvFillPadFile (
+ IN EFI_FFS_FILE_HEADER *PadFileHeader,
+ IN UINTN PadFileLength
+ )
+{
+ //
+ // Fill File Name Guid, here we assign a NULL-GUID to Pad files
+ //
+ ZeroMem (&PadFileHeader->Name, sizeof (EFI_GUID));
+
+ //
+ // Fill File Type, checksum(0), Attributes(0), Size
+ //
+ PadFileHeader->Type = EFI_FV_FILETYPE_FFS_PAD;
+ PadFileHeader->Attributes = 0;
+ if (PadFileLength > 0x00FFFFFF) {
+ ((EFI_FFS_FILE_HEADER2 *) PadFileHeader)->ExtendedSize = (UINT32) PadFileLength;
+ *(UINT32 *) PadFileHeader->Size &= 0xFF000000;
+ PadFileHeader->Attributes |= FFS_ATTRIB_LARGE_FILE;
+ } else {
+ *(UINT32 *) PadFileHeader->Size &= 0xFF000000;
+ *(UINT32 *) PadFileHeader->Size |= PadFileLength;
+ }
+
+ SetHeaderChecksum (PadFileHeader);
+ SetPadFileChecksum (PadFileHeader);
+
+ //
+ // Set File State to 0x00000111
+ //
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, PadFileHeader);
+ SetFileState (EFI_FILE_HEADER_VALID, PadFileHeader);
+ SetFileState (EFI_FILE_DATA_VALID, PadFileHeader);
+
+ return ;
+}
+
+/**
+ Create entire FFS file.
+
+ @param FileHeader Starting Address of a Buffer that hold the FFS File image.
+ @param FfsFileBuffer The source buffer that contains the File Data.
+ @param BufferSize The length of FfsFileBuffer.
+ @param ActualFileSize Size of FFS file.
+ @param FileName The Guid of Ffs File.
+ @param FileType The type of the written Ffs File.
+ @param FileAttributes The attributes of the written Ffs File.
+
+ @retval EFI_INVALID_PARAMETER File type is not valid.
+ @retval EFI_SUCCESS FFS file is successfully created.
+
+**/
+EFI_STATUS
+FvFillFfsFile (
+ OUT EFI_FFS_FILE_HEADER *FileHeader,
+ IN UINT8 *FfsFileBuffer,
+ IN UINTN BufferSize,
+ IN UINTN ActualFileSize,
+ IN EFI_GUID *FileName,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ )
+{
+ EFI_FFS_FILE_ATTRIBUTES TmpFileAttribute;
+ EFI_FFS_FILE_HEADER *TmpFileHeader;
+
+ //
+ // File Type value 0x0E~0xE0 are reserved
+ //
+ if ((FileType > EFI_FV_FILETYPE_SMM_CORE) && (FileType < 0xE0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ TmpFileHeader = (EFI_FFS_FILE_HEADER *) FfsFileBuffer;
+ //
+ // First fill all fields ready in FfsFileBuffer
+ //
+ CopyGuid (&TmpFileHeader->Name, FileName);
+ TmpFileHeader->Type = FileType;
+
+ //
+ // Convert the FileAttributes to FFSFileAttributes
+ //
+ FvFileAttrib2FfsFileAttrib (FileAttributes, &TmpFileAttribute);
+
+ TmpFileHeader->Attributes = TmpFileAttribute;
+
+ if (ActualFileSize > 0x00FFFFFF) {
+ ((EFI_FFS_FILE_HEADER2 *) FileHeader)->ExtendedSize = (UINT32) ActualFileSize;
+ *(UINT32 *) FileHeader->Size &= 0xFF000000;
+ FileHeader->Attributes |= FFS_ATTRIB_LARGE_FILE;
+ } else {
+ *(UINT32 *) FileHeader->Size &= 0xFF000000;
+ *(UINT32 *) FileHeader->Size |= ActualFileSize;
+ }
+
+ SetHeaderChecksum (TmpFileHeader);
+ SetFileChecksum (TmpFileHeader, ActualFileSize);
+
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, TmpFileHeader);
+ SetFileState (EFI_FILE_HEADER_VALID, TmpFileHeader);
+ SetFileState (EFI_FILE_DATA_VALID, TmpFileHeader);
+
+ //
+ // Copy data from FfsFileBuffer to FileHeader(cache)
+ //
+ CopyMem (FileHeader, FfsFileBuffer, BufferSize);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Fill some other extra space using 0xFF(Erase Value).
+
+ @param ErasePolarity Fv erase value.
+ @param FileHeader Point to the start of FFS File.
+ @param ExtraLength The pading length.
+
+**/
+VOID
+FvAdjustFfsFile (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FileHeader,
+ IN UINTN ExtraLength
+ )
+{
+ UINT8 *Ptr;
+ UINT8 PadingByte;
+
+ if (IS_FFS_FILE2 (FileHeader)) {
+ Ptr = (UINT8 *) FileHeader + FFS_FILE2_SIZE (FileHeader);
+ } else {
+ Ptr = (UINT8 *) FileHeader + FFS_FILE_SIZE (FileHeader);
+ }
+
+ if (ErasePolarity == 0) {
+ PadingByte = 0;
+ } else {
+ PadingByte = 0xFF;
+ }
+ //
+ // Fill the non-used space with Padding Byte
+ //
+ SetMem (Ptr, ExtraLength, PadingByte);
+
+ return ;
+}
+
+/**
+ Free File List entry pointed by FileListHead.
+
+ @param FileListHeader FileListEntry Header.
+
+**/
+VOID
+FreeFileList (
+ IN LIST_ENTRY *FileListHead
+ )
+{
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ LIST_ENTRY *NextEntry;
+
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) (FileListHead->ForwardLink);
+
+ //
+ // Loop the whole list entry to free resources
+ //
+ while (&FfsFileEntry->Link != FileListHead) {
+ NextEntry = (&FfsFileEntry->Link)->ForwardLink;
+ FreePool (FfsFileEntry);
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) NextEntry;
+ }
+
+ return ;
+}
+
+/**
+ Create a new file within a PAD file area.
+
+ @param FvDevice Firmware Volume Device.
+ @param FfsFileBuffer A buffer that holds an FFS file,(it contains a File Header which is in init state).
+ @param BufferSize The size of FfsFileBuffer.
+ @param ActualFileSize The actual file length, it may not be multiples of 8.
+ @param FileName The FFS File Name.
+ @param FileType The FFS File Type.
+ @param FileAttributes The Attributes of the FFS File to be created.
+
+ @retval EFI_SUCCESS Successfully create a new file within the found PAD file area.
+ @retval EFI_OUT_OF_RESOURCES No suitable PAD file is found.
+ @retval other errors New file is created failed.
+
+**/
+EFI_STATUS
+FvCreateNewFileInsidePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINT8 *FfsFileBuffer,
+ IN UINTN BufferSize,
+ IN UINTN ActualFileSize,
+ IN EFI_GUID *FileName,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ )
+{
+ UINTN RequiredAlignment;
+ FFS_FILE_LIST_ENTRY *PadFileEntry;
+ EFI_STATUS Status;
+ UINTN PadAreaLength;
+ UINTN PadSize;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ EFI_FFS_FILE_HEADER *OldPadFileHeader;
+ EFI_FFS_FILE_HEADER *PadFileHeader;
+ EFI_FFS_FILE_HEADER *TailPadFileHeader;
+ UINTN StateOffset;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+ UINT8 *StartPos;
+ LIST_ENTRY NewFileList;
+ FFS_FILE_LIST_ENTRY *NewFileListEntry;
+ FFS_FILE_LIST_ENTRY *FfsEntry;
+ FFS_FILE_LIST_ENTRY *NextFfsEntry;
+
+ //
+ // First get the required alignment from the File Attributes
+ //
+ RequiredAlignment = GetRequiredAlignment (FileAttributes);
+
+ //
+ // Find a suitable PAD File
+ //
+ Status = FvLocatePadFile (
+ FvDevice,
+ BufferSize,
+ RequiredAlignment,
+ &PadSize,
+ &PadFileEntry
+ );
+
+ if (EFI_ERROR (Status)) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ OldPadFileHeader = (EFI_FFS_FILE_HEADER *) PadFileEntry->FfsHeader;
+
+ //
+ // Step 1: Update Pad File Header
+ //
+ SetFileState (EFI_FILE_MARKED_FOR_UPDATE, OldPadFileHeader);
+
+ StartPos = PadFileEntry->FfsHeader;
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &OldPadFileHeader->State - (UINT8 *) OldPadFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &OldPadFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, OldPadFileHeader);
+ return Status;
+ }
+
+ //
+ // Step 2: Update Pad area
+ //
+ InitializeListHead (&NewFileList);
+
+ if (IS_FFS_FILE2 (OldPadFileHeader)) {
+ PadAreaLength = FFS_FILE2_SIZE (OldPadFileHeader) - sizeof (EFI_FFS_FILE_HEADER);
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER2));
+ } else {
+ PadAreaLength = FFS_FILE_SIZE (OldPadFileHeader) - sizeof (EFI_FFS_FILE_HEADER);
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER));
+ }
+
+ if (PadSize != 0) {
+ //
+ // Insert a PAD file before to achieve required alignment
+ //
+ FvFillPadFile (PadFileHeader, PadSize);
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ ASSERT (NewFileListEntry != NULL);
+ NewFileListEntry->FfsHeader = (UINT8 *) PadFileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+ }
+
+ FileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) PadFileHeader + PadSize);
+
+ Status = FvFillFfsFile (
+ FileHeader,
+ FfsFileBuffer,
+ BufferSize,
+ ActualFileSize,
+ FileName,
+ FileType,
+ FileAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ return Status;
+ }
+
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ ASSERT (NewFileListEntry != NULL);
+
+ NewFileListEntry->FfsHeader = (UINT8 *) FileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+
+ FvDevice->CurrentFfsFile = NewFileListEntry;
+
+ if (PadAreaLength > (BufferSize + PadSize)) {
+ if ((PadAreaLength - BufferSize - PadSize) >= sizeof (EFI_FFS_FILE_HEADER)) {
+ //
+ // we can insert another PAD file
+ //
+ TailPadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FileHeader + BufferSize);
+ FvFillPadFile (TailPadFileHeader, PadAreaLength - BufferSize - PadSize);
+
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ ASSERT (NewFileListEntry != NULL);
+
+ NewFileListEntry->FfsHeader = (UINT8 *) TailPadFileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+ } else {
+ //
+ // because left size cannot hold another PAD file header,
+ // adjust the writing file size (just in cache)
+ //
+ FvAdjustFfsFile (
+ FvDevice->ErasePolarity,
+ FileHeader,
+ PadAreaLength - BufferSize - PadSize
+ );
+ }
+ }
+ //
+ // Start writing to FV
+ //
+ if (IS_FFS_FILE2 (OldPadFileHeader)) {
+ StartPos = (UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ StartPos = (UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+
+ NumBytesWritten = PadAreaLength;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ StartPos
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return Status;
+ }
+
+ //
+ // Step 3: Mark Pad file header as EFI_FILE_HEADER_INVALID
+ //
+ SetFileState (EFI_FILE_HEADER_INVALID, OldPadFileHeader);
+
+ StartPos = PadFileEntry->FfsHeader;
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &OldPadFileHeader->State - (UINT8 *) OldPadFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &OldPadFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ SetFileState (EFI_FILE_HEADER_INVALID, OldPadFileHeader);
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return Status;
+ }
+
+ //
+ // If all successfully, update FFS_FILE_LIST
+ //
+
+ //
+ // Delete old pad file entry
+ //
+ FfsEntry = (FFS_FILE_LIST_ENTRY *) PadFileEntry->Link.BackLink;
+ NextFfsEntry = (FFS_FILE_LIST_ENTRY *) PadFileEntry->Link.ForwardLink;
+
+ FreePool (PadFileEntry);
+
+ FfsEntry->Link.ForwardLink = NewFileList.ForwardLink;
+ (NewFileList.ForwardLink)->BackLink = &FfsEntry->Link;
+ NextFfsEntry->Link.BackLink = NewFileList.BackLink;
+ (NewFileList.BackLink)->ForwardLink = &NextFfsEntry->Link;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Free all FfsBuffer.
+
+ @param NumOfFiles Number of FfsBuffer.
+ @param FfsBuffer An array of pointer to an FFS File Buffer
+
+**/
+VOID
+FreeFfsBuffer (
+ IN UINTN NumOfFiles,
+ IN UINT8 **FfsBuffer
+ )
+{
+ UINTN Index;
+ for (Index = 0; Index < NumOfFiles; Index++) {
+ if (FfsBuffer[Index] != NULL) {
+ FreePool (FfsBuffer[Index]);
+ }
+ }
+}
+
+/**
+ Create multiple files within a PAD File area.
+
+ @param FvDevice Firmware Volume Device.
+ @param PadFileEntry The pad file entry to be written in.
+ @param NumOfFiles Total File number to be written.
+ @param BufferSize The array of buffer size of each FfsBuffer.
+ @param ActualFileSize The array of actual file size.
+ @param PadSize The array of leading pad file size for each FFS File
+ @param FfsBuffer The array of Ffs Buffer pointer.
+ @param FileData The array of EFI_FV_WRITE_FILE_DATA structure,
+ used to get name, attributes, type, etc.
+
+ @retval EFI_SUCCESS Add the input multiple files into PAD file area.
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval other error Files can't be added into PAD file area.
+
+**/
+EFI_STATUS
+FvCreateMultipleFilesInsidePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN FFS_FILE_LIST_ENTRY *PadFileEntry,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *ActualFileSize,
+ IN UINTN *PadSize,
+ IN UINT8 **FfsBuffer,
+ IN EFI_FV_WRITE_FILE_DATA *FileData
+ )
+{
+ EFI_STATUS Status;
+ EFI_FFS_FILE_HEADER *OldPadFileHeader;
+ UINTN Index;
+ EFI_FFS_FILE_HEADER *PadFileHeader;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ EFI_FFS_FILE_HEADER *TailPadFileHeader;
+ UINTN TotalSize;
+ UINTN PadAreaLength;
+ LIST_ENTRY NewFileList;
+ FFS_FILE_LIST_ENTRY *NewFileListEntry;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+ UINT8 *StartPos;
+ FFS_FILE_LIST_ENTRY *FfsEntry;
+ FFS_FILE_LIST_ENTRY *NextFfsEntry;
+
+ InitializeListHead (&NewFileList);
+
+ NewFileListEntry = NULL;
+
+ OldPadFileHeader = (EFI_FFS_FILE_HEADER *) PadFileEntry->FfsHeader;
+ if (IS_FFS_FILE2 (OldPadFileHeader)) {
+ PadAreaLength = FFS_FILE2_SIZE (OldPadFileHeader) - sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ PadAreaLength = FFS_FILE_SIZE (OldPadFileHeader) - sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ Status = UpdateHeaderBit (
+ FvDevice,
+ OldPadFileHeader,
+ EFI_FILE_MARKED_FOR_UPDATE
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Update PAD area
+ //
+ TotalSize = 0;
+ if (IS_FFS_FILE2 (OldPadFileHeader)) {
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER2));
+ } else {
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER));
+ }
+ FileHeader = PadFileHeader;
+
+ for (Index = 0; Index < NumOfFiles; Index++) {
+ if (PadSize[Index] != 0) {
+ FvFillPadFile (PadFileHeader, PadSize[Index]);
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (NewFileListEntry == NULL) {
+ FreeFileList (&NewFileList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileListEntry->FfsHeader = (UINT8 *) PadFileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+ }
+
+ FileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) PadFileHeader + PadSize[Index]);
+ Status = FvFillFfsFile (
+ FileHeader,
+ FfsBuffer[Index],
+ BufferSize[Index],
+ ActualFileSize[Index],
+ FileData[Index].NameGuid,
+ FileData[Index].Type,
+ FileData[Index].FileAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ return Status;
+ }
+
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (NewFileListEntry == NULL) {
+ FreeFileList (&NewFileList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileListEntry->FfsHeader = (UINT8 *) FileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FileHeader + BufferSize[Index]);
+ TotalSize += PadSize[Index];
+ TotalSize += BufferSize[Index];
+ }
+
+ FvDevice->CurrentFfsFile = NewFileListEntry;
+ //
+ // Maybe we need a tail pad file
+ //
+ if (PadAreaLength > TotalSize) {
+ if ((PadAreaLength - TotalSize) >= sizeof (EFI_FFS_FILE_HEADER)) {
+ //
+ // we can insert another PAD file
+ //
+ TailPadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FileHeader + BufferSize[NumOfFiles - 1]);
+ FvFillPadFile (TailPadFileHeader, PadAreaLength - TotalSize);
+
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (NewFileListEntry == NULL) {
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileListEntry->FfsHeader = (UINT8 *) TailPadFileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+ } else {
+ //
+ // because left size cannot hold another PAD file header,
+ // adjust the writing file size (just in cache)
+ //
+ FvAdjustFfsFile (
+ FvDevice->ErasePolarity,
+ FileHeader,
+ PadAreaLength - TotalSize
+ );
+ }
+ }
+ //
+ // Start writing to FV
+ //
+ if (IS_FFS_FILE2 (OldPadFileHeader)) {
+ StartPos = (UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ StartPos = (UINT8 *) OldPadFileHeader + sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+
+ NumBytesWritten = PadAreaLength;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ StartPos
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return Status;
+ }
+
+ Status = UpdateHeaderBit (
+ FvDevice,
+ OldPadFileHeader,
+ EFI_FILE_HEADER_INVALID
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return Status;
+ }
+
+ //
+ // Update File List Link
+ //
+
+ //
+ // First delete old pad file entry
+ //
+ FfsEntry = (FFS_FILE_LIST_ENTRY *) PadFileEntry->Link.BackLink;
+ NextFfsEntry = (FFS_FILE_LIST_ENTRY *) PadFileEntry->Link.ForwardLink;
+
+ FreePool (PadFileEntry);
+
+ FfsEntry->Link.ForwardLink = NewFileList.ForwardLink;
+ (NewFileList.ForwardLink)->BackLink = &FfsEntry->Link;
+ NextFfsEntry->Link.BackLink = NewFileList.BackLink;
+ (NewFileList.BackLink)->ForwardLink = &NextFfsEntry->Link;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Create multiple files within the Free Space.
+
+ @param FvDevice Firmware Volume Device.
+ @param FreeSpaceEntry Indicating in which Free Space(Cache) the multiple files will be inserted.
+ @param NumOfFiles Total File number to be written.
+ @param BufferSize The array of buffer size of each FfsBuffer.
+ @param ActualFileSize The array of actual file size.
+ @param PadSize The array of leading pad file size for each FFS File
+ @param FfsBuffer The array of Ffs Buffer pointer.
+ @param FileData The array of EFI_FV_WRITE_FILE_DATA structure,
+ used to get name, attributes, type, etc.
+
+ @retval EFI_SUCCESS Add the input multiple files into PAD file area.
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval other error Files can't be added into PAD file area.
+
+**/
+EFI_STATUS
+FvCreateMultipleFilesInsideFreeSpace (
+ IN FV_DEVICE *FvDevice,
+ IN FREE_SPACE_ENTRY *FreeSpaceEntry,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *ActualFileSize,
+ IN UINTN *PadSize,
+ IN UINT8 **FfsBuffer,
+ IN EFI_FV_WRITE_FILE_DATA *FileData
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_FFS_FILE_HEADER *PadFileHeader;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ UINTN TotalSize;
+ LIST_ENTRY NewFileList;
+ FFS_FILE_LIST_ENTRY *NewFileListEntry;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+ UINT8 *StartPos;
+
+ InitializeListHead (&NewFileList);
+
+ NewFileListEntry = NULL;
+
+ TotalSize = 0;
+ StartPos = FreeSpaceEntry->StartingAddress;
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) StartPos;
+ FileHeader = PadFileHeader;
+
+ for (Index = 0; Index < NumOfFiles; Index++) {
+ if (PadSize[Index] != 0) {
+ FvFillPadFile (PadFileHeader, PadSize[Index]);
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (NewFileListEntry == NULL) {
+ FreeFileList (&NewFileList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileListEntry->FfsHeader = (UINT8 *) PadFileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+ }
+
+ FileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) PadFileHeader + PadSize[Index]);
+ Status = FvFillFfsFile (
+ FileHeader,
+ FfsBuffer[Index],
+ BufferSize[Index],
+ ActualFileSize[Index],
+ FileData[Index].NameGuid,
+ FileData[Index].Type,
+ FileData[Index].FileAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ return Status;
+ }
+
+ NewFileListEntry = AllocatePool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (NewFileListEntry == NULL) {
+ FreeFileList (&NewFileList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewFileListEntry->FfsHeader = (UINT8 *) FileHeader;
+ InsertTailList (&NewFileList, &NewFileListEntry->Link);
+
+ PadFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FileHeader + BufferSize[Index]);
+ TotalSize += PadSize[Index];
+ TotalSize += BufferSize[Index];
+ }
+
+ if (FreeSpaceEntry->Length < TotalSize) {
+ FreeFileList (&NewFileList);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FvDevice->CurrentFfsFile = NewFileListEntry;
+
+ //
+ // Start writing to FV
+ //
+ Offset = (UINTN) (StartPos - FvDevice->CachedFv);
+
+ NumBytesWritten = TotalSize;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ StartPos
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFileList (&NewFileList);
+ FvDevice->CurrentFfsFile = NULL;
+ return Status;
+ }
+
+ FreeSpaceEntry->Length -= TotalSize;
+ FreeSpaceEntry->StartingAddress += TotalSize;
+
+ NewFileListEntry = (FFS_FILE_LIST_ENTRY *) (NewFileList.ForwardLink);
+
+ while (NewFileListEntry != (FFS_FILE_LIST_ENTRY *) &NewFileList) {
+ InsertTailList (&FvDevice->FfsFileListHeader, &NewFileListEntry->Link);
+ NewFileListEntry = (FFS_FILE_LIST_ENTRY *) (NewFileListEntry->Link.ForwardLink);
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write multiple files into FV in reliable method.
+
+ @param FvDevice Firmware Volume Device.
+ @param NumOfFiles Total File number to be written.
+ @param FileData The array of EFI_FV_WRITE_FILE_DATA structure,
+ used to get name, attributes, type, etc
+ @param FileOperation The array of operation for each file.
+
+ @retval EFI_SUCCESS Files are added into FV.
+ @retval EFI_OUT_OF_RESOURCES No enough free PAD files to add the input files.
+ @retval EFI_INVALID_PARAMETER File number is less than or equal to 1.
+ @retval EFI_UNSUPPORTED File number exceeds the supported max numbers of files.
+
+**/
+EFI_STATUS
+FvCreateMultipleFiles (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN EFI_FV_WRITE_FILE_DATA *FileData,
+ IN BOOLEAN *FileOperation
+ )
+{
+ EFI_STATUS Status;
+ UINT8 *FfsBuffer[MAX_FILES];
+ UINTN Index1;
+ UINTN Index2;
+ UINTN BufferSize[MAX_FILES];
+ UINTN ActualFileSize[MAX_FILES];
+ UINTN RequiredAlignment[MAX_FILES];
+ UINTN PadSize[MAX_FILES];
+ FFS_FILE_LIST_ENTRY *PadFileEntry;
+ UINTN TotalSizeNeeded;
+ FREE_SPACE_ENTRY *FreeSpaceEntry;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
+ UINTN Key;
+ EFI_GUID FileNameGuid;
+ EFI_FV_FILETYPE OldFileType;
+ EFI_FV_FILE_ATTRIBUTES OldFileAttributes;
+ UINTN OldFileSize;
+ FFS_FILE_LIST_ENTRY *OldFfsFileEntry[MAX_FILES];
+ EFI_FFS_FILE_HEADER *OldFileHeader[MAX_FILES];
+ BOOLEAN IsCreateFile;
+ UINTN HeaderSize;
+
+ //
+ // To use this function, we must ensure that the NumOfFiles is great
+ // than 1
+ //
+ if (NumOfFiles <= 1) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (NumOfFiles > MAX_FILES) {
+ return EFI_UNSUPPORTED;
+ }
+
+ Fv = &FvDevice->Fv;
+
+ SetMem (FfsBuffer, NumOfFiles, 0);
+ SetMem (RequiredAlignment, NumOfFiles, 8);
+ SetMem (PadSize, NumOfFiles, 0);
+ ZeroMem (OldFfsFileEntry, sizeof (OldFfsFileEntry));
+ ZeroMem (OldFileHeader, sizeof (OldFileHeader));
+
+ //
+ // Adjust file size
+ //
+ for (Index1 = 0; Index1 < NumOfFiles; Index1++) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ ActualFileSize[Index1] = FileData[Index1].BufferSize + HeaderSize;
+ if (ActualFileSize[Index1] > 0x00FFFFFF) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ ActualFileSize[Index1] = FileData[Index1].BufferSize + HeaderSize;
+ }
+ BufferSize[Index1] = ActualFileSize[Index1];
+
+ if (BufferSize[Index1] == HeaderSize) {
+ //
+ // clear file attributes, zero-length file does not have any attributes
+ //
+ FileData[Index1].FileAttributes = 0;
+ }
+
+ while ((BufferSize[Index1] & 0x07) != 0) {
+ BufferSize[Index1]++;
+ }
+
+ FfsBuffer[Index1] = AllocateZeroPool (BufferSize[Index1]);
+
+ //
+ // Copy File Data into FileBuffer
+ //
+ CopyMem (
+ FfsBuffer[Index1] + HeaderSize,
+ FileData[Index1].Buffer,
+ FileData[Index1].BufferSize
+ );
+
+ if (FvDevice->ErasePolarity == 1) {
+ for (Index2 = 0; Index2 < HeaderSize; Index2++) {
+ FfsBuffer[Index1][Index2] = (UINT8)~FfsBuffer[Index1][Index2];
+ }
+ }
+
+ if ((FileData[Index1].FileAttributes & EFI_FV_FILE_ATTRIB_ALIGNMENT) != 0) {
+ RequiredAlignment[Index1] = GetRequiredAlignment (FileData[Index1].FileAttributes);
+ }
+ //
+ // If update file, mark the original file header to
+ // EFI_FILE_MARKED_FOR_UPDATE
+ //
+ IsCreateFile = FileOperation[Index1];
+ if (!IsCreateFile) {
+
+ Key = 0;
+ do {
+ OldFileType = 0;
+ Status = Fv->GetNextFile (
+ Fv,
+ &Key,
+ &OldFileType,
+ &FileNameGuid,
+ &OldFileAttributes,
+ &OldFileSize
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFfsBuffer (NumOfFiles, FfsBuffer);
+ return Status;
+ }
+ } while (!CompareGuid (&FileNameGuid, FileData[Index1].NameGuid));
+
+ //
+ // Get FfsFileEntry from the search key
+ //
+ OldFfsFileEntry[Index1] = (FFS_FILE_LIST_ENTRY *) Key;
+ OldFileHeader[Index1] = (EFI_FFS_FILE_HEADER *) OldFfsFileEntry[Index1]->FfsHeader;
+ Status = UpdateHeaderBit (
+ FvDevice,
+ OldFileHeader[Index1],
+ EFI_FILE_MARKED_FOR_UPDATE
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFfsBuffer (NumOfFiles, FfsBuffer);
+ return Status;
+ }
+ }
+ }
+ //
+ // First to search a suitable pad file that can hold so
+ // many files
+ //
+ Status = FvSearchSuitablePadFile (
+ FvDevice,
+ NumOfFiles,
+ BufferSize,
+ RequiredAlignment,
+ PadSize,
+ &TotalSizeNeeded,
+ &PadFileEntry
+ );
+
+ if (Status == EFI_NOT_FOUND) {
+ //
+ // Try to find a free space that can hold these files
+ //
+ Status = FvSearchSuitableFreeSpace (
+ FvDevice,
+ NumOfFiles,
+ BufferSize,
+ RequiredAlignment,
+ PadSize,
+ &TotalSizeNeeded,
+ &FreeSpaceEntry
+ );
+ if (EFI_ERROR (Status)) {
+ FreeFfsBuffer (NumOfFiles, FfsBuffer);
+ return EFI_OUT_OF_RESOURCES;
+ }
+ Status = FvCreateMultipleFilesInsideFreeSpace (
+ FvDevice,
+ FreeSpaceEntry,
+ NumOfFiles,
+ BufferSize,
+ ActualFileSize,
+ PadSize,
+ FfsBuffer,
+ FileData
+ );
+
+ } else {
+ //
+ // Create multiple files inside such a pad file
+ // to achieve lock-step update
+ //
+ Status = FvCreateMultipleFilesInsidePadFile (
+ FvDevice,
+ PadFileEntry,
+ NumOfFiles,
+ BufferSize,
+ ActualFileSize,
+ PadSize,
+ FfsBuffer,
+ FileData
+ );
+ }
+
+ FreeFfsBuffer (NumOfFiles, FfsBuffer);
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Delete those updated files
+ //
+ for (Index1 = 0; Index1 < NumOfFiles; Index1++) {
+ IsCreateFile = FileOperation[Index1];
+ if (!IsCreateFile && OldFfsFileEntry[Index1] != NULL) {
+ (OldFfsFileEntry[Index1]->Link.BackLink)->ForwardLink = OldFfsFileEntry[Index1]->Link.ForwardLink;
+ (OldFfsFileEntry[Index1]->Link.ForwardLink)->BackLink = OldFfsFileEntry[Index1]->Link.BackLink;
+ FreePool (OldFfsFileEntry[Index1]);
+ }
+ }
+ //
+ // Set those files' state to EFI_FILE_DELETED
+ //
+ for (Index1 = 0; Index1 < NumOfFiles; Index1++) {
+ IsCreateFile = FileOperation[Index1];
+ if (!IsCreateFile && OldFileHeader[Index1] != NULL) {
+ Status = UpdateHeaderBit (FvDevice, OldFileHeader[Index1], EFI_FILE_DELETED);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVol.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVol.c
new file mode 100644
index 0000000000..65a292db6b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVol.c
@@ -0,0 +1,798 @@
+/** @file
+
+ Firmware File System driver that produce full Firmware Volume2 protocol.
+ Layers on top of Firmware Block protocol to produce a file abstraction
+ of FV based files.
+
+ Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "FwVolDriver.h"
+
+#define KEYSIZE sizeof (UINTN)
+
+/**
+ Given the supplied FW_VOL_BLOCK_PROTOCOL, allocate a buffer for output and
+ copy the real length volume header into it.
+
+ @param Fvb The FW_VOL_BLOCK_PROTOCOL instance from which to
+ read the volume header
+ @param FwVolHeader Pointer to pointer to allocated buffer in which
+ the volume header is returned.
+
+ @retval EFI_OUT_OF_RESOURCES No enough buffer could be allocated.
+ @retval EFI_SUCCESS Successfully read volume header to the allocated
+ buffer.
+ @retval EFI_ACCESS_DENIED Read status of FV is not enabled.
+ @retval EFI_INVALID_PARAMETER The FV Header signature is not as expected or
+ the file system could not be understood.
+**/
+EFI_STATUS
+GetFwVolHeader (
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb,
+ OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_HEADER TempFvh;
+ EFI_FVB_ATTRIBUTES_2 FvbAttributes;
+ UINTN FvhLength;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+
+ //
+ // Determine the real length of FV header
+ //
+ Status = Fvb->GetAttributes (
+ Fvb,
+ &FvbAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ if ((FvbAttributes & EFI_FVB2_READ_STATUS) == 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ //
+ // Just avoid compiling warning
+ //
+ BaseAddress = 0;
+ FvhLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER);
+
+ //
+ // memory-mapped FV and non memory-mapped has different ways to read
+ //
+ if ((FvbAttributes & EFI_FVB2_MEMORY_MAPPED) != 0) {
+ Status = Fvb->GetPhysicalAddress (
+ Fvb,
+ &BaseAddress
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ CopyMem (&TempFvh, (VOID *) (UINTN) BaseAddress, FvhLength);
+ } else {
+ Status = Fvb->Read (
+ Fvb,
+ 0,
+ 0,
+ &FvhLength,
+ (UINT8 *) &TempFvh
+ );
+ }
+
+ //
+ // Validate FV Header signature, if not as expected, continue.
+ //
+ if (TempFvh.Signature != EFI_FVH_SIGNATURE) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Check to see that the file system is indeed formatted in a way we can
+ // understand it...
+ //
+ if ((!CompareGuid (&TempFvh.FileSystemGuid, &gEfiFirmwareFileSystem2Guid)) &&
+ (!CompareGuid (&TempFvh.FileSystemGuid, &gEfiFirmwareFileSystem3Guid))) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *FwVolHeader = AllocatePool (TempFvh.HeaderLength);
+ if (*FwVolHeader == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Read the whole header
+ //
+ if ((FvbAttributes & EFI_FVB2_MEMORY_MAPPED) != 0) {
+ CopyMem (*FwVolHeader, (VOID *) (UINTN) BaseAddress, TempFvh.HeaderLength);
+ } else {
+ //
+ // Assumed the first block is bigger than the length of Fv headder
+ //
+ FvhLength = TempFvh.HeaderLength;
+ Status = Fvb->Read (
+ Fvb,
+ 0,
+ 0,
+ &FvhLength,
+ (UINT8 *) *FwVolHeader
+ );
+ //
+ // Check whether Read successes.
+ //
+ if (EFI_ERROR (Status)) {
+ FreePool (*FwVolHeader);
+ *FwVolHeader = NULL;
+ return Status;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Free FvDevice resource when error happens.
+
+ @param FvDevice Pointer to the FvDevice to be freed.
+**/
+VOID
+FreeFvDeviceResource (
+ IN FV_DEVICE *FvDevice
+ )
+{
+ LBA_ENTRY *LbaEntry;
+ FREE_SPACE_ENTRY *FreeSpaceEntry;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ LIST_ENTRY *NextEntry;
+
+ //
+ // Free LAB Entry
+ //
+ LbaEntry = (LBA_ENTRY *) FvDevice->LbaHeader.ForwardLink;
+ while (&LbaEntry->Link != &FvDevice->LbaHeader) {
+ NextEntry = (&LbaEntry->Link)->ForwardLink;
+ FreePool (LbaEntry);
+ LbaEntry = (LBA_ENTRY *) NextEntry;
+ }
+ //
+ // Free File List Entry
+ //
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) FvDevice->FfsFileListHeader.ForwardLink;
+ while (&FfsFileEntry->Link != &FvDevice->FfsFileListHeader) {
+ NextEntry = (&FfsFileEntry->Link)->ForwardLink;
+ FreePool (FfsFileEntry);
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) NextEntry;
+ }
+ //
+ // Free Space Entry
+ //
+ FreeSpaceEntry = (FREE_SPACE_ENTRY *) FvDevice->FreeSpaceHeader.ForwardLink;
+ while (&FreeSpaceEntry->Link != &FvDevice->FreeSpaceHeader) {
+ NextEntry = (&FreeSpaceEntry->Link)->ForwardLink;
+ FreePool (FreeSpaceEntry);
+ FreeSpaceEntry = (FREE_SPACE_ENTRY *) NextEntry;
+ }
+ //
+ // Free the cache
+ //
+ FreePool ((UINT8 *) (UINTN) FvDevice->CachedFv);
+
+ return ;
+}
+
+/**
+
+ Firmware volume inherits authentication status from the FV image file and section(in another firmware volume)
+ where it came from.
+
+ @param FvDevice A pointer to the FvDevice.
+
+**/
+VOID
+FwVolInheritAuthenticationStatus (
+ IN FV_DEVICE *FvDevice
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_HEADER *CachedFvHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *CachedFvExtHeader;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *ParentFvProtocol;
+ UINTN Key;
+ EFI_GUID FileNameGuid;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES FileAttributes;
+ UINTN FileSize;
+ EFI_SECTION_TYPE SectionType;
+ UINT32 AuthenticationStatus;
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader;
+ UINTN BufferSize;
+
+ CachedFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) FvDevice->CachedFv;
+
+ if (FvDevice->Fv.ParentHandle != NULL) {
+ //
+ // By Parent Handle, find out the FV image file and section(in another firmware volume) where the firmware volume came from
+ //
+ Status = gBS->HandleProtocol (FvDevice->Fv.ParentHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **) &ParentFvProtocol);
+ if (!EFI_ERROR (Status) && (ParentFvProtocol != NULL)) {
+ Key = 0;
+ do {
+ FileType = EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE;
+ Status = ParentFvProtocol->GetNextFile (
+ ParentFvProtocol,
+ &Key,
+ &FileType,
+ &FileNameGuid,
+ &FileAttributes,
+ &FileSize
+ );
+ if (EFI_ERROR (Status)) {
+ return;
+ }
+
+ SectionType = EFI_SECTION_FIRMWARE_VOLUME_IMAGE;
+ FvHeader = NULL;
+ BufferSize = 0;
+ Status = ParentFvProtocol->ReadSection (
+ ParentFvProtocol,
+ &FileNameGuid,
+ SectionType,
+ 0,
+ (VOID **) &FvHeader,
+ &BufferSize,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+ if ((FvHeader->FvLength == CachedFvHeader->FvLength) &&
+ (FvHeader->ExtHeaderOffset == CachedFvHeader->ExtHeaderOffset)) {
+ if (FvHeader->ExtHeaderOffset !=0) {
+ //
+ // Both FVs contain extension header, then compare their FV Name GUID
+ //
+ FvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) ((UINTN) FvHeader + FvHeader->ExtHeaderOffset);
+ CachedFvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) ((UINTN) CachedFvHeader + CachedFvHeader->ExtHeaderOffset);
+ if (CompareGuid (&FvExtHeader->FvName, &CachedFvExtHeader->FvName)) {
+ //
+ // Found the FV image section where the firmware volume came from,
+ // and then inherit authentication status from it.
+ //
+ FvDevice->AuthenticationStatus = AuthenticationStatus;
+ FreePool ((VOID *) FvHeader);
+ return;
+ }
+ } else {
+ //
+ // Both FVs don't contain extension header, then compare their whole FV Image.
+ //
+ if (CompareMem ((VOID *) FvHeader, (VOID *) CachedFvHeader, (UINTN) FvHeader->FvLength) == 0) {
+ //
+ // Found the FV image section where the firmware volume came from
+ // and then inherit authentication status from it.
+ //
+ FvDevice->AuthenticationStatus = AuthenticationStatus;
+ FreePool ((VOID *) FvHeader);
+ return;
+ }
+ }
+ }
+ FreePool ((VOID *) FvHeader);
+ }
+ } while (TRUE);
+ }
+ }
+}
+
+/**
+ Check if an FV is consistent and allocate cache for it.
+
+ @param FvDevice A pointer to the FvDevice to be checked.
+
+ @retval EFI_OUT_OF_RESOURCES No enough buffer could be allocated.
+ @retval EFI_VOLUME_CORRUPTED File system is corrupted.
+ @retval EFI_SUCCESS FV is consistent and cache is allocated.
+
+**/
+EFI_STATUS
+FvCheck (
+ IN FV_DEVICE *FvDevice
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_FVB_ATTRIBUTES_2 FvbAttributes;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader;
+ UINT8 *FwCache;
+ LBA_ENTRY *LbaEntry;
+ FREE_SPACE_ENTRY *FreeSpaceEntry;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ UINT8 *LbaStart;
+ UINTN Index;
+ EFI_LBA LbaIndex;
+ UINT8 *Ptr;
+ UINTN Size;
+ UINT8 *FreeStart;
+ UINTN FreeSize;
+ UINT8 ErasePolarity;
+ EFI_FFS_FILE_STATE FileState;
+ UINT8 *TopFvAddress;
+ UINTN TestLength;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+
+ Fvb = FvDevice->Fvb;
+
+ Status = Fvb->GetAttributes (Fvb, &FvbAttributes);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ InitializeListHead (&FvDevice->LbaHeader);
+ InitializeListHead (&FvDevice->FreeSpaceHeader);
+ InitializeListHead (&FvDevice->FfsFileListHeader);
+
+ FwVolHeader = NULL;
+ Status = GetFwVolHeader (Fvb, &FwVolHeader);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ ASSERT (FwVolHeader != NULL);
+
+ FvDevice->IsFfs3Fv = CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem3Guid);
+
+ //
+ // Double Check firmware volume header here
+ //
+ if (!VerifyFvHeaderChecksum (FwVolHeader)) {
+ FreePool (FwVolHeader);
+ return EFI_VOLUME_CORRUPTED;
+ }
+
+ BlockMap = FwVolHeader->BlockMap;
+
+ //
+ // FwVolHeader->FvLength is the whole FV length including FV header
+ //
+ FwCache = AllocateZeroPool ((UINTN) FwVolHeader->FvLength);
+ if (FwCache == NULL) {
+ FreePool (FwVolHeader);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FvDevice->CachedFv = (EFI_PHYSICAL_ADDRESS) (UINTN) FwCache;
+
+ //
+ // Copy to memory
+ //
+ LbaStart = FwCache;
+ LbaIndex = 0;
+ Ptr = NULL;
+
+ if ((FvbAttributes & EFI_FVB2_MEMORY_MAPPED) != 0) {
+ //
+ // Get volume base address
+ //
+ Status = Fvb->GetPhysicalAddress (Fvb, &BaseAddress);
+ if (EFI_ERROR (Status)) {
+ FreePool (FwVolHeader);
+ return Status;
+ }
+
+ Ptr = (UINT8 *) ((UINTN) BaseAddress);
+
+ DEBUG((EFI_D_INFO, "Fv Base Address is 0x%LX\n", BaseAddress));
+ }
+ //
+ // Copy whole FV into the memory
+ //
+ while ((BlockMap->NumBlocks != 0) || (BlockMap->Length != 0)) {
+
+ for (Index = 0; Index < BlockMap->NumBlocks; Index++) {
+ LbaEntry = AllocatePool (sizeof (LBA_ENTRY));
+ if (LbaEntry == NULL) {
+ FreePool (FwVolHeader);
+ FreeFvDeviceResource (FvDevice);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ LbaEntry->LbaIndex = LbaIndex;
+ LbaEntry->StartingAddress = LbaStart;
+ LbaEntry->BlockLength = BlockMap->Length;
+
+ //
+ // Copy each LBA into memory
+ //
+ if ((FvbAttributes & EFI_FVB2_MEMORY_MAPPED) != 0) {
+
+ CopyMem (LbaStart, Ptr, BlockMap->Length);
+ Ptr += BlockMap->Length;
+
+ } else {
+
+ Size = BlockMap->Length;
+ Status = Fvb->Read (
+ Fvb,
+ LbaIndex,
+ 0,
+ &Size,
+ LbaStart
+ );
+ //
+ // Not check EFI_BAD_BUFFER_SIZE, for Size = BlockMap->Length
+ //
+ if (EFI_ERROR (Status)) {
+ FreePool (FwVolHeader);
+ FreeFvDeviceResource (FvDevice);
+ return Status;
+ }
+
+ }
+
+ LbaIndex++;
+ LbaStart += BlockMap->Length;
+
+ InsertTailList (&FvDevice->LbaHeader, &LbaEntry->Link);
+ }
+
+ BlockMap++;
+ }
+
+ FvDevice->FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) FwCache;
+
+ //
+ // it is not used any more, so free FwVolHeader
+ //
+ FreePool (FwVolHeader);
+
+ //
+ // Scan to check the free space & File list
+ //
+ if ((FvbAttributes & EFI_FVB2_ERASE_POLARITY) != 0) {
+ ErasePolarity = 1;
+ } else {
+ ErasePolarity = 0;
+ }
+
+ FvDevice->ErasePolarity = ErasePolarity;
+
+ //
+ // go through the whole FV cache, check the consistence of the FV
+ //
+ if (FvDevice->FwVolHeader->ExtHeaderOffset != 0) {
+ //
+ // Searching for files starts on an 8 byte aligned boundary after the end of the Extended Header if it exists.
+ //
+ FwVolExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) (UINTN) (FvDevice->CachedFv + FvDevice->FwVolHeader->ExtHeaderOffset);
+ Ptr = (UINT8 *) FwVolExtHeader + FwVolExtHeader->ExtHeaderSize;
+ Ptr = (UINT8 *) ALIGN_POINTER (Ptr, 8);
+ } else {
+ Ptr = (UINT8 *) (UINTN) (FvDevice->CachedFv + FvDevice->FwVolHeader->HeaderLength);
+ }
+ TopFvAddress = (UINT8 *) (UINTN) (FvDevice->CachedFv + FvDevice->FwVolHeader->FvLength);
+
+ //
+ // Build FFS list & Free Space List here
+ //
+ while (Ptr < TopFvAddress) {
+ TestLength = TopFvAddress - Ptr;
+
+ if (TestLength > sizeof (EFI_FFS_FILE_HEADER)) {
+ TestLength = sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ if (IsBufferErased (ErasePolarity, Ptr, TestLength)) {
+ //
+ // We found free space
+ //
+ FreeStart = Ptr;
+ FreeSize = 0;
+
+ do {
+ TestLength = TopFvAddress - Ptr;
+
+ if (TestLength > sizeof (EFI_FFS_FILE_HEADER)) {
+ TestLength = sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ if (!IsBufferErased (ErasePolarity, Ptr, TestLength)) {
+ break;
+ }
+
+ FreeSize += TestLength;
+ Ptr += TestLength;
+ } while (Ptr < TopFvAddress);
+
+ FreeSpaceEntry = AllocateZeroPool (sizeof (FREE_SPACE_ENTRY));
+ if (FreeSpaceEntry == NULL) {
+ FreeFvDeviceResource (FvDevice);
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Create a Free space entry
+ //
+ FreeSpaceEntry->StartingAddress = FreeStart;
+ FreeSpaceEntry->Length = FreeSize;
+ InsertTailList (&FvDevice->FreeSpaceHeader, &FreeSpaceEntry->Link);
+ continue;
+ }
+ //
+ // double check boundary
+ //
+ if (TestLength < sizeof (EFI_FFS_FILE_HEADER)) {
+ break;
+ }
+
+ if (!IsValidFFSHeader (
+ FvDevice->ErasePolarity,
+ (EFI_FFS_FILE_HEADER *) Ptr
+ )) {
+ FileState = GetFileState (
+ FvDevice->ErasePolarity,
+ (EFI_FFS_FILE_HEADER *) Ptr
+ );
+ if ((FileState == EFI_FILE_HEADER_INVALID) || (FileState == EFI_FILE_HEADER_CONSTRUCTION)) {
+ if (IS_FFS_FILE2 (Ptr)) {
+ if (!FvDevice->IsFfs3Fv) {
+ DEBUG ((EFI_D_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &((EFI_FFS_FILE_HEADER *) Ptr)->Name));
+ }
+ Ptr = Ptr + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ Ptr = Ptr + sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ continue;
+
+ } else {
+ //
+ // File system is corrputed, return
+ //
+ FreeFvDeviceResource (FvDevice);
+ return EFI_VOLUME_CORRUPTED;
+ }
+ }
+
+ if (IS_FFS_FILE2 (Ptr)) {
+ ASSERT (FFS_FILE2_SIZE (Ptr) > 0x00FFFFFF);
+ if (!FvDevice->IsFfs3Fv) {
+ DEBUG ((EFI_D_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &((EFI_FFS_FILE_HEADER *) Ptr)->Name));
+ Ptr = Ptr + FFS_FILE2_SIZE (Ptr);
+ //
+ // Adjust Ptr to the next 8-byte aligned boundary.
+ //
+ while (((UINTN) Ptr & 0x07) != 0) {
+ Ptr++;
+ }
+ continue;
+ }
+ }
+
+ if (IsValidFFSFile (FvDevice, (EFI_FFS_FILE_HEADER *) Ptr)) {
+ FileState = GetFileState (
+ FvDevice->ErasePolarity,
+ (EFI_FFS_FILE_HEADER *) Ptr
+ );
+
+ //
+ // check for non-deleted file
+ //
+ if (FileState != EFI_FILE_DELETED) {
+ //
+ // Create a FFS list entry for each non-deleted file
+ //
+ FfsFileEntry = AllocateZeroPool (sizeof (FFS_FILE_LIST_ENTRY));
+ if (FfsFileEntry == NULL) {
+ FreeFvDeviceResource (FvDevice);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ FfsFileEntry->FfsHeader = Ptr;
+ InsertTailList (&FvDevice->FfsFileListHeader, &FfsFileEntry->Link);
+ }
+
+ if (IS_FFS_FILE2 (Ptr)) {
+ Ptr = Ptr + FFS_FILE2_SIZE (Ptr);
+ } else {
+ Ptr = Ptr + FFS_FILE_SIZE (Ptr);
+ }
+
+ //
+ // Adjust Ptr to the next 8-byte aligned boundary.
+ //
+ while (((UINTN) Ptr & 0x07) != 0) {
+ Ptr++;
+ }
+ } else {
+ //
+ // File system is corrupted, return
+ //
+ FreeFvDeviceResource (FvDevice);
+ return EFI_VOLUME_CORRUPTED;
+ }
+ }
+
+ FvDevice->CurrentFfsFile = NULL;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Entry point function does install/reinstall FV2 protocol with full functionality.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_SUCCESS At least one Fv protocol install/reinstall successfully.
+ @retval EFI_NOT_FOUND No FV protocol install/reinstall successfully.
+**/
+EFI_STATUS
+EFIAPI
+FwVolDriverInit (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE *HandleBuffer;
+ UINTN HandleCount;
+ UINTN Index;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
+ FV_DEVICE *FvDevice;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ BOOLEAN Reinstall;
+ BOOLEAN InstallFlag;
+
+ DEBUG ((EFI_D_INFO, "=========FwVol writable driver installed\n"));
+ InstallFlag = FALSE;
+ //
+ // Locate all handles of Fvb protocol
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ NULL,
+ &HandleCount,
+ &HandleBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+
+ for (Index = 0; Index < HandleCount; Index += 1) {
+ Status = gBS->HandleProtocol (
+ HandleBuffer[Index],
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ (VOID **) &Fvb
+ );
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+
+ FwVolHeader = NULL;
+ Status = GetFwVolHeader (Fvb, &FwVolHeader);
+ if (EFI_ERROR (Status)) {
+ continue;
+ }
+ ASSERT (FwVolHeader != NULL);
+ FreePool (FwVolHeader);
+
+ Reinstall = FALSE;
+ //
+ // Check if there is an FV protocol already installed in that handle
+ //
+ Status = gBS->HandleProtocol (
+ HandleBuffer[Index],
+ &gEfiFirmwareVolume2ProtocolGuid,
+ (VOID **) &Fv
+ );
+ if (!EFI_ERROR (Status)) {
+ Reinstall = TRUE;
+ }
+ //
+ // FwVol protocol on the handle so create a new one
+ //
+ FvDevice = AllocateZeroPool (sizeof (FV_DEVICE));
+ if (FvDevice == NULL) {
+ goto Done;
+ }
+
+ FvDevice->Signature = FV_DEVICE_SIGNATURE;
+ FvDevice->Fvb = Fvb;
+
+ //
+ // Firmware Volume Protocol interface
+ //
+ FvDevice->Fv.GetVolumeAttributes = FvGetVolumeAttributes;
+ FvDevice->Fv.SetVolumeAttributes = FvSetVolumeAttributes;
+ FvDevice->Fv.ReadFile = FvReadFile;
+ FvDevice->Fv.ReadSection = FvReadFileSection;
+ FvDevice->Fv.WriteFile = FvWriteFile;
+ FvDevice->Fv.GetNextFile = FvGetNextFile;
+ FvDevice->Fv.KeySize = KEYSIZE;
+ FvDevice->Fv.GetInfo = FvGetVolumeInfo;
+ FvDevice->Fv.SetInfo = FvSetVolumeInfo;
+ FvDevice->Fv.ParentHandle = Fvb->ParentHandle;
+
+ Status = FvCheck (FvDevice);
+ if (EFI_ERROR (Status)) {
+ //
+ // The file system is not consistence
+ //
+ FreePool (FvDevice);
+ continue;
+ }
+
+ FwVolInheritAuthenticationStatus (FvDevice);
+
+ if (Reinstall) {
+ //
+ // Reinstall an New FV protocol
+ //
+ // FvDevice = FV_DEVICE_FROM_THIS (Fv);
+ // FvDevice->Fvb = Fvb;
+ // FreeFvDeviceResource (FvDevice);
+ //
+ Status = gBS->ReinstallProtocolInterface (
+ HandleBuffer[Index],
+ &gEfiFirmwareVolume2ProtocolGuid,
+ Fv,
+ &FvDevice->Fv
+ );
+ if (!EFI_ERROR (Status)) {
+ InstallFlag = TRUE;
+ } else {
+ FreePool (FvDevice);
+ }
+
+ DEBUG ((EFI_D_INFO, "Reinstall FV protocol as writable - %r\n", Status));
+ ASSERT_EFI_ERROR (Status);
+ } else {
+ //
+ // Install an New FV protocol
+ //
+ Status = gBS->InstallProtocolInterface (
+ &FvDevice->Handle,
+ &gEfiFirmwareVolume2ProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &FvDevice->Fv
+ );
+ if (!EFI_ERROR (Status)) {
+ InstallFlag = TRUE;
+ } else {
+ FreePool (FvDevice);
+ }
+
+ DEBUG ((EFI_D_INFO, "Install FV protocol as writable - %r\n", Status));
+ ASSERT_EFI_ERROR (Status);
+ }
+ }
+
+Done:
+ //
+ // As long as one Fv protocol install/reinstall successfully,
+ // success should return to ensure this image will be not unloaded.
+ // Otherwise, new Fv protocols are corrupted by other loaded driver.
+ //
+ if (InstallFlag) {
+ return EFI_SUCCESS;
+ }
+
+ //
+ // No FV protocol install/reinstall successfully.
+ // EFI_NOT_FOUND should return to ensure this image will be unloaded.
+ //
+ return EFI_NOT_FOUND;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolAttrib.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolAttrib.c
new file mode 100644
index 0000000000..0e4ddf8bea
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolAttrib.c
@@ -0,0 +1,220 @@
+/** @file
+
+ Implements get/set firmware volume attributes.
+
+ Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "FwVolDriver.h"
+
+/**
+ Retrieves attributes, insures positive polarity of attribute bits, returns
+ resulting attributes in output parameter.
+
+ @param This Calling context
+ @param Attributes output buffer which contains attributes
+
+ @retval EFI_SUCCESS Successfully got volume attributes
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetVolumeAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ OUT EFI_FV_ATTRIBUTES *Attributes
+ )
+{
+ EFI_STATUS Status;
+ FV_DEVICE *FvDevice;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_FVB_ATTRIBUTES_2 FvbAttributes;
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+ Fvb = FvDevice->Fvb;
+
+ //
+ // First get the Firmware Volume Block Attributes
+ //
+ Status = Fvb->GetAttributes (Fvb, &FvbAttributes);
+ FvbAttributes &= 0xfffff0ff;
+
+ *Attributes = FvbAttributes;
+ *Attributes |= EFI_FV2_WRITE_POLICY_RELIABLE;
+ return Status;
+}
+
+/**
+ Sets current attributes for volume.
+
+ @param This Calling context
+ @param Attributes On input, FvAttributes is a pointer to
+ an EFI_FV_ATTRIBUTES containing the
+ desired firmware volume settings. On
+ successful return, it contains the new
+ settings of the firmware volume. On
+ unsuccessful return, FvAttributes is not
+ modified and the firmware volume
+ settings are not changed.
+
+ @retval EFI_SUCCESS The requested firmware volume attributes
+ were set and the resulting
+ EFI_FV_ATTRIBUTES is returned in
+ FvAttributes.
+ @retval EFI_ACCESS_DENIED Atrribute is locked down.
+ @retval EFI_INVALID_PARAMETER Atrribute is not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+FvSetVolumeAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN OUT EFI_FV_ATTRIBUTES *Attributes
+ )
+{
+ EFI_STATUS Status;
+ FV_DEVICE *FvDevice;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_FVB_ATTRIBUTES_2 OldFvbAttributes;
+ EFI_FVB_ATTRIBUTES_2 NewFvbAttributes;
+ UINT64 NewStatus;
+ UINT32 Capabilities;
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+ Fvb = FvDevice->Fvb;
+
+ //
+ // First get the current Volume Attributes
+ //
+ Status = Fvb->GetAttributes (
+ Fvb,
+ &OldFvbAttributes
+ );
+
+ if ((OldFvbAttributes & EFI_FVB2_LOCK_STATUS) != 0) {
+ return EFI_ACCESS_DENIED;
+ }
+ //
+ // Only status attributes can be updated.
+ //
+ Capabilities = OldFvbAttributes & EFI_FVB2_CAPABILITIES;
+ NewStatus = (*Attributes) & EFI_FVB2_STATUS;
+
+ //
+ // Test read disable
+ //
+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) == 0) {
+ if ((NewStatus & EFI_FVB2_READ_STATUS) == 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ //
+ // Test read enable
+ //
+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) == 0) {
+ if ((NewStatus & EFI_FVB2_READ_STATUS) != 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ //
+ // Test write disable
+ //
+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) == 0) {
+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) == 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ //
+ // Test write enable
+ //
+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) == 0) {
+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) != 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ //
+ // Test lock
+ //
+ if ((Capabilities & EFI_FVB2_LOCK_CAP) == 0) {
+ if ((NewStatus & EFI_FVB2_LOCK_STATUS) != 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ NewFvbAttributes = OldFvbAttributes & (0xFFFFFFFF & (~EFI_FVB2_STATUS));
+ NewFvbAttributes |= NewStatus;
+ Status = Fvb->SetAttributes (
+ Fvb,
+ &NewFvbAttributes
+ );
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ *Attributes = 0;
+
+ This->GetVolumeAttributes (
+ This,
+ Attributes
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Return information of type InformationType for the requested firmware
+ volume.
+
+ @param This Pointer to EFI_FIRMWARE_VOLUME2_PROTOCOL.
+ @param InformationType InformationType for requested.
+ @param BufferSize On input, size of Buffer.On output, the amount of
+ data returned in Buffer.
+ @param Buffer A poniter to the data buffer to return.
+
+ @return EFI_UNSUPPORTED Could not get.
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetVolumeInfo (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *InformationType,
+ IN OUT UINTN *BufferSize,
+ OUT VOID *Buffer
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Set information with InformationType into the requested firmware volume.
+
+ @param This Pointer to EFI_FIRMWARE_VOLUME2_PROTOCOL.
+ @param InformationType InformationType for requested.
+ @param BufferSize Size of Buffer data.
+ @param Buffer A poniter to the data buffer to be set.
+
+ @retval EFI_UNSUPPORTED Could not set.
+
+**/
+EFI_STATUS
+EFIAPI
+FvSetVolumeInfo (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *InformationType,
+ IN UINTN BufferSize,
+ IN CONST VOID *Buffer
+ )
+{
+ return EFI_UNSUPPORTED;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDriver.h b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDriver.h
new file mode 100644
index 0000000000..b1646dd39e
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDriver.h
@@ -0,0 +1,761 @@
+/** @file
+ Common defines and definitions for a FwVolDxe driver.
+
+ Copyright (c) 2006 - 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 _FWVOL_DRIVER_H_
+#define _FWVOL_DRIVER_H_
+
+#include <PiDxe.h>
+
+#include <Guid/FirmwareFileSystem2.h>
+#include <Guid/FirmwareFileSystem3.h>
+#include <Protocol/SectionExtraction.h>
+#include <Protocol/FaultTolerantWrite.h>
+#include <Protocol/FirmwareVolume2.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+
+#include <Library/DebugLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#define FV_DEVICE_SIGNATURE SIGNATURE_32 ('_', 'F', 'V', '_')
+
+//
+// Define two helper macro to extract the Capability field or Status field in FVB
+// bit fields
+//
+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP | \
+ EFI_FVB2_READ_ENABLED_CAP | \
+ EFI_FVB2_WRITE_DISABLED_CAP | \
+ EFI_FVB2_WRITE_ENABLED_CAP | \
+ EFI_FVB2_LOCK_CAP \
+ )
+
+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | EFI_FVB2_LOCK_STATUS)
+
+#define MAX_FILES 32
+
+//
+// Used to calculate from address -> Lba
+//
+typedef struct {
+ LIST_ENTRY Link;
+ EFI_LBA LbaIndex;
+ UINT8 *StartingAddress;
+ UINTN BlockLength;
+} LBA_ENTRY;
+
+//
+// Used to track free space in the Fv
+//
+typedef struct {
+ LIST_ENTRY Link;
+ UINT8 *StartingAddress;
+ UINTN Length;
+} FREE_SPACE_ENTRY;
+
+//
+// Used to track all non-deleted files
+//
+typedef struct {
+ LIST_ENTRY Link;
+ UINT8 *FfsHeader;
+} FFS_FILE_LIST_ENTRY;
+
+typedef struct {
+ UINTN Signature;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL Fv;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ UINT8 *Key;
+ EFI_HANDLE Handle;
+
+ UINT8 ErasePolarity;
+ EFI_PHYSICAL_ADDRESS CachedFv;
+ LIST_ENTRY LbaHeader;
+ LIST_ENTRY FreeSpaceHeader;
+ LIST_ENTRY FfsFileListHeader;
+
+ FFS_FILE_LIST_ENTRY *CurrentFfsFile;
+ BOOLEAN IsFfs3Fv;
+ UINT32 AuthenticationStatus;
+} FV_DEVICE;
+
+#define FV_DEVICE_FROM_THIS(a) CR (a, FV_DEVICE, Fv, FV_DEVICE_SIGNATURE)
+
+/**
+ Retrieves attributes, insures positive polarity of attribute bits, returns
+ resulting attributes in output parameter.
+
+ @param This Calling context
+ @param Attributes output buffer which contains attributes
+
+ @retval EFI_SUCCESS Successfully got volume attributes
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetVolumeAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ OUT EFI_FV_ATTRIBUTES *Attributes
+ );
+
+/**
+ Sets current attributes for volume.
+
+ @param This Calling context
+ @param Attributes On input, FvAttributes is a pointer to
+ an EFI_FV_ATTRIBUTES containing the
+ desired firmware volume settings. On
+ successful return, it contains the new
+ settings of the firmware volume. On
+ unsuccessful return, FvAttributes is not
+ modified and the firmware volume
+ settings are not changed.
+
+ @retval EFI_SUCCESS The requested firmware volume attributes
+ were set and the resulting
+ EFI_FV_ATTRIBUTES is returned in
+ FvAttributes.
+ @retval EFI_ACCESS_DENIED Atrribute is locked down.
+ @retval EFI_INVALID_PARAMETER Atrribute is not valid.
+
+**/
+EFI_STATUS
+EFIAPI
+FvSetVolumeAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN OUT EFI_FV_ATTRIBUTES *Attributes
+ );
+
+/**
+ Given the input key, search for the next matching file in the volume.
+
+ @param This Indicates the calling context.
+ @param Key Key is a pointer to a caller allocated
+ buffer that contains implementation specific
+ data that is used to track where to begin
+ the search for the next file. The size of
+ the buffer must be at least This->KeySize
+ bytes long. To reinitialize the search and
+ begin from the beginning of the firmware
+ volume, the entire buffer must be cleared to
+ zero. Other than clearing the buffer to
+ initiate a new search, the caller must not
+ modify the data in the buffer between calls
+ to GetNextFile().
+ @param FileType FileType is a pointer to a caller allocated
+ EFI_FV_FILETYPE. The GetNextFile() API can
+ filter it's search for files based on the
+ value of *FileType input. A *FileType input
+ of 0 causes GetNextFile() to search for
+ files of all types. If a file is found, the
+ file's type is returned in *FileType.
+ *FileType is not modified if no file is
+ found.
+ @param NameGuid NameGuid is a pointer to a caller allocated
+ EFI_GUID. If a file is found, the file's
+ name is returned in *NameGuid. *NameGuid is
+ not modified if no file is found.
+ @param Attributes Attributes is a pointer to a caller
+ allocated EFI_FV_FILE_ATTRIBUTES. If a file
+ is found, the file's attributes are returned
+ in *Attributes. *Attributes is not modified
+ if no file is found.
+ @param Size Size is a pointer to a caller allocated
+ UINTN. If a file is found, the file's size
+ is returned in *Size. *Size is not modified
+ if no file is found.
+
+ @retval EFI_SUCCESS Successfully find the file.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Fv could not read.
+ @retval EFI_NOT_FOUND No matching file found.
+ @retval EFI_INVALID_PARAMETER Invalid parameter
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetNextFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN OUT VOID *Key,
+ IN OUT EFI_FV_FILETYPE *FileType,
+ OUT EFI_GUID *NameGuid,
+ OUT EFI_FV_FILE_ATTRIBUTES *Attributes,
+ OUT UINTN *Size
+ );
+
+/**
+ Locates a file in the firmware volume and
+ copies it to the supplied buffer.
+
+ @param This Indicates the calling context.
+ @param NameGuid Pointer to an EFI_GUID, which is the
+ filename.
+ @param Buffer Buffer is a pointer to pointer to a buffer
+ in which the file or section contents or are
+ returned.
+ @param BufferSize BufferSize is a pointer to caller allocated
+ UINTN. On input *BufferSize indicates the
+ size in bytes of the memory region pointed
+ to by Buffer. On output, *BufferSize
+ contains the number of bytes required to
+ read the file.
+ @param FoundType FoundType is a pointer to a caller allocated
+ EFI_FV_FILETYPE that on successful return
+ from Read() contains the type of file read.
+ This output reflects the file type
+ irrespective of the value of the SectionType
+ input.
+ @param FileAttributes FileAttributes is a pointer to a caller
+ allocated EFI_FV_FILE_ATTRIBUTES. On
+ successful return from Read(),
+ *FileAttributes contains the attributes of
+ the file read.
+ @param AuthenticationStatus AuthenticationStatus is a pointer to a
+ caller allocated UINTN in which the
+ authentication status is returned.
+
+ @retval EFI_SUCCESS Successfully read to memory buffer.
+ @retval EFI_WARN_BUFFER_TOO_SMALL Buffer too small.
+ @retval EFI_NOT_FOUND Not found.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Could not read.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+ @retval EFI_OUT_OF_RESOURCES Not enough buffer to be allocated.
+
+**/
+EFI_STATUS
+EFIAPI
+FvReadFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *NameGuid,
+ IN OUT VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT EFI_FV_FILETYPE *FoundType,
+ OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes,
+ OUT UINT32 *AuthenticationStatus
+ );
+
+/**
+ Locates a section in a given FFS File and
+ copies it to the supplied buffer (not including section header).
+
+ @param This Indicates the calling context.
+ @param NameGuid Pointer to an EFI_GUID, which is the
+ filename.
+ @param SectionType Indicates the section type to return.
+ @param SectionInstance Indicates which instance of sections with a
+ type of SectionType to return.
+ @param Buffer Buffer is a pointer to pointer to a buffer
+ in which the file or section contents or are
+ returned.
+ @param BufferSize BufferSize is a pointer to caller allocated
+ UINTN.
+ @param AuthenticationStatus AuthenticationStatus is a pointer to a
+ caller allocated UINT32 in which the
+ authentication status is returned.
+
+ @retval EFI_SUCCESS Successfully read the file section into
+ buffer.
+ @retval EFI_WARN_BUFFER_TOO_SMALL Buffer too small.
+ @retval EFI_NOT_FOUND Section not found.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Could not read.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+
+**/
+EFI_STATUS
+EFIAPI
+FvReadFileSection (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *NameGuid,
+ IN EFI_SECTION_TYPE SectionType,
+ IN UINTN SectionInstance,
+ IN OUT VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT UINT32 *AuthenticationStatus
+ );
+
+/**
+ Writes one or more files to the firmware volume.
+
+ @param This Indicates the calling context.
+ @param NumberOfFiles Number of files.
+ @param WritePolicy WritePolicy indicates the level of reliability
+ for the write in the event of a power failure or
+ other system failure during the write operation.
+ @param FileData FileData is an pointer to an array of
+ EFI_FV_WRITE_DATA. Each element of array
+ FileData represents a file to be written.
+
+ @retval EFI_SUCCESS Files successfully written to firmware volume
+ @retval EFI_OUT_OF_RESOURCES Not enough buffer to be allocated.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_WRITE_PROTECTED Write protected.
+ @retval EFI_NOT_FOUND Not found.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+ @retval EFI_UNSUPPORTED This function not supported.
+
+**/
+EFI_STATUS
+EFIAPI
+FvWriteFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN UINT32 NumberOfFiles,
+ IN EFI_FV_WRITE_POLICY WritePolicy,
+ IN EFI_FV_WRITE_FILE_DATA *FileData
+ );
+
+/**
+ Return information of type InformationType for the requested firmware
+ volume.
+
+ @param This Pointer to EFI_FIRMWARE_VOLUME2_PROTOCOL.
+ @param InformationType InformationType for requested.
+ @param BufferSize On input, size of Buffer.On output, the amount of
+ data returned in Buffer.
+ @param Buffer A poniter to the data buffer to return.
+
+ @return EFI_UNSUPPORTED Could not get.
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetVolumeInfo (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *InformationType,
+ IN OUT UINTN *BufferSize,
+ OUT VOID *Buffer
+ );
+
+
+/**
+ Set information with InformationType into the requested firmware volume.
+
+ @param This Pointer to EFI_FIRMWARE_VOLUME2_PROTOCOL.
+ @param InformationType InformationType for requested.
+ @param BufferSize Size of Buffer data.
+ @param Buffer A poniter to the data buffer to be set.
+
+ @retval EFI_UNSUPPORTED Could not set.
+
+**/
+EFI_STATUS
+EFIAPI
+FvSetVolumeInfo (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *InformationType,
+ IN UINTN BufferSize,
+ IN CONST VOID *Buffer
+ );
+
+/**
+ Writes data beginning at Lba:Offset from FV. The write terminates either
+ when *NumBytes of data have been written, or when the firmware end is
+ reached. *NumBytes is updated to reflect the actual number of bytes
+ written.
+
+ @param FvDevice Cached Firmware Volume
+ @param Offset Offset in the block at which to begin write
+ @param NumBytes At input, indicates the requested write size.
+ At output, indicates the actual number of bytes written.
+ @param Buffer Buffer containing source data for the write.
+
+ @retval EFI_SUCCESS Data is successfully written into FV.
+ @return error Data is failed written.
+
+**/
+EFI_STATUS
+FvcWrite (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ );
+
+
+/**
+ Check if a block of buffer is erased.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param Buffer The buffer to be checked
+ @param BufferSize Size of the buffer in bytes
+
+ @retval TRUE The block of buffer is erased
+ @retval FALSE The block of buffer is not erased
+
+**/
+BOOLEAN
+IsBufferErased (
+ IN UINT8 ErasePolarity,
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize
+ );
+
+/**
+ Get the FFS file state by checking the highest bit set in the header's state field.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param FfsHeader Points to the FFS file header
+
+ @return FFS File state
+
+**/
+EFI_FFS_FILE_STATE
+GetFileState (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ );
+
+/**
+ Verify checksum of the firmware volume header.
+
+ @param FvHeader Points to the firmware volume header to be checked
+
+ @retval TRUE Checksum verification passed
+ @retval FALSE Checksum verification failed
+
+**/
+BOOLEAN
+VerifyFvHeaderChecksum (
+ IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader
+ );
+
+/**
+ Check if it's a valid FFS file header.
+
+ @param ErasePolarity Erase polarity attribute of the firmware volume
+ @param FfsHeader Points to the FFS file header to be checked
+
+ @retval TRUE Valid FFS file header
+ @retval FALSE Invalid FFS file header
+
+**/
+BOOLEAN
+IsValidFFSHeader (
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ );
+
+/**
+ Check if it's a valid FFS file.
+ Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first.
+
+ @param FvDevice Cached FV image.
+ @param FfsHeader Points to the FFS file to be checked
+
+ @retval TRUE Valid FFS file
+ @retval FALSE Invalid FFS file
+
+**/
+BOOLEAN
+IsValidFFSFile (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ );
+
+/**
+ Given the supplied FW_VOL_BLOCK_PROTOCOL, allocate a buffer for output and
+ copy the real length volume header into it.
+
+ @param Fvb The FW_VOL_BLOCK_PROTOCOL instance from which to
+ read the volume header
+ @param FwVolHeader Pointer to pointer to allocated buffer in which
+ the volume header is returned.
+
+ @retval EFI_OUT_OF_RESOURCES No enough buffer could be allocated.
+ @retval EFI_SUCCESS Successfully read volume header to the allocated
+ buffer.
+ @retval EFI_ACCESS_DENIED Read status of FV is not enabled.
+ @retval EFI_INVALID_PARAMETER The FV Header signature is not as expected or
+ the file system could not be understood.
+**/
+EFI_STATUS
+GetFwVolHeader (
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb,
+ OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader
+ );
+
+/**
+ Convert the Buffer Address to LBA Entry Address.
+
+ @param FvDevice Cached FvDevice
+ @param BufferAddress Address of Buffer
+ @param LbaListEntry Pointer to the got LBA entry that contains the address.
+
+ @retval EFI_NOT_FOUND Buffer address is out of FvDevice.
+ @retval EFI_SUCCESS LBA entry is found for Buffer address.
+
+**/
+EFI_STATUS
+Buffer2LbaEntry (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_PHYSICAL_ADDRESS BufferAddress,
+ OUT LBA_ENTRY **LbaListEntry
+ );
+
+/**
+ Convert the Buffer Address to LBA Address & Offset.
+
+ @param FvDevice Cached FvDevice
+ @param BufferAddress Address of Buffer
+ @param Lba Pointer to the gob Lba value
+ @param Offset Pointer to the got Offset
+
+ @retval EFI_NOT_FOUND Buffer address is out of FvDevice.
+ @retval EFI_SUCCESS LBA and Offset is found for Buffer address.
+
+**/
+EFI_STATUS
+Buffer2Lba (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_PHYSICAL_ADDRESS BufferAddress,
+ OUT EFI_LBA *Lba,
+ OUT UINTN *Offset
+ );
+
+/**
+ Set File State in the FfsHeader.
+
+ @param State File state to be set into FFS header.
+ @param FfsHeader Points to the FFS file header
+
+**/
+VOID
+SetFileState (
+ IN UINT8 State,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ );
+
+/**
+ Create a PAD File in the Free Space.
+
+ @param FvDevice Firmware Volume Device.
+ @param FreeSpaceEntry Indicating in which Free Space(Cache) the Pad file will be inserted.
+ @param Size Pad file Size, not include the header.
+ @param PadFileEntry The Ffs File Entry that points to this Pad File.
+
+ @retval EFI_SUCCESS Successfully create a PAD file.
+ @retval EFI_OUT_OF_RESOURCES No enough free space to create a PAD file.
+ @retval EFI_INVALID_PARAMETER Size is not 8 byte alignment.
+ @retval EFI_DEVICE_ERROR Free space is not erased.
+**/
+EFI_STATUS
+FvCreatePadFileInFreeSpace (
+ IN FV_DEVICE *FvDevice,
+ IN FREE_SPACE_ENTRY *FreeSpaceEntry,
+ IN UINTN Size,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ );
+
+/**
+ Create a new file within a PAD file area.
+
+ @param FvDevice Firmware Volume Device.
+ @param FfsFileBuffer A buffer that holds an FFS file,(it contains a File Header which is in init state).
+ @param BufferSize The size of FfsFileBuffer.
+ @param ActualFileSize The actual file length, it may not be multiples of 8.
+ @param FileName The FFS File Name.
+ @param FileType The FFS File Type.
+ @param FileAttributes The Attributes of the FFS File to be created.
+
+ @retval EFI_SUCCESS Successfully create a new file within the found PAD file area.
+ @retval EFI_OUT_OF_RESOURCES No suitable PAD file is found.
+ @retval other errors New file is created failed.
+
+**/
+EFI_STATUS
+FvCreateNewFileInsidePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINT8 *FfsFileBuffer,
+ IN UINTN BufferSize,
+ IN UINTN ActualFileSize,
+ IN EFI_GUID *FileName,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ );
+
+/**
+ Write multiple files into FV in reliable method.
+
+ @param FvDevice Firmware Volume Device.
+ @param NumOfFiles Total File number to be written.
+ @param FileData The array of EFI_FV_WRITE_FILE_DATA structure,
+ used to get name, attributes, type, etc
+ @param FileOperation The array of operation for each file.
+
+ @retval EFI_SUCCESS Files are added into FV.
+ @retval EFI_OUT_OF_RESOURCES No enough free PAD files to add the input files.
+ @retval EFI_INVALID_PARAMETER File number is less than or equal to 1.
+ @retval EFI_UNSUPPORTED File number exceeds the supported max numbers of files.
+
+**/
+EFI_STATUS
+FvCreateMultipleFiles (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN EFI_FV_WRITE_FILE_DATA *FileData,
+ IN BOOLEAN *FileOperation
+ );
+
+/**
+ Calculate the checksum for the FFS header.
+
+ @param FfsHeader FFS File Header which needs to calculate the checksum
+
+**/
+VOID
+SetHeaderChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ );
+
+/**
+ Calculate the checksum for the FFS File.
+
+ @param FfsHeader FFS File Header which needs to calculate the checksum
+ @param ActualFileSize The whole Ffs File Length.
+
+**/
+VOID
+SetFileChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader,
+ IN UINTN ActualFileSize
+ );
+
+/**
+ Get the alignment value from File Attributes.
+
+ @param FfsAttributes FFS attribute
+
+ @return Alignment value.
+
+**/
+UINTN
+GetRequiredAlignment (
+ IN EFI_FV_FILE_ATTRIBUTES FfsAttributes
+ );
+
+/**
+ Locate Pad File for writing, this is got from FV Cache.
+
+ @param FvDevice Cached Firmware Volume.
+ @param Size The required FFS file size.
+ @param RequiredAlignment FFS File Data alignment requirement.
+ @param PadSize Pointer to the size of leading Pad File.
+ @param PadFileEntry Pointer to the Pad File Entry that meets the requirement.
+
+ @retval EFI_SUCCESS The required pad file is found.
+ @retval EFI_NOT_FOUND The required pad file can't be found.
+
+**/
+EFI_STATUS
+FvLocatePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Size,
+ IN UINTN RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ );
+
+/**
+ Locate a suitable pad file for multiple file writing.
+
+ @param FvDevice Cached Firmware Volume.
+ @param NumOfFiles The number of Files that needed updating
+ @param BufferSize The array of each file size.
+ @param RequiredAlignment The array of of FFS File Data alignment requirement.
+ @param PadSize The array of size of each leading Pad File.
+ @param TotalSizeNeeded The totalsize that can hold these files.
+ @param PadFileEntry Pointer to the Pad File Entry that meets the requirement.
+
+ @retval EFI_SUCCESS The required pad file is found.
+ @retval EFI_NOT_FOUND The required pad file can't be found.
+
+**/
+EFI_STATUS
+FvSearchSuitablePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT UINTN *TotalSizeNeeded,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ );
+
+/**
+ Locate a Free Space entry which can hold these files, including
+ meeting the alignment requirements.
+
+ @param FvDevice Cached Firmware Volume.
+ @param NumOfFiles The number of Files that needed updating
+ @param BufferSize The array of each file size.
+ @param RequiredAlignment The array of of FFS File Data alignment requirement.
+ @param PadSize The array of size of each leading Pad File.
+ @param TotalSizeNeeded The got total size that can hold these files.
+ @param FreeSpaceEntry The Free Space Entry that can hold these files.
+
+ @retval EFI_SUCCESS The free space entry is found.
+ @retval EFI_NOT_FOUND The free space entry can't be found.
+
+**/
+EFI_STATUS
+FvSearchSuitableFreeSpace (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT UINTN *TotalSizeNeeded,
+ OUT FREE_SPACE_ENTRY **FreeSpaceEntry
+ );
+
+/**
+ Change FFS file header state and write to FV.
+
+ @param FvDevice Cached FV image.
+ @param FfsHeader Points to the FFS file header to be updated.
+ @param State FFS file state to be set.
+
+ @retval EFI_SUCCESS File state is writen into FV.
+ @retval others File state can't be writen into FV.
+
+**/
+EFI_STATUS
+UpdateHeaderBit (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_FFS_FILE_HEADER *FfsHeader,
+ IN EFI_FFS_FILE_STATE State
+ );
+
+/**
+ Convert EFI_FV_FILE_ATTRIBUTES to FFS_FILE_ATTRIBUTES.
+
+ @param FvFileAttrib The value of EFI_FV_FILE_ATTRIBUTES
+ @param FfsFileAttrib Pointer to the got FFS_FILE_ATTRIBUTES value.
+
+**/
+VOID
+FvFileAttrib2FfsFileAttrib (
+ IN EFI_FV_FILE_ATTRIBUTES FvFileAttrib,
+ OUT UINT8 *FfsFileAttrib
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.inf b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.inf
new file mode 100644
index 0000000000..057266bb2b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.inf
@@ -0,0 +1,74 @@
+## @file
+# FwVolDxe Driver.
+#
+# This driver produces Firmware Volume2 protocol with full services
+# (read/write, get/set) based on Firmware Volume Block protocol.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials are
+# licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = FwVolDxe
+ MODULE_UNI_FILE = FwVolDxe.uni
+ FILE_GUID = 233C2592-1CEC-494a-A097-15DC96379777
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = FwVolDriverInit
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ FwVolDriver.h
+ FwPadFile.c
+ Ffs.c
+ FwVolWrite.c
+ FwVolRead.c
+ FwVolAttrib.c
+ FwVol.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+
+
+[LibraryClasses]
+ UefiBootServicesTableLib
+ MemoryAllocationLib
+ BaseMemoryLib
+ BaseLib
+ UefiLib
+ UefiDriverEntryPoint
+ DebugLib
+
+
+[Guids]
+ gEfiFirmwareVolumeTopFileGuid ## CONSUMES ## File # VTF file
+ gEfiFirmwareFileSystem2Guid ## CONSUMES ## GUID # File System Guid
+ gEfiFirmwareFileSystem3Guid ## CONSUMES ## GUID # File System Guid
+
+[Protocols]
+ gEfiSectionExtractionProtocolGuid ## CONSUMES
+ gEfiFirmwareVolumeBlockProtocolGuid ## CONSUMES
+ gEfiFirmwareVolume2ProtocolGuid ## PRODUCES
+
+[Depex]
+ gEfiFirmwareVolumeBlockProtocolGuid AND gEfiSectionExtractionProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ FwVolDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.uni b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.uni
new file mode 100644
index 0000000000..fb77667395
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxe.uni
@@ -0,0 +1,23 @@
+// /** @file
+// FwVolDxe Driver.
+//
+// This driver produces Firmware Volume2 protocol with full services
+// (read/write, get/set) based on Firmware Volume Block protocol.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "FwVolDxe Driver"
+
+#string STR_MODULE_DESCRIPTION #language en-US "This driver produces the Firmware Volume2 protocol with full services (read/write, get/set) based on Firmware Volume Block protocol."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxeExtra.uni
new file mode 100644
index 0000000000..9af2689ec3
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// FwVolDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Flash Storage DXE Driver v2"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolRead.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolRead.c
new file mode 100644
index 0000000000..0d9021914f
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolRead.c
@@ -0,0 +1,632 @@
+/** @file
+ Implements functions to read firmware file.
+
+ Copyright (c) 2006 - 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.
+
+**/
+
+#include "FwVolDriver.h"
+
+/**
+Required Alignment Alignment Value in FFS Alignment Value in
+(bytes) Attributes Field Firmware Volume Interfaces
+1 0 0
+16 1 4
+128 2 7
+512 3 9
+1 KB 4 10
+4 KB 5 12
+32 KB 6 15
+64 KB 7 16
+**/
+UINT8 mFvAttributes[] = {0, 4, 7, 9, 10, 12, 15, 16};
+
+/**
+ Convert the FFS File Attributes to FV File Attributes.
+
+ @param FfsAttributes The attributes of UINT8 type.
+
+ @return The attributes of EFI_FV_FILE_ATTRIBUTES
+
+**/
+EFI_FV_FILE_ATTRIBUTES
+FfsAttributes2FvFileAttributes (
+ IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes
+ )
+{
+ UINT8 DataAlignment;
+ EFI_FV_FILE_ATTRIBUTES FileAttribute;
+
+ DataAlignment = (UINT8) ((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3);
+ ASSERT (DataAlignment < 8);
+
+ FileAttribute = (EFI_FV_FILE_ATTRIBUTES) mFvAttributes[DataAlignment];
+
+ if ((FfsAttributes & FFS_ATTRIB_FIXED) == FFS_ATTRIB_FIXED) {
+ FileAttribute |= EFI_FV_FILE_ATTRIB_FIXED;
+ }
+
+ return FileAttribute;
+}
+
+/**
+ Given the input key, search for the next matching file in the volume.
+
+ @param This Indicates the calling context.
+ @param Key Key is a pointer to a caller allocated
+ buffer that contains implementation specific
+ data that is used to track where to begin
+ the search for the next file. The size of
+ the buffer must be at least This->KeySize
+ bytes long. To reinitialize the search and
+ begin from the beginning of the firmware
+ volume, the entire buffer must be cleared to
+ zero. Other than clearing the buffer to
+ initiate a new search, the caller must not
+ modify the data in the buffer between calls
+ to GetNextFile().
+ @param FileType FileType is a pointer to a caller allocated
+ EFI_FV_FILETYPE. The GetNextFile() API can
+ filter it's search for files based on the
+ value of *FileType input. A *FileType input
+ of 0 causes GetNextFile() to search for
+ files of all types. If a file is found, the
+ file's type is returned in *FileType.
+ *FileType is not modified if no file is
+ found.
+ @param NameGuid NameGuid is a pointer to a caller allocated
+ EFI_GUID. If a file is found, the file's
+ name is returned in *NameGuid. *NameGuid is
+ not modified if no file is found.
+ @param Attributes Attributes is a pointer to a caller
+ allocated EFI_FV_FILE_ATTRIBUTES. If a file
+ is found, the file's attributes are returned
+ in *Attributes. *Attributes is not modified
+ if no file is found.
+ @param Size Size is a pointer to a caller allocated
+ UINTN. If a file is found, the file's size
+ is returned in *Size. *Size is not modified
+ if no file is found.
+
+ @retval EFI_SUCCESS Successfully find the file.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Fv could not read.
+ @retval EFI_NOT_FOUND No matching file found.
+ @retval EFI_INVALID_PARAMETER Invalid parameter
+
+**/
+EFI_STATUS
+EFIAPI
+FvGetNextFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN OUT VOID *Key,
+ IN OUT EFI_FV_FILETYPE *FileType,
+ OUT EFI_GUID *NameGuid,
+ OUT EFI_FV_FILE_ATTRIBUTES *Attributes,
+ OUT UINTN *Size
+ )
+{
+ EFI_STATUS Status;
+ FV_DEVICE *FvDevice;
+ EFI_FV_ATTRIBUTES FvAttributes;
+ EFI_FFS_FILE_HEADER *FfsFileHeader;
+ UINTN *KeyValue;
+ LIST_ENTRY *Link;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+
+ Status = This->GetVolumeAttributes (This, &FvAttributes);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ KeyValue = (UINTN *) Key;
+ FfsFileHeader = NULL;
+
+ //
+ // Check if read operation is enabled
+ //
+ if ((FvAttributes & EFI_FV2_READ_STATUS) == 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ if (*FileType > EFI_FV_FILETYPE_SMM_CORE) {
+ //
+ // File type needs to be in 0 - 0x0D
+ //
+ return EFI_NOT_FOUND;
+ }
+
+ do {
+ if (*KeyValue == 0) {
+ //
+ // Search for 1st matching file
+ //
+ Link = &FvDevice->FfsFileListHeader;
+ if (Link->ForwardLink == &FvDevice->FfsFileListHeader) {
+ return EFI_NOT_FOUND;
+ }
+
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) Link->ForwardLink;
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+
+ //
+ // remember the key
+ //
+ *KeyValue = (UINTN) FfsFileEntry;
+
+ //
+ // we ignore pad files
+ //
+ if (FfsFileHeader->Type == EFI_FV_FILETYPE_FFS_PAD) {
+ continue;
+ }
+
+ if (*FileType == 0) {
+ break;
+ }
+
+ if (*FileType == FfsFileHeader->Type) {
+ break;
+ }
+
+ } else {
+ //
+ // Getting link from last Ffs
+ //
+ Link = (LIST_ENTRY *) (*KeyValue);
+ if (Link->ForwardLink == &FvDevice->FfsFileListHeader) {
+ return EFI_NOT_FOUND;
+ }
+
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) Link->ForwardLink;
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+
+ //
+ // remember the key
+ //
+ *KeyValue = (UINTN) FfsFileEntry;
+
+ //
+ // we ignore pad files
+ //
+ if (FfsFileHeader->Type == EFI_FV_FILETYPE_FFS_PAD) {
+ continue;
+ }
+
+ if (*FileType == EFI_FV_FILETYPE_ALL) {
+ break;
+ }
+
+ if (*FileType == FfsFileHeader->Type) {
+ break;
+ }
+ }
+ } while (Link->ForwardLink != &FvDevice->FfsFileListHeader);
+
+ //
+ // Cache this file entry
+ //
+ FvDevice->CurrentFfsFile = FfsFileEntry;
+
+ *FileType = FfsFileHeader->Type;
+ CopyGuid (NameGuid, &FfsFileHeader->Name);
+ *Attributes = FfsAttributes2FvFileAttributes (FfsFileHeader->Attributes);
+ if ((FvDevice->FwVolHeader->Attributes & EFI_FVB2_MEMORY_MAPPED) == EFI_FVB2_MEMORY_MAPPED) {
+ *Attributes |= EFI_FV_FILE_ATTRIB_MEMORY_MAPPED;
+ }
+
+ //
+ // we need to substract the header size
+ //
+ if (IS_FFS_FILE2 (FfsFileHeader)) {
+ *Size = FFS_FILE2_SIZE (FfsFileHeader) - sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ *Size = FFS_FILE_SIZE (FfsFileHeader) - sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ if (CompareGuid (&gEfiFirmwareVolumeTopFileGuid, NameGuid)) {
+ //
+ // specially deal with VTF file
+ //
+ UINT8 *SrcPtr;
+ UINT32 Tmp;
+
+ if (IS_FFS_FILE2 (FfsFileHeader)) {
+ SrcPtr = ((UINT8 *) FfsFileHeader) + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ SrcPtr = ((UINT8 *) FfsFileHeader) + sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ while (*Size >= 4) {
+ Tmp = *(UINT32 *) SrcPtr;
+ if (Tmp == 0) {
+ SrcPtr += 4;
+ (*Size) -= 4;
+ } else {
+ break;
+ }
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Locates a file in the firmware volume and
+ copies it to the supplied buffer.
+
+ @param This Indicates the calling context.
+ @param NameGuid Pointer to an EFI_GUID, which is the
+ filename.
+ @param Buffer Buffer is a pointer to pointer to a buffer
+ in which the file or section contents or are
+ returned.
+ @param BufferSize BufferSize is a pointer to caller allocated
+ UINTN. On input *BufferSize indicates the
+ size in bytes of the memory region pointed
+ to by Buffer. On output, *BufferSize
+ contains the number of bytes required to
+ read the file.
+ @param FoundType FoundType is a pointer to a caller allocated
+ EFI_FV_FILETYPE that on successful return
+ from Read() contains the type of file read.
+ This output reflects the file type
+ irrespective of the value of the SectionType
+ input.
+ @param FileAttributes FileAttributes is a pointer to a caller
+ allocated EFI_FV_FILE_ATTRIBUTES. On
+ successful return from Read(),
+ *FileAttributes contains the attributes of
+ the file read.
+ @param AuthenticationStatus AuthenticationStatus is a pointer to a
+ caller allocated UINTN in which the
+ authentication status is returned.
+
+ @retval EFI_SUCCESS Successfully read to memory buffer.
+ @retval EFI_WARN_BUFFER_TOO_SMALL Buffer too small.
+ @retval EFI_NOT_FOUND Not found.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Could not read.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+ @retval EFI_OUT_OF_RESOURCES Not enough buffer to be allocated.
+
+**/
+EFI_STATUS
+EFIAPI
+FvReadFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *NameGuid,
+ IN OUT VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT EFI_FV_FILETYPE *FoundType,
+ OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes,
+ OUT UINT32 *AuthenticationStatus
+ )
+{
+ EFI_STATUS Status;
+ FV_DEVICE *FvDevice;
+ UINTN Key;
+ EFI_GUID SearchNameGuid;
+ EFI_FV_ATTRIBUTES FvAttributes;
+ EFI_FV_FILETYPE LocalFoundType;
+ EFI_FV_FILE_ATTRIBUTES LocalAttributes;
+ UINTN FileSize;
+ UINT8 *SrcPtr;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ EFI_FFS_FILE_HEADER *FfsHeader;
+ UINT8 *FileBuffer;
+
+ if (NULL == This || NULL == NameGuid) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+
+ Status = This->GetVolumeAttributes (This, &FvAttributes);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // First check to see that FV is enabled for reads...
+ //
+ if (0 == (FvAttributes & EFI_FV2_READ_STATUS)) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ FfsHeader = NULL;
+
+ //
+ // Check if the file was read last time.
+ //
+ FfsFileEntry = FvDevice->CurrentFfsFile;
+
+ if (FfsFileEntry != NULL) {
+ FfsHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+ }
+
+ if ((FfsFileEntry == NULL) || (!CompareGuid (&FfsHeader->Name, NameGuid))) {
+ //
+ // If not match or no file cached, search this file
+ //
+ Key = 0;
+ do {
+ LocalFoundType = 0;
+ Status = This->GetNextFile (
+ This,
+ &Key,
+ &LocalFoundType,
+ &SearchNameGuid,
+ &LocalAttributes,
+ &FileSize
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+ } while (!CompareGuid (&SearchNameGuid, NameGuid));
+
+ //
+ // Get file entry
+ //
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) Key;
+
+ //
+ // Update the cache
+ //
+ FvDevice->CurrentFfsFile = FfsFileEntry;
+
+ FfsHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+
+ } else {
+ //
+ // Get File Size of the cached file
+ //
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ FileSize = FFS_FILE2_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ FileSize = FFS_FILE_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER);
+ }
+ }
+ //
+ // Get file info
+ //
+ *FoundType = FfsHeader->Type;
+ *FileAttributes = FfsAttributes2FvFileAttributes (FfsHeader->Attributes);
+ if ((FvDevice->FwVolHeader->Attributes & EFI_FVB2_MEMORY_MAPPED) == EFI_FVB2_MEMORY_MAPPED) {
+ *FileAttributes |= EFI_FV_FILE_ATTRIB_MEMORY_MAPPED;
+ }
+ //
+ // Inherit the authentication status.
+ //
+ *AuthenticationStatus = FvDevice->AuthenticationStatus;
+
+ //
+ // If Buffer is NULL, we only want to get some information
+ //
+ if (Buffer == NULL) {
+ *BufferSize = FileSize;
+ return EFI_SUCCESS;
+ }
+
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ SrcPtr = ((UINT8 *) FfsHeader) + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ SrcPtr = ((UINT8 *) FfsHeader) + sizeof (EFI_FFS_FILE_HEADER);
+ }
+
+ if (CompareGuid (&gEfiFirmwareVolumeTopFileGuid, NameGuid)) {
+ //
+ // specially deal with VTF file
+ //
+ UINT32 Tmp;
+
+ while (FileSize >= 4) {
+ Tmp = *(UINT32 *) SrcPtr;
+ if (Tmp == 0) {
+ SrcPtr += 4;
+ FileSize -= 4;
+ } else {
+ break;
+ }
+ }
+ }
+ //
+ // If we drop out of the above loop, we've found the correct file header...
+ //
+ if (*Buffer == NULL) {
+ FileBuffer = AllocateCopyPool (FileSize, SrcPtr);
+ if (FileBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ *BufferSize = FileSize;
+ *Buffer = FileBuffer;
+
+ return EFI_SUCCESS;
+ }
+ //
+ // If the user's buffer is smaller than the file size, then copy as much
+ // as we can and return an appropriate status.
+ //
+ if (FileSize > *BufferSize) {
+ CopyMem (*Buffer, SrcPtr, *BufferSize);
+ *BufferSize = FileSize;
+ return EFI_WARN_BUFFER_TOO_SMALL;
+ }
+ //
+ // User's buffer size is ok, so copy the entire file to their buffer.
+ //
+ *BufferSize = FileSize;
+ CopyMem (*Buffer, SrcPtr, *BufferSize);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Locates a section in a given FFS File and
+ copies it to the supplied buffer (not including section header).
+
+ @param This Indicates the calling context.
+ @param NameGuid Pointer to an EFI_GUID, which is the
+ filename.
+ @param SectionType Indicates the section type to return.
+ @param SectionInstance Indicates which instance of sections with a
+ type of SectionType to return.
+ @param Buffer Buffer is a pointer to pointer to a buffer
+ in which the file or section contents or are
+ returned.
+ @param BufferSize BufferSize is a pointer to caller allocated
+ UINTN.
+ @param AuthenticationStatus AuthenticationStatus is a pointer to a
+ caller allocated UINT32 in which the
+ authentication status is returned.
+
+ @retval EFI_SUCCESS Successfully read the file section into
+ buffer.
+ @retval EFI_WARN_BUFFER_TOO_SMALL Buffer too small.
+ @retval EFI_NOT_FOUND Section not found.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_ACCESS_DENIED Could not read.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+
+**/
+EFI_STATUS
+EFIAPI
+FvReadFileSection (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN CONST EFI_GUID *NameGuid,
+ IN EFI_SECTION_TYPE SectionType,
+ IN UINTN SectionInstance,
+ IN OUT VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT UINT32 *AuthenticationStatus
+ )
+{
+ EFI_STATUS Status;
+ FV_DEVICE *FvDevice;
+ EFI_FV_ATTRIBUTES FvAttributes;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES FileAttributes;
+ UINTN FileSize;
+ UINT8 *FileBuffer;
+ EFI_SECTION_EXTRACTION_PROTOCOL *Sep;
+ UINTN StreamHandle;
+
+ if (NULL == This || NULL == NameGuid || Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+
+ Status = This->GetVolumeAttributes (This, &FvAttributes);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // First check to see that FV is enabled for reads...
+ //
+ if (0 == (FvAttributes & EFI_FV2_READ_STATUS)) {
+ return EFI_ACCESS_DENIED;
+ }
+ //
+ // Read the whole file into buffer
+ //
+ FileBuffer = NULL;
+ Status = This->ReadFile (
+ This,
+ NameGuid,
+ (VOID **) &FileBuffer,
+ &FileSize,
+ &FileType,
+ &FileAttributes,
+ AuthenticationStatus
+ );
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Check to see that the file actually HAS sections before we go any further.
+ //
+ if (FileType == EFI_FV_FILETYPE_RAW) {
+ FreePool (FileBuffer);
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Located the protocol
+ //
+ Status = gBS->LocateProtocol (
+ &gEfiSectionExtractionProtocolGuid,
+ NULL,
+ (VOID **) &Sep
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (FileBuffer);
+ return Status;
+ }
+
+ Status = Sep->OpenSectionStream (
+ Sep,
+ FileSize,
+ FileBuffer,
+ &StreamHandle
+ );
+
+ if (EFI_ERROR (Status)) {
+ FreePool (FileBuffer);
+ return Status;
+ }
+
+ if (SectionType == 0) {
+ //
+ // We need the whole section stream
+ //
+ Status = Sep->GetSection (
+ Sep,
+ StreamHandle,
+ NULL,
+ NULL,
+ 0,
+ Buffer,
+ BufferSize,
+ AuthenticationStatus
+ );
+ } else {
+ Status = Sep->GetSection (
+ Sep,
+ StreamHandle,
+ &SectionType,
+ NULL,
+ SectionInstance,
+ Buffer,
+ BufferSize,
+ AuthenticationStatus
+ );
+ }
+
+ if (!EFI_ERROR (Status)) {
+ //
+ // Inherit the authentication status.
+ //
+ *AuthenticationStatus |= FvDevice->AuthenticationStatus;
+ }
+
+ //
+ // Handle AuthenticationStatus if necessary
+ //
+ Sep->CloseSectionStream (Sep, StreamHandle);
+
+ FreePool (FileBuffer);
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolWrite.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolWrite.c
new file mode 100644
index 0000000000..99385e0f57
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/FwVolDxe/FwVolWrite.c
@@ -0,0 +1,1586 @@
+/** @file
+ Implements write firmware file.
+
+ Copyright (c) 2006 - 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.
+
+**/
+
+#include "FwVolDriver.h"
+
+/**
+ Calculate the checksum for the FFS header.
+
+ @param FfsHeader FFS File Header which needs to calculate the checksum
+
+**/
+VOID
+SetHeaderChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ EFI_FFS_FILE_STATE State;
+ UINT8 FileChecksum;
+
+ //
+ // The state and the File checksum are not included
+ //
+ State = FfsHeader->State;
+ FfsHeader->State = 0;
+
+ FileChecksum = FfsHeader->IntegrityCheck.Checksum.File;
+ FfsHeader->IntegrityCheck.Checksum.File = 0;
+
+ FfsHeader->IntegrityCheck.Checksum.Header = 0;
+
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ FfsHeader->IntegrityCheck.Checksum.Header = CalculateCheckSum8 (
+ (UINT8 *) FfsHeader,
+ sizeof (EFI_FFS_FILE_HEADER2)
+ );
+ } else {
+ FfsHeader->IntegrityCheck.Checksum.Header = CalculateCheckSum8 (
+ (UINT8 *) FfsHeader,
+ sizeof (EFI_FFS_FILE_HEADER)
+ );
+ }
+
+ FfsHeader->State = State;
+ FfsHeader->IntegrityCheck.Checksum.File = FileChecksum;
+
+ return ;
+}
+
+/**
+ Calculate the checksum for the FFS File.
+
+ @param FfsHeader FFS File Header which needs to calculate the checksum
+ @param ActualFileSize The whole Ffs File Length.
+
+**/
+VOID
+SetFileChecksum (
+ IN EFI_FFS_FILE_HEADER *FfsHeader,
+ IN UINTN ActualFileSize
+ )
+{
+ if ((FfsHeader->Attributes & FFS_ATTRIB_CHECKSUM) != 0) {
+
+ FfsHeader->IntegrityCheck.Checksum.File = 0;
+
+ if (IS_FFS_FILE2 (FfsHeader)) {
+ FfsHeader->IntegrityCheck.Checksum.File = CalculateCheckSum8 (
+ (UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER2),
+ ActualFileSize - sizeof (EFI_FFS_FILE_HEADER2)
+ );
+ } else {
+ FfsHeader->IntegrityCheck.Checksum.File = CalculateCheckSum8 (
+ (UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER),
+ ActualFileSize - sizeof (EFI_FFS_FILE_HEADER)
+ );
+ }
+
+ } else {
+
+ FfsHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
+
+ }
+
+ return ;
+}
+
+/**
+ Get the alignment value from File Attributes.
+
+ @param FfsAttributes FFS attribute
+
+ @return Alignment value.
+
+**/
+UINTN
+GetRequiredAlignment (
+ IN EFI_FV_FILE_ATTRIBUTES FfsAttributes
+ )
+{
+ UINTN AlignmentValue;
+
+ AlignmentValue = FfsAttributes & EFI_FV_FILE_ATTRIB_ALIGNMENT;
+
+ if (AlignmentValue <= 3) {
+ return 0x08;
+ }
+
+ if (AlignmentValue > 16) {
+ //
+ // Anyway, we won't reach this code
+ //
+ return 0x08;
+ }
+
+ return (UINTN)1 << AlignmentValue;
+
+}
+
+/**
+ Calculate the leading Pad file size to meet the alignment requirement.
+
+ @param FvDevice Cached Firmware Volume.
+ @param StartAddress The starting address to write the FFS File.
+ @param BufferSize The FFS File Buffer Size.
+ @param RequiredAlignment FFS File Data alignment requirement.
+
+ @return The required Pad File Size.
+
+**/
+UINTN
+CalculatePadFileSize (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_PHYSICAL_ADDRESS StartAddress,
+ IN UINTN BufferSize,
+ IN UINTN RequiredAlignment
+ )
+{
+ UINTN DataStartPos;
+ UINTN RelativePos;
+ UINTN PadSize;
+
+ if (BufferSize > 0x00FFFFFF) {
+ DataStartPos = (UINTN) StartAddress + sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ DataStartPos = (UINTN) StartAddress + sizeof (EFI_FFS_FILE_HEADER);
+ }
+ RelativePos = DataStartPos - (UINTN) FvDevice->CachedFv;
+
+ PadSize = 0;
+
+ while ((RelativePos & (RequiredAlignment - 1)) != 0) {
+ RelativePos++;
+ PadSize++;
+ }
+ //
+ // If padsize is 0, no pad file needed;
+ // If padsize is great than 24, then pad file can be created
+ //
+ if ((PadSize == 0) || (PadSize >= sizeof (EFI_FFS_FILE_HEADER))) {
+ return PadSize;
+ }
+
+ //
+ // Perhaps following method can save space
+ //
+ RelativePos = DataStartPos - (UINTN) FvDevice->CachedFv + sizeof (EFI_FFS_FILE_HEADER);
+ PadSize = sizeof (EFI_FFS_FILE_HEADER);
+
+ while ((RelativePos & (RequiredAlignment - 1)) != 0) {
+ RelativePos++;
+ PadSize++;
+ }
+
+ return PadSize;
+}
+
+/**
+ Convert EFI_FV_FILE_ATTRIBUTES to FFS_FILE_ATTRIBUTES.
+
+ @param FvFileAttrib The value of EFI_FV_FILE_ATTRIBUTES
+ @param FfsFileAttrib Pointer to the got FFS_FILE_ATTRIBUTES value.
+
+**/
+VOID
+FvFileAttrib2FfsFileAttrib (
+ IN EFI_FV_FILE_ATTRIBUTES FvFileAttrib,
+ OUT UINT8 *FfsFileAttrib
+ )
+{
+ UINT8 FvFileAlignment;
+ UINT8 FfsFileAlignment;
+
+ FvFileAlignment = (UINT8) (FvFileAttrib & EFI_FV_FILE_ATTRIB_ALIGNMENT);
+ FfsFileAlignment = 0;
+
+ switch (FvFileAlignment) {
+ case 0:
+ //
+ // fall through
+ //
+ case 1:
+ //
+ // fall through
+ //
+ case 2:
+ //
+ // fall through
+ //
+ case 3:
+ //
+ // fall through
+ //
+ FfsFileAlignment = 0;
+ break;
+
+ case 4:
+ //
+ // fall through
+ //
+ case 5:
+ //
+ // fall through
+ //
+ case 6:
+ //
+ // fall through
+ //
+ FfsFileAlignment = 1;
+ break;
+
+ case 7:
+ //
+ // fall through
+ //
+ case 8:
+ //
+ // fall through
+ //
+ FfsFileAlignment = 2;
+ break;
+
+ case 9:
+ FfsFileAlignment = 3;
+ break;
+
+ case 10:
+ //
+ // fall through
+ //
+ case 11:
+ //
+ // fall through
+ //
+ FfsFileAlignment = 4;
+ break;
+
+ case 12:
+ //
+ // fall through
+ //
+ case 13:
+ //
+ // fall through
+ //
+ case 14:
+ //
+ // fall through
+ //
+ FfsFileAlignment = 5;
+ break;
+
+ case 15:
+ FfsFileAlignment = 6;
+ break;
+
+ case 16:
+ FfsFileAlignment = 7;
+ break;
+ }
+
+ *FfsFileAttrib = (UINT8) (FfsFileAlignment << 3);
+
+ return ;
+}
+
+/**
+ Locate a free space entry that can hold this FFS file.
+
+ @param FvDevice Cached Firmware Volume.
+ @param Size The FFS file size.
+ @param RequiredAlignment FFS File Data alignment requirement.
+ @param PadSize Pointer to the size of leading Pad File.
+ @param FreeSpaceEntry Pointer to the Free Space Entry that meets the requirement.
+
+ @retval EFI_SUCCESS The free space entry is found.
+ @retval EFI_NOT_FOUND The free space entry can't be found.
+
+**/
+EFI_STATUS
+FvLocateFreeSpaceEntry (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Size,
+ IN UINTN RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT FREE_SPACE_ENTRY **FreeSpaceEntry
+ )
+{
+ FREE_SPACE_ENTRY *FreeSpaceListEntry;
+ LIST_ENTRY *Link;
+ UINTN PadFileSize;
+
+ Link = FvDevice->FreeSpaceHeader.ForwardLink;
+ FreeSpaceListEntry = (FREE_SPACE_ENTRY *) Link;
+
+ //
+ // Loop the free space entry list to find one that can hold the
+ // required the file size
+ //
+ while ((LIST_ENTRY *) FreeSpaceListEntry != &FvDevice->FreeSpaceHeader) {
+ PadFileSize = CalculatePadFileSize (
+ FvDevice,
+ (EFI_PHYSICAL_ADDRESS) (UINTN) FreeSpaceListEntry->StartingAddress,
+ Size,
+ RequiredAlignment
+ );
+ if (FreeSpaceListEntry->Length >= Size + PadFileSize) {
+ *FreeSpaceEntry = FreeSpaceListEntry;
+ *PadSize = PadFileSize;
+ return EFI_SUCCESS;
+ }
+
+ FreeSpaceListEntry = (FREE_SPACE_ENTRY *) FreeSpaceListEntry->Link.ForwardLink;
+ }
+
+ return EFI_NOT_FOUND;
+
+}
+
+/**
+ Locate Pad File for writing, this is got from FV Cache.
+
+ @param FvDevice Cached Firmware Volume.
+ @param Size The required FFS file size.
+ @param RequiredAlignment FFS File Data alignment requirement.
+ @param PadSize Pointer to the size of leading Pad File.
+ @param PadFileEntry Pointer to the Pad File Entry that meets the requirement.
+
+ @retval EFI_SUCCESS The required pad file is found.
+ @retval EFI_NOT_FOUND The required pad file can't be found.
+
+**/
+EFI_STATUS
+FvLocatePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Size,
+ IN UINTN RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ )
+{
+ FFS_FILE_LIST_ENTRY *FileEntry;
+ EFI_FFS_FILE_STATE FileState;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ UINTN PadAreaLength;
+ UINTN PadFileSize;
+ UINTN HeaderSize;
+
+ FileEntry = (FFS_FILE_LIST_ENTRY *) FvDevice->FfsFileListHeader.ForwardLink;
+
+ //
+ // travel through the whole file list to get the pad file entry
+ //
+ while (FileEntry != (FFS_FILE_LIST_ENTRY *) &FvDevice->FfsFileListHeader) {
+
+ FileHeader = (EFI_FFS_FILE_HEADER *) FileEntry->FfsHeader;
+ FileState = GetFileState (FvDevice->ErasePolarity, FileHeader);
+
+ if ((FileHeader->Type == EFI_FV_FILETYPE_FFS_PAD) && (FileState == EFI_FILE_DATA_VALID)) {
+ //
+ // we find one valid pad file, check its free area length
+ //
+ if (IS_FFS_FILE2 (FileHeader)) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ PadAreaLength = FFS_FILE2_SIZE (FileHeader) - HeaderSize;
+ } else {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ PadAreaLength = FFS_FILE_SIZE (FileHeader) - HeaderSize;
+ }
+
+ PadFileSize = CalculatePadFileSize (
+ FvDevice,
+ (EFI_PHYSICAL_ADDRESS) (UINTN) FileHeader + HeaderSize,
+ Size,
+ RequiredAlignment
+ );
+ if (PadAreaLength >= (Size + PadFileSize)) {
+ *PadSize = PadFileSize;
+ *PadFileEntry = FileEntry;
+ return EFI_SUCCESS;
+ }
+ }
+
+ FileEntry = (FFS_FILE_LIST_ENTRY *) (FileEntry->Link.ForwardLink);
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+/**
+ Locate a suitable pad file for multiple file writing.
+
+ @param FvDevice Cached Firmware Volume.
+ @param NumOfFiles The number of Files that needed updating
+ @param BufferSize The array of each file size.
+ @param RequiredAlignment The array of of FFS File Data alignment requirement.
+ @param PadSize The array of size of each leading Pad File.
+ @param TotalSizeNeeded The totalsize that can hold these files.
+ @param PadFileEntry Pointer to the Pad File Entry that meets the requirement.
+
+ @retval EFI_SUCCESS The required pad file is found.
+ @retval EFI_NOT_FOUND The required pad file can't be found.
+
+**/
+EFI_STATUS
+FvSearchSuitablePadFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT UINTN *TotalSizeNeeded,
+ OUT FFS_FILE_LIST_ENTRY **PadFileEntry
+ )
+{
+ FFS_FILE_LIST_ENTRY *FileEntry;
+ EFI_FFS_FILE_STATE FileState;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ UINTN PadAreaLength;
+ UINTN TotalSize;
+ UINTN Index;
+ UINTN HeaderSize;
+
+ FileEntry = (FFS_FILE_LIST_ENTRY *) FvDevice->FfsFileListHeader.ForwardLink;
+
+ //
+ // travel through the whole file list to get the pad file entry
+ //
+ while (FileEntry != (FFS_FILE_LIST_ENTRY *) &FvDevice->FfsFileListHeader) {
+
+ FileHeader = (EFI_FFS_FILE_HEADER *) FileEntry->FfsHeader;
+ FileState = GetFileState (FvDevice->ErasePolarity, FileHeader);
+
+ if ((FileHeader->Type == EFI_FV_FILETYPE_FFS_PAD) && (FileState == EFI_FILE_DATA_VALID)) {
+ //
+ // we find one valid pad file, check its length
+ //
+ if (IS_FFS_FILE2 (FileHeader)) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ PadAreaLength = FFS_FILE2_SIZE (FileHeader) - HeaderSize;
+ } else {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ PadAreaLength = FFS_FILE_SIZE (FileHeader) - HeaderSize;
+ }
+ TotalSize = 0;
+
+ for (Index = 0; Index < NumOfFiles; Index++) {
+ PadSize[Index] = CalculatePadFileSize (
+ FvDevice,
+ (EFI_PHYSICAL_ADDRESS) (UINTN) FileHeader + HeaderSize + TotalSize,
+ BufferSize[Index],
+ RequiredAlignment[Index]
+ );
+ TotalSize += PadSize[Index];
+ TotalSize += BufferSize[Index];
+
+ if (TotalSize > PadAreaLength) {
+ break;
+ }
+ }
+
+ if (PadAreaLength >= TotalSize) {
+ *PadFileEntry = FileEntry;
+ *TotalSizeNeeded = TotalSize;
+ return EFI_SUCCESS;
+ }
+ }
+
+ FileEntry = (FFS_FILE_LIST_ENTRY *) (FileEntry->Link.ForwardLink);
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+/**
+ Locate a Free Space entry which can hold these files, including
+ meeting the alignment requirements.
+
+ @param FvDevice Cached Firmware Volume.
+ @param NumOfFiles The number of Files that needed updating
+ @param BufferSize The array of each file size.
+ @param RequiredAlignment The array of of FFS File Data alignment requirement.
+ @param PadSize The array of size of each leading Pad File.
+ @param TotalSizeNeeded The got total size that can hold these files.
+ @param FreeSpaceEntry The Free Space Entry that can hold these files.
+
+ @retval EFI_SUCCESS The free space entry is found.
+ @retval EFI_NOT_FOUND The free space entry can't be found.
+
+**/
+EFI_STATUS
+FvSearchSuitableFreeSpace (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN NumOfFiles,
+ IN UINTN *BufferSize,
+ IN UINTN *RequiredAlignment,
+ OUT UINTN *PadSize,
+ OUT UINTN *TotalSizeNeeded,
+ OUT FREE_SPACE_ENTRY **FreeSpaceEntry
+ )
+{
+ FREE_SPACE_ENTRY *FreeSpaceListEntry;
+ LIST_ENTRY *Link;
+ UINTN TotalSize;
+ UINTN Index;
+ UINT8 *StartAddr;
+
+ Link = FvDevice->FreeSpaceHeader.ForwardLink;
+
+ FreeSpaceListEntry = (FREE_SPACE_ENTRY *) Link;
+
+ while ((LIST_ENTRY *) FreeSpaceListEntry != &FvDevice->FreeSpaceHeader) {
+ TotalSize = 0;
+ StartAddr = FreeSpaceListEntry->StartingAddress;
+
+ //
+ // Calculate the totalsize we need
+ //
+ for (Index = 0; Index < NumOfFiles; Index++) {
+ //
+ // Perhaps we don't need an EFI_FFS_FILE_HEADER, the first file
+ // have had its leading pad file.
+ //
+ PadSize[Index] = CalculatePadFileSize (
+ FvDevice,
+ (EFI_PHYSICAL_ADDRESS) (UINTN) StartAddr + TotalSize,
+ BufferSize[Index],
+ RequiredAlignment[Index]
+ );
+
+ TotalSize += PadSize[Index];
+ TotalSize += BufferSize[Index];
+
+ if (TotalSize > FreeSpaceListEntry->Length) {
+ break;
+ }
+ }
+
+ if (FreeSpaceListEntry->Length >= TotalSize) {
+ *FreeSpaceEntry = FreeSpaceListEntry;
+ *TotalSizeNeeded = TotalSize;
+ return EFI_SUCCESS;
+ }
+
+ FreeSpaceListEntry = (FREE_SPACE_ENTRY *) FreeSpaceListEntry->Link.ForwardLink;
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+/**
+ Calculate the length of the remaining space in FV.
+
+ @param FvDevice Cached Firmware Volume
+ @param Offset Current offset to FV base address.
+ @param Lba LBA number for the current offset.
+ @param LOffset Offset in block for the current offset.
+
+ @return the length of remaining space.
+
+**/
+UINTN
+CalculateRemainingLength (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Offset,
+ OUT EFI_LBA *Lba,
+ OUT UINTN *LOffset
+ )
+{
+ LIST_ENTRY *Link;
+ LBA_ENTRY *LbaEntry;
+ UINTN Count;
+
+ Count = 0;
+ *Lba = 0;
+ Link = FvDevice->LbaHeader.ForwardLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+
+ while (&LbaEntry->Link != &FvDevice->LbaHeader) {
+ if (Count > Offset) {
+ break;
+ }
+
+ Count += LbaEntry->BlockLength;
+ (*Lba)++;
+ Link = LbaEntry->Link.ForwardLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+ }
+
+ if (Count <= Offset) {
+ return 0;
+ }
+
+ Link = LbaEntry->Link.BackLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+
+ (*Lba)--;
+ *LOffset = (UINTN) (LbaEntry->BlockLength - (Count - Offset));
+
+ Count = 0;
+ while (&LbaEntry->Link != &FvDevice->LbaHeader) {
+
+ Count += LbaEntry->BlockLength;
+
+ Link = LbaEntry->Link.ForwardLink;
+ LbaEntry = (LBA_ENTRY *) Link;
+ }
+
+ Count -= *LOffset;
+
+ return Count;
+}
+
+/**
+ Writes data beginning at Lba:Offset from FV. The write terminates either
+ when *NumBytes of data have been written, or when the firmware end is
+ reached. *NumBytes is updated to reflect the actual number of bytes
+ written.
+
+ @param FvDevice Cached Firmware Volume
+ @param Offset Offset in the block at which to begin write
+ @param NumBytes At input, indicates the requested write size.
+ At output, indicates the actual number of bytes written.
+ @param Buffer Buffer containing source data for the write.
+
+ @retval EFI_SUCCESS Data is successfully written into FV.
+ @return error Data is failed written.
+
+**/
+EFI_STATUS
+FvcWrite (
+ IN FV_DEVICE *FvDevice,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_LBA Lba;
+ UINTN LOffset;
+ EFI_FVB_ATTRIBUTES_2 FvbAttributes;
+ UINTN RemainingLength;
+ UINTN WriteLength;
+ UINT8 *TmpBuffer;
+
+ LOffset = 0;
+ RemainingLength = CalculateRemainingLength (FvDevice, Offset, &Lba, &LOffset);
+ if ((UINTN) (*NumBytes) > RemainingLength) {
+ *NumBytes = (UINTN) RemainingLength;
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Fvb = FvDevice->Fvb;
+
+ Status = Fvb->GetAttributes (
+ Fvb,
+ &FvbAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ if ((FvbAttributes & EFI_FV2_WRITE_STATUS) == 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ RemainingLength = *NumBytes;
+ WriteLength = RemainingLength;
+ TmpBuffer = Buffer;
+
+ do {
+ Status = Fvb->Write (
+ Fvb,
+ Lba,
+ LOffset,
+ &WriteLength,
+ TmpBuffer
+ );
+ if (!EFI_ERROR (Status)) {
+ goto Done;
+ }
+
+ if (Status == EFI_BAD_BUFFER_SIZE) {
+ Lba++;
+ LOffset = 0;
+ TmpBuffer += WriteLength;
+ RemainingLength -= WriteLength;
+ WriteLength = (UINTN) RemainingLength;
+
+ continue;
+ } else {
+ return Status;
+ }
+ } while (1);
+
+Done:
+ return EFI_SUCCESS;
+}
+
+/**
+ Create a new FFS file into Firmware Volume device.
+
+ @param FvDevice Cached Firmware Volume.
+ @param FfsFileBuffer A buffer that holds an FFS file,(it contains
+ a File Header which is in init state).
+ @param BufferSize The size of FfsFileBuffer.
+ @param ActualFileSize The actual file length, it may not be multiples of 8.
+ @param FileName The FFS File Name.
+ @param FileType The FFS File Type.
+ @param FileAttributes The Attributes of the FFS File to be created.
+
+ @retval EFI_SUCCESS FFS fle is added into FV.
+ @retval EFI_INVALID_PARAMETER File type is not valid.
+ @retval EFI_DEVICE_ERROR FV doesn't set writable attribute.
+ @retval EFI_NOT_FOUND FV has no enough space for the added file.
+
+**/
+EFI_STATUS
+FvCreateNewFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINT8 *FfsFileBuffer,
+ IN UINTN BufferSize,
+ IN UINTN ActualFileSize,
+ IN EFI_GUID *FileName,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ )
+{
+ EFI_STATUS Status;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ EFI_PHYSICAL_ADDRESS BufferPtr;
+ UINTN Offset;
+ UINTN NumBytesWritten;
+ UINTN StateOffset;
+ FREE_SPACE_ENTRY *FreeSpaceEntry;
+ UINTN RequiredAlignment;
+ UINTN PadFileSize;
+ FFS_FILE_LIST_ENTRY *PadFileEntry;
+ EFI_FFS_FILE_ATTRIBUTES TmpFileAttribute;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ UINTN HeaderSize;
+
+ //
+ // File Type: 0x0E~0xE0 are reserved
+ //
+ if ((FileType > EFI_FV_FILETYPE_SMM_CORE) && (FileType < 0xE0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // First find a free space that can hold this image.
+ // Check alignment, FFS at least must be aligned at 8-byte boundary
+ //
+ RequiredAlignment = GetRequiredAlignment (FileAttributes);
+
+ Status = FvLocateFreeSpaceEntry (
+ FvDevice,
+ BufferSize,
+ RequiredAlignment,
+ &PadFileSize,
+ &FreeSpaceEntry
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // Maybe we need to find a PAD file that can hold this image
+ //
+ Status = FvCreateNewFileInsidePadFile (
+ FvDevice,
+ FfsFileBuffer,
+ BufferSize,
+ ActualFileSize,
+ FileName,
+ FileType,
+ FileAttributes
+ );
+
+ return Status;
+ }
+
+ BufferPtr = (EFI_PHYSICAL_ADDRESS) (UINTN) FreeSpaceEntry->StartingAddress;
+
+ //
+ // If we need a leading PAD File, create it first.
+ //
+ if (PadFileSize != 0) {
+ Status = FvCreatePadFileInFreeSpace (
+ FvDevice,
+ FreeSpaceEntry,
+ PadFileSize - sizeof (EFI_FFS_FILE_HEADER),
+ &PadFileEntry
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+ //
+ // Maybe we create a pad file, so re-get the free space starting address
+ // and length
+ //
+ BufferPtr = (EFI_PHYSICAL_ADDRESS) (UINTN) FreeSpaceEntry->StartingAddress;
+
+ //
+ // File creation step 1: Allocate File Header,
+ // Mark EFI_FILE_HEADER_CONSTRUCTION bit to TRUE,
+ // Write Name, IntegrityCheck.Header, Type, Attributes, and Size
+ //
+ FileHeader = (EFI_FFS_FILE_HEADER *) FfsFileBuffer;
+ if (ActualFileSize > 0x00FFFFFF) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ } else {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ }
+ SetFileState (EFI_FILE_HEADER_CONSTRUCTION, FileHeader);
+
+ Offset = (UINTN) (BufferPtr - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &FileHeader->State - (UINT8 *) FileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &FileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // update header 2 cache
+ //
+ CopyMem (
+ (UINT8 *) (UINTN) BufferPtr,
+ FileHeader,
+ HeaderSize
+ );
+
+ //
+ // update Free Space Entry, now need to substract the file header length
+ //
+ FreeSpaceEntry->StartingAddress += HeaderSize;
+ FreeSpaceEntry->Length -= HeaderSize;
+
+ CopyGuid (&FileHeader->Name, FileName);
+ FileHeader->Type = FileType;
+
+ //
+ // Convert FvFileAttribute to FfsFileAttributes
+ //
+ FvFileAttrib2FfsFileAttrib (FileAttributes, &TmpFileAttribute);
+
+ FileHeader->Attributes = TmpFileAttribute;
+
+ //
+ // File size is including the FFS File Header.
+ //
+ if (ActualFileSize > 0x00FFFFFF) {
+ ((EFI_FFS_FILE_HEADER2 *) FileHeader)->ExtendedSize = (UINT32) ActualFileSize;
+ *(UINT32 *) FileHeader->Size &= 0xFF000000;
+ FileHeader->Attributes |= FFS_ATTRIB_LARGE_FILE;
+ } else {
+ *(UINT32 *) FileHeader->Size &= 0xFF000000;
+ *(UINT32 *) FileHeader->Size |= ActualFileSize;
+ }
+
+ SetHeaderChecksum (FileHeader);
+
+ Offset = (UINTN) (BufferPtr - FvDevice->CachedFv);
+
+ NumBytesWritten = HeaderSize;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ (UINT8 *) FileHeader
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // update header 2 cache
+ //
+ CopyMem (
+ (UINT8 *) (UINTN) BufferPtr,
+ FileHeader,
+ HeaderSize
+ );
+
+ //
+ // end of step 1
+ //
+ // File creation step 2:
+ // MARK EFI_FILE_HEADER_VALID bit to TRUE,
+ // Write IntegrityCheck.File, File Data
+ //
+ SetFileState (EFI_FILE_HEADER_VALID, FileHeader);
+
+ Offset = (UINTN) (BufferPtr - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &FileHeader->State - (UINT8 *) FileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &FileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // update header 2 cache
+ //
+ CopyMem (
+ (UINT8 *) (UINTN) BufferPtr,
+ FileHeader,
+ HeaderSize
+ );
+
+ //
+ // update Free Space Entry, now need to substract the file data length
+ //
+ FreeSpaceEntry->StartingAddress += (BufferSize - HeaderSize);
+ FreeSpaceEntry->Length -= (BufferSize - HeaderSize);
+
+ //
+ // Calculate File Checksum
+ //
+ SetFileChecksum (FileHeader, ActualFileSize);
+
+ Offset = (UINTN) (BufferPtr - FvDevice->CachedFv);
+
+ NumBytesWritten = BufferSize;
+ Status = FvcWrite (
+ FvDevice,
+ Offset,
+ &NumBytesWritten,
+ FfsFileBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // each time write block successfully, write also to cache
+ //
+ CopyMem (
+ (UINT8 *) (UINTN) BufferPtr,
+ FfsFileBuffer,
+ NumBytesWritten
+ );
+
+ //
+ // Step 3: Mark EFI_FILE_DATA_VALID to TRUE
+ //
+ SetFileState (EFI_FILE_DATA_VALID, FileHeader);
+
+ Offset = (UINTN) (BufferPtr - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &FileHeader->State - (UINT8 *) FileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &FileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // update header 2 cache
+ //
+ CopyMem (
+ (UINT8 *) (UINTN) BufferPtr,
+ FileHeader,
+ HeaderSize
+ );
+
+ //
+ // If successfully, insert an FfsFileEntry at the end of ffs file list
+ //
+
+ FfsFileEntry = AllocateZeroPool (sizeof (FFS_FILE_LIST_ENTRY));
+ ASSERT (FfsFileEntry != NULL);
+ FfsFileEntry->FfsHeader = (UINT8 *) (UINTN) BufferPtr;
+ InsertTailList (&FvDevice->FfsFileListHeader, &FfsFileEntry->Link);
+
+ //
+ // Set cache file to this file
+ //
+ FvDevice->CurrentFfsFile = FfsFileEntry;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Update a File, so after successful update, there are 2 files existing
+ in FV, one is marked for deleted, and another one is valid.
+
+ @param FvDevice Cached Firmware Volume.
+ @param FfsFileBuffer A buffer that holds an FFS file,(it contains
+ a File Header which is in init state).
+ @param BufferSize The size of FfsFileBuffer.
+ @param ActualFileSize The actual file length, it may not be multiples of 8.
+ @param FileName The FFS File Name.
+ @param NewFileType The FFS File Type.
+ @param NewFileAttributes The Attributes of the FFS File to be created.
+
+ @retval EFI_SUCCESS FFS fle is updated into FV.
+ @retval EFI_INVALID_PARAMETER File type is not valid.
+ @retval EFI_DEVICE_ERROR FV doesn't set writable attribute.
+ @retval EFI_NOT_FOUND FV has no enough space for the added file.
+ FFS with same file name is not found in FV.
+
+**/
+EFI_STATUS
+FvUpdateFile (
+ IN FV_DEVICE *FvDevice,
+ IN UINT8 *FfsFileBuffer,
+ IN UINTN BufferSize,
+ IN UINTN ActualFileSize,
+ IN EFI_GUID *FileName,
+ IN EFI_FV_FILETYPE NewFileType,
+ IN EFI_FV_FILE_ATTRIBUTES NewFileAttributes
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
+ UINTN NumBytesWritten;
+ EFI_FV_FILETYPE OldFileType;
+ EFI_FV_FILE_ATTRIBUTES OldFileAttributes;
+ UINTN OldFileSize;
+ EFI_FFS_FILE_HEADER *OldFileHeader;
+ UINTN OldOffset;
+ UINTN OldStateOffset;
+ FFS_FILE_LIST_ENTRY *OldFfsFileEntry;
+ UINTN Key;
+ EFI_GUID FileNameGuid;
+
+ Fv = &FvDevice->Fv;
+
+ //
+ // Step 1, find old file,
+ // Mark EFI_FILE_MARKED_FOR_UPDATE to TRUE in the older header
+ //
+
+ //
+ // Check if the file was read last time.
+ //
+ OldFileHeader = NULL;
+ OldFfsFileEntry = FvDevice->CurrentFfsFile;
+
+ if (OldFfsFileEntry != NULL) {
+ OldFileHeader = (EFI_FFS_FILE_HEADER *) OldFfsFileEntry->FfsHeader;
+ }
+
+ if ((OldFfsFileEntry == NULL) || (!CompareGuid (&OldFileHeader->Name, FileName))) {
+ Key = 0;
+ do {
+ OldFileType = 0;
+ Status = Fv->GetNextFile (
+ Fv,
+ &Key,
+ &OldFileType,
+ &FileNameGuid,
+ &OldFileAttributes,
+ &OldFileSize
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ } while (!CompareGuid (&FileNameGuid, FileName));
+
+ //
+ // Get FfsFileEntry from the search key
+ //
+ OldFfsFileEntry = (FFS_FILE_LIST_ENTRY *) Key;
+
+ //
+ // Double check file state before being ready to be removed
+ //
+ OldFileHeader = (EFI_FFS_FILE_HEADER *) OldFfsFileEntry->FfsHeader;
+ } else {
+ //
+ // Mark the cache file to invalid
+ //
+ FvDevice->CurrentFfsFile = NULL;
+ }
+ //
+ // Update File: Mark EFI_FILE_MARKED_FOR_UPDATE to TRUE
+ //
+ SetFileState (EFI_FILE_MARKED_FOR_UPDATE, OldFileHeader);
+
+ OldOffset = (UINTN) ((EFI_PHYSICAL_ADDRESS) (UINTN) OldFileHeader - FvDevice->CachedFv);
+ OldStateOffset = OldOffset + (UINT8 *) &OldFileHeader->State - (UINT8 *) OldFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ OldStateOffset,
+ &NumBytesWritten,
+ &OldFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // if failed, write the bit back in the cache, its XOR operation.
+ //
+ SetFileState (EFI_FILE_MARKED_FOR_UPDATE, OldFileHeader);
+
+ return Status;
+ }
+
+ //
+ // Step 2, Create New Files
+ //
+ Status = FvCreateNewFile (
+ FvDevice,
+ FfsFileBuffer,
+ BufferSize,
+ ActualFileSize,
+ FileName,
+ NewFileType,
+ NewFileAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // If successfully, remove this file entry,
+ // although delete file may fail.
+ //
+ (OldFfsFileEntry->Link.BackLink)->ForwardLink = OldFfsFileEntry->Link.ForwardLink;
+ (OldFfsFileEntry->Link.ForwardLink)->BackLink = OldFfsFileEntry->Link.BackLink;
+ FreePool (OldFfsFileEntry);
+
+ //
+ // Step 3: Delete old files,
+ // by marking EFI_FILE_DELETED to TRUE
+ //
+ SetFileState (EFI_FILE_DELETED, OldFileHeader);
+
+ OldOffset = (UINTN) ((EFI_PHYSICAL_ADDRESS) (UINTN) OldFileHeader - FvDevice->CachedFv);
+ OldStateOffset = OldOffset + (UINT8 *) &OldFileHeader->State - (UINT8 *) OldFileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ OldStateOffset,
+ &NumBytesWritten,
+ &OldFileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // if failed, write the bit back in the cache, its XOR operation.
+ //
+ SetFileState (EFI_FILE_DELETED, OldFileHeader);
+
+ return Status;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Deleted a given file from FV device.
+
+ @param FvDevice Cached Firmware Volume.
+ @param NameGuid The FFS File Name.
+
+ @retval EFI_SUCCESS FFS file with the specified FFS name is removed.
+ @retval EFI_NOT_FOUND FFS file with the specified FFS name is not found.
+
+**/
+EFI_STATUS
+FvDeleteFile (
+ IN FV_DEVICE *FvDevice,
+ IN EFI_GUID *NameGuid
+ )
+{
+ EFI_STATUS Status;
+ UINTN Key;
+ EFI_GUID FileNameGuid;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES FileAttributes;
+ UINTN FileSize;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ FFS_FILE_LIST_ENTRY *FfsFileEntry;
+ EFI_FFS_FILE_STATE FileState;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
+ UINTN Offset;
+ UINTN StateOffset;
+ UINTN NumBytesWritten;
+
+ Fv = &FvDevice->Fv;
+
+ //
+ // Check if the file was read last time.
+ //
+ FileHeader = NULL;
+ FfsFileEntry = FvDevice->CurrentFfsFile;
+
+ if (FfsFileEntry != NULL) {
+ FileHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+ }
+
+ if ((FfsFileEntry == NULL) || (!CompareGuid (&FileHeader->Name, NameGuid))) {
+ //
+ // Next search for the file using GetNextFile
+ //
+ Key = 0;
+ do {
+ FileType = 0;
+ Status = Fv->GetNextFile (
+ Fv,
+ &Key,
+ &FileType,
+ &FileNameGuid,
+ &FileAttributes,
+ &FileSize
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ } while (!CompareGuid (&FileNameGuid, NameGuid));
+
+ //
+ // Get FfsFileEntry from the search key
+ //
+ FfsFileEntry = (FFS_FILE_LIST_ENTRY *) Key;
+
+ //
+ // Double check file state before being ready to be removed
+ //
+ FileHeader = (EFI_FFS_FILE_HEADER *) FfsFileEntry->FfsHeader;
+ } else {
+ //
+ // Mark the cache file to NULL
+ //
+ FvDevice->CurrentFfsFile = NULL;
+ }
+
+ FileState = GetFileState (FvDevice->ErasePolarity, FileHeader);
+
+ if (FileState == EFI_FILE_HEADER_INVALID) {
+ return EFI_NOT_FOUND;
+ }
+
+ if (FileState == EFI_FILE_DELETED) {
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Delete File: Mark EFI_FILE_DELETED to TRUE
+ //
+ SetFileState (EFI_FILE_DELETED, FileHeader);
+
+ Offset = (UINTN) ((EFI_PHYSICAL_ADDRESS) (UINTN) FileHeader - FvDevice->CachedFv);
+ StateOffset = Offset + (UINT8 *) &FileHeader->State - (UINT8 *) FileHeader;
+
+ NumBytesWritten = sizeof (EFI_FFS_FILE_STATE);
+ Status = FvcWrite (
+ FvDevice,
+ StateOffset,
+ &NumBytesWritten,
+ &FileHeader->State
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // if failed, write the bit back in the cache, its XOR operation.
+ //
+ SetFileState (EFI_FILE_DELETED, FileHeader);
+
+ return Status;
+ }
+ //
+ // If successfully, remove this file entry
+ //
+ FvDevice->CurrentFfsFile = NULL;
+
+ (FfsFileEntry->Link.BackLink)->ForwardLink = FfsFileEntry->Link.ForwardLink;
+ (FfsFileEntry->Link.ForwardLink)->BackLink = FfsFileEntry->Link.BackLink;
+ FreePool (FfsFileEntry);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Writes one or more files to the firmware volume.
+
+ @param This Indicates the calling context.
+ @param NumberOfFiles Number of files.
+ @param WritePolicy WritePolicy indicates the level of reliability
+ for the write in the event of a power failure or
+ other system failure during the write operation.
+ @param FileData FileData is an pointer to an array of
+ EFI_FV_WRITE_DATA. Each element of array
+ FileData represents a file to be written.
+
+ @retval EFI_SUCCESS Files successfully written to firmware volume
+ @retval EFI_OUT_OF_RESOURCES Not enough buffer to be allocated.
+ @retval EFI_DEVICE_ERROR Device error.
+ @retval EFI_WRITE_PROTECTED Write protected.
+ @retval EFI_NOT_FOUND Not found.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+ @retval EFI_UNSUPPORTED This function not supported.
+
+**/
+EFI_STATUS
+EFIAPI
+FvWriteFile (
+ IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
+ IN UINT32 NumberOfFiles,
+ IN EFI_FV_WRITE_POLICY WritePolicy,
+ IN EFI_FV_WRITE_FILE_DATA *FileData
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index1;
+ UINTN Index2;
+ UINT8 *FileBuffer;
+ UINTN BufferSize;
+ UINTN ActualSize;
+ UINT8 ErasePolarity;
+ FV_DEVICE *FvDevice;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES FileAttributes;
+ UINTN Size;
+ BOOLEAN CreateNewFile[MAX_FILES];
+ UINTN NumDelete;
+ EFI_FV_ATTRIBUTES FvAttributes;
+ UINT32 AuthenticationStatus;
+ UINTN HeaderSize;
+
+ if (NumberOfFiles > MAX_FILES) {
+ return EFI_UNSUPPORTED;
+ }
+
+ Status = EFI_SUCCESS;
+
+ SetMem (CreateNewFile, NumberOfFiles, TRUE);
+
+ FvDevice = FV_DEVICE_FROM_THIS (This);
+
+ //
+ // First check the volume attributes.
+ //
+ Status = This->GetVolumeAttributes (
+ This,
+ &FvAttributes
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Can we have write right?
+ //
+ if ((FvAttributes & EFI_FV2_WRITE_STATUS) == 0) {
+ return EFI_WRITE_PROTECTED;
+ }
+
+ ErasePolarity = FvDevice->ErasePolarity;
+
+ //
+ // Loop for all files
+ //
+ NumDelete = 0;
+ for (Index1 = 0; Index1 < NumberOfFiles; Index1++) {
+
+ if ((FileData[Index1].BufferSize + sizeof (EFI_FFS_FILE_HEADER) > 0x00FFFFFF) && !FvDevice->IsFfs3Fv) {
+ //
+ // Found a file needs a FFS3 formatted file to store it, but it is in a non-FFS3 formatted FV.
+ //
+ DEBUG ((EFI_D_ERROR, "FFS3 formatted file can't be written in a non-FFS3 formatted FV.\n"));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (FileData[Index1].BufferSize == 0) {
+ //
+ // Here we will delete this file
+ //
+ Status = This->ReadFile (
+ This,
+ FileData[Index1].NameGuid,
+ NULL,
+ &Size,
+ &FileType,
+ &FileAttributes,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+ NumDelete++;
+ } else {
+ return Status;
+ }
+ }
+
+ if (FileData[Index1].Type == EFI_FV_FILETYPE_FFS_PAD) {
+ //
+ // According to PI spec, on EFI_FV_FILETYPE_FFS_PAD:
+ // "Standard firmware file system services will not return the handle of any pad files,
+ // nor will they permit explicit creation of such files."
+ //
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ if ((NumDelete != NumberOfFiles) && (NumDelete != 0)) {
+ //
+ // A delete was request with a multiple file write
+ //
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (NumDelete == NumberOfFiles) {
+ for (Index1 = 0; Index1 < NumberOfFiles; Index1++) {
+ //
+ // Delete Files
+ //
+ Status = FvDeleteFile (FvDevice, FileData[Index1].NameGuid);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ return EFI_SUCCESS;
+ }
+
+ for (Index1 = 0; Index1 < NumberOfFiles; Index1++) {
+ Status = This->ReadFile (
+ This,
+ FileData[Index1].NameGuid,
+ NULL,
+ &Size,
+ &FileType,
+ &FileAttributes,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+ CreateNewFile[Index1] = FALSE;
+ } else if (Status == EFI_NOT_FOUND) {
+ CreateNewFile[Index1] = TRUE;
+ } else {
+ return Status;
+ }
+ //
+ // Checking alignment
+ //
+ if ((FileData[Index1].FileAttributes & EFI_FV_FILE_ATTRIB_ALIGNMENT) != 0) {
+ UINT8 FFSAlignmentValue;
+ UINT8 FvAlignmentValue;
+
+ FFSAlignmentValue = (UINT8) (FileData[Index1].FileAttributes & EFI_FV_FILE_ATTRIB_ALIGNMENT);
+ FvAlignmentValue = (UINT8) (((UINT32) (FvAttributes & EFI_FV2_ALIGNMENT)) >> 16);
+
+ if (FFSAlignmentValue > FvAlignmentValue) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+ }
+
+ if ((WritePolicy != EFI_FV_RELIABLE_WRITE) && (WritePolicy != EFI_FV_UNRELIABLE_WRITE)) {
+ return EFI_INVALID_PARAMETER;
+ }
+ //
+ // Checking the reliable write is supported by FV
+ //
+
+ if ((WritePolicy == EFI_FV_RELIABLE_WRITE) && (NumberOfFiles > 1)) {
+ //
+ // Only for multiple files, reliable write is meaningful
+ //
+ Status = FvCreateMultipleFiles (
+ FvDevice,
+ NumberOfFiles,
+ FileData,
+ CreateNewFile
+ );
+
+ return Status;
+ }
+
+ for (Index1 = 0; Index1 < NumberOfFiles; Index1++) {
+ //
+ // Making Buffersize QWORD boundary, and add file tail.
+ //
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER);
+ ActualSize = FileData[Index1].BufferSize + HeaderSize;
+ if (ActualSize > 0x00FFFFFF) {
+ HeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
+ ActualSize = FileData[Index1].BufferSize + HeaderSize;
+ }
+ BufferSize = ActualSize;
+
+ while ((BufferSize & 0x07) != 0) {
+ BufferSize++;
+ }
+
+ FileBuffer = AllocateZeroPool (BufferSize);
+ if (FileBuffer == NULL) {
+ return Status;
+ }
+ //
+ // Copy File Data into FileBuffer
+ //
+ CopyMem (
+ FileBuffer + HeaderSize,
+ FileData[Index1].Buffer,
+ FileData[Index1].BufferSize
+ );
+
+ if (ErasePolarity == 1) {
+ //
+ // Fill the file header and padding byte with Erase Byte
+ //
+ for (Index2 = 0; Index2 < HeaderSize; Index2++) {
+ FileBuffer[Index2] = (UINT8)~FileBuffer[Index2];
+ }
+
+ for (Index2 = ActualSize; Index2 < BufferSize; Index2++) {
+ FileBuffer[Index2] = (UINT8)~FileBuffer[Index2];
+ }
+ }
+
+ if (CreateNewFile[Index1]) {
+ Status = FvCreateNewFile (
+ FvDevice,
+ FileBuffer,
+ BufferSize,
+ ActualSize,
+ FileData[Index1].NameGuid,
+ FileData[Index1].Type,
+ FileData[Index1].FileAttributes
+ );
+ } else {
+ Status = FvUpdateFile (
+ FvDevice,
+ FileBuffer,
+ BufferSize,
+ ActualSize,
+ FileData[Index1].NameGuid,
+ FileData[Index1].Type,
+ FileData[Index1].FileAttributes
+ );
+ }
+
+ FreePool (FileBuffer);
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/FlashUpdate.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/FlashUpdate.c
new file mode 100644
index 0000000000..56514c9855
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/FlashUpdate.c
@@ -0,0 +1,1218 @@
+/** @file
+ Functions in this file will program the image into flash area.
+
+ Copyright (c) 2002 - 2010, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "UpdateDriver.h"
+
+/**
+ Write a block size data into flash.
+
+ @param FvbProtocol Pointer to FVB protocol.
+ @param Lba Logic block index to be updated.
+ @param BlockSize Block size
+ @param Buffer Buffer data to be written.
+
+ @retval EFI_SUCCESS Write data successfully.
+ @retval other errors Write data failed.
+
+**/
+EFI_STATUS
+UpdateOneBlock (
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_LBA Lba,
+ IN UINTN BlockSize,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINTN Size;
+
+ //
+ // First erase the block
+ //
+ Status = FvbProtocol->EraseBlocks (
+ FvbProtocol,
+ Lba, // Lba
+ 1, // NumOfBlocks
+ EFI_LBA_LIST_TERMINATOR
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Write the block
+ //
+ Size = BlockSize;
+ Status = FvbProtocol->Write (
+ FvbProtocol,
+ Lba, // Lba
+ 0, // Offset
+ &Size, // Size
+ Buffer // Buffer
+ );
+ if ((EFI_ERROR (Status)) || (Size != BlockSize)) {
+ return Status;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write buffer data in a flash block.
+
+ @param FvbProtocol Pointer to FVB protocol.
+ @param Lba Logic block index to be updated.
+ @param Offset The offset within the block.
+ @param Length Size of buffer to be updated.
+ @param BlockSize Block size.
+ @param Buffer Buffer data to be updated.
+
+ @retval EFI_SUCCESS Write data successfully.
+ @retval other errors Write data failed.
+
+**/
+EFI_STATUS
+UpdateBufferInOneBlock (
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN UINTN Length,
+ IN UINTN BlockSize,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINTN Size;
+ UINT8 *ReservedBuffer;
+
+ //
+ // If we are going to update a whole block
+ //
+ if ((Offset == 0) && (Length == BlockSize)) {
+ Status = UpdateOneBlock (
+ FvbProtocol,
+ Lba,
+ BlockSize,
+ Buffer
+ );
+ return Status;
+ }
+
+ //
+ // If it is not a full block update, we need to coalesce data in
+ // the block that is not going to be updated and new data together.
+ //
+
+ //
+ // Allocate a reserved buffer to make up the final buffer for update
+ //
+ ReservedBuffer = NULL;
+ ReservedBuffer = AllocatePool (BlockSize);
+ if (ReservedBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // First get the original content of the block
+ //
+ Size = BlockSize;
+ Status = FvbProtocol->Read (
+ FvbProtocol,
+ Lba,
+ 0,
+ &Size,
+ ReservedBuffer
+ );
+ if ((EFI_ERROR (Status)) || (Size != BlockSize)) {
+ FreePool (ReservedBuffer);
+ return Status;
+ }
+
+ //
+ // Overwrite the reserved buffer with new content
+ //
+ CopyMem (ReservedBuffer + Offset, Buffer, Length);
+
+ Status = UpdateOneBlock (
+ FvbProtocol,
+ Lba,
+ BlockSize,
+ ReservedBuffer
+ );
+
+ FreePool (ReservedBuffer);
+
+ return Status;
+}
+
+/**
+ Get the last write log, and check the status of last write.
+ If not complete, restart will be taken.
+
+ @param FvbHandle Handle of FVB protocol.
+ @param FtwProtocol FTW protocol instance.
+ @param ConfigData Config data on updating driver.
+ @param PrivateDataSize bytes from the private data
+ stored for this write.
+ @param PrivateData A pointer to a buffer. The function will copy.
+ @param Lba The logical block address of the last write.
+ @param Offset The offset within the block of the last write.
+ @param Length The length of the last write.
+ @param Pending A Boolean value with TRUE indicating
+ that the write was completed.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_ABORTED The FTW work space is damaged.
+ @retval EFI_NOT_FOUND The last write is not done by this driver.
+ @retval EFI_SUCCESS Last write log is got.
+
+**/
+EFI_STATUS
+RetrieveLastWrite (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *FtwProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINTN PrivateDataSize,
+ IN OUT UPDATE_PRIVATE_DATA *PrivateData,
+ IN OUT EFI_LBA *Lba,
+ IN OUT UINTN *Offset,
+ IN OUT UINTN *Length,
+ IN OUT BOOLEAN *Pending
+ )
+{
+ EFI_STATUS Status;
+ EFI_GUID CallerId;
+ UINTN PrivateBufferSize;
+ BOOLEAN Complete;
+ VOID *PrivateDataBuffer;
+
+ //
+ // Get the last write
+ //
+ *Pending = FALSE;
+ PrivateBufferSize = PrivateDataSize;
+ PrivateDataBuffer = NULL;
+ Status = FtwProtocol->GetLastWrite (
+ FtwProtocol,
+ &CallerId,
+ Lba,
+ Offset,
+ Length,
+ &PrivateBufferSize,
+ PrivateData,
+ &Complete
+ );
+ if (EFI_ERROR (Status)) {
+ //
+ // If there is no incompleted record, return success.
+ //
+ if ((Status == EFI_NOT_FOUND) && Complete) {
+ return EFI_SUCCESS;
+ } else if (Status == EFI_BUFFER_TOO_SMALL) {
+ //
+ // If buffer too small, reallocate buffer and call getlastwrite again
+ //
+ PrivateDataBuffer = AllocatePool (PrivateBufferSize);
+
+ if (PrivateDataBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Status = FtwProtocol->GetLastWrite (
+ FtwProtocol,
+ &CallerId,
+ Lba,
+ Offset,
+ Length,
+ &PrivateBufferSize,
+ PrivateDataBuffer,
+ &Complete
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool ( PrivateDataBuffer);
+ return EFI_ABORTED;
+ } else {
+ CopyMem (PrivateData, PrivateDataBuffer, PrivateDataSize);
+ FreePool (PrivateDataBuffer);
+ PrivateDataBuffer = NULL;
+ }
+ } else {
+ return EFI_ABORTED;
+ }
+ }
+
+ *Pending = TRUE;
+
+ //
+ // If the caller is not the update driver, then return.
+ // The update driver cannot continue to perform the update
+ //
+ if (CompareMem (&CallerId, &gEfiCallerIdGuid, sizeof (EFI_GUID)) != 0) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Check the private data and see if it is the one I need.
+ //
+ if (CompareMem (&(PrivateData->FileGuid), &(ConfigData->FileGuid), sizeof(EFI_GUID)) != 0) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // If the caller is the update driver and complete is not true, then restart().
+ //
+ if (!Complete) {
+ //
+ // Re-start the update
+ //
+ Status = FtwProtocol->Restart (
+ FtwProtocol,
+ FvbHandle
+ );
+ //
+ // If restart() error, then abort().
+ //
+ if (EFI_ERROR (Status)) {
+ FtwProtocol->Abort (FtwProtocol);
+ //
+ // Now set Pending as FALSE as this record has been cleared
+ //
+ *Pending = FALSE;
+ return EFI_SUCCESS;
+ }
+
+ }
+
+ return Status;
+}
+
+/**
+ Update the whole FV image in fault tolerant write method.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param BlockMap Block array to specify flash area.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+
+ @retval EFI_SUCCESS FV image is writed into flash.
+ @retval EFI_INVALID_PARAMETER Config data is not valid.
+ @retval EFI_NOT_FOUND FTW protocol doesn't exist.
+ @retval EFI_OUT_OF_RESOURCES No enough backup space.
+ @retval EFI_ABORTED Error happen when update FV.
+
+**/
+EFI_STATUS
+FaultTolerantUpdateOnWholeFv (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_FV_BLOCK_MAP_ENTRY *BlockMap,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_FAULT_TOLERANT_WRITE_PROTOCOL *FtwProtocol;
+ UINTN MaxBlockSize;
+ UINTN FtwMaxBlockSize;
+ BOOLEAN Pending;
+ UPDATE_PRIVATE_DATA PrivateData;
+ EFI_LBA PendingLba;
+ EFI_LBA Lba;
+ UINTN PendingOffset;
+ UINTN Offset;
+ UINTN PendingLength;
+ UINTN Length;
+ EFI_FV_BLOCK_MAP_ENTRY *PtrMap;
+ UINTN NumOfBlocks;
+ UINTN Index;
+ UINT8 *UpdateBuffer;
+
+ if ((ConfigData->UpdateType != UpdateWholeFV)
+ || (!ConfigData->FaultTolerant)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Get the FTW protocol
+ //
+ Status = gBS->LocateProtocol (
+ &gEfiFaultTolerantWriteProtocolGuid,
+ NULL,
+ (VOID **) &FtwProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Get the maximum block size of the FV, and number of blocks
+ // NumOfBlocks will be the NumOfUdpates.
+ //
+ MaxBlockSize = 0;
+ NumOfBlocks = 0;
+ PtrMap = BlockMap;
+ while (TRUE) {
+ if ((PtrMap->NumBlocks == 0) || (PtrMap->Length == 0)) {
+ break;
+ }
+ if (MaxBlockSize < PtrMap->Length) {
+ MaxBlockSize = PtrMap->Length;
+ }
+ NumOfBlocks = NumOfBlocks + PtrMap->NumBlocks;
+ PtrMap++;
+ }
+
+ FtwProtocol->GetMaxBlockSize (FtwProtocol, &FtwMaxBlockSize);
+ //
+ // Not enough backup space. return directly
+ //
+ if (FtwMaxBlockSize < MaxBlockSize) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ PendingLba = 0;
+ PendingOffset = 0;
+ PendingLength = 0;
+ Pending = FALSE;
+
+ //
+ // Fault Tolerant Write can only support actual fault tolerance if the write
+ // is a reclaim operation, which means the data buffer (new and old) are
+ // acutally both stored in flash. But for component update write, the data
+ // are now in memory. So we cannot actually recover the data after power
+ // failure.
+ //
+ Status = RetrieveLastWrite (
+ FvbHandle,
+ FtwProtocol,
+ ConfigData,
+ sizeof (UPDATE_PRIVATE_DATA),
+ &PrivateData,
+ &PendingLba,
+ &PendingOffset,
+ &PendingLength,
+ &Pending
+ );
+
+ if (Pending && (Status == EFI_NOT_FOUND)) {
+ //
+ // Cannot continue with the write operation
+ //
+ return EFI_ABORTED;
+ }
+
+ if (EFI_ERROR(Status)) {
+ return EFI_ABORTED;
+ }
+
+ //
+ // Currently we start from the pending write if there is any. But as we
+ // are going to update a whole FV, we can just abort last write and start
+ // from the very begining.
+ //
+ if (!Pending) {
+ //
+ // Now allocte the update private data in FTW. If there is pending
+ // write, it has already been allocated and no need to allocate here.
+ //
+ Status = FtwProtocol->Allocate (
+ FtwProtocol,
+ &gEfiCallerIdGuid,
+ sizeof (UPDATE_PRIVATE_DATA),
+ NumOfBlocks
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ //
+ // Perform the update now. If there are pending writes, we need to
+ // start from the pending write instead of the very beginning.
+ //
+ PtrMap = BlockMap;
+ Lba = 0;
+ Offset = 0;
+ UpdateBuffer = ImageBuffer;
+ CopyMem (
+ (VOID *) &PrivateData.FileGuid,
+ (VOID *) &ConfigData->FileGuid,
+ sizeof (EFI_GUID)
+ );
+
+ while (TRUE) {
+ if ((PtrMap->NumBlocks == 0) || (PtrMap->Length == 0)) {
+ break;
+ }
+ Length = (UINTN)PtrMap->Length;
+ for (Index = 0; Index < PtrMap->NumBlocks; Index++) {
+
+ //
+ // Add an extra check here to see if the pending record is correct
+ //
+ if (Pending && (Lba == PendingLba)) {
+ if ((PendingOffset != Offset) || (PendingLength != Length)) {
+ //
+ // Error.
+ //
+ Status = EFI_ABORTED;
+ break;
+ }
+ }
+
+ if ((!Pending) || (Lba >= PendingLba)) {
+ Status = FtwProtocol->Write (
+ FtwProtocol,
+ Lba, // Lba
+ Offset, // Offset
+ Length, // Size
+ &PrivateData, // Private Data
+ FvbHandle, // FVB handle
+ UpdateBuffer // Buffer
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ Lba++;
+ UpdateBuffer = (UINT8 *) ((UINTN)UpdateBuffer + Length);
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ PtrMap++;
+ }
+
+ return Status;
+
+}
+
+/**
+ Directly update the whole FV image without fault tolerant write method.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param BlockMap Block array to specify flash area.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+
+ @retval EFI_SUCCESS FV image is writed into flash.
+ @retval EFI_INVALID_PARAMETER Config data is not valid.
+ @retval EFI_ABORTED Error happen when update FV.
+
+**/
+EFI_STATUS
+NonFaultTolerantUpdateOnWholeFv (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_FV_BLOCK_MAP_ENTRY *BlockMap,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_FV_BLOCK_MAP_ENTRY *PtrMap;
+ UINTN Index;
+ EFI_LBA UpdateLba;
+ UINT8 *UpdateBuffer;
+ UINTN UpdateSize;
+
+ if ((ConfigData->UpdateType != UpdateWholeFV )
+ || (ConfigData->FaultTolerant)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status = EFI_SUCCESS;
+ PtrMap = BlockMap;
+ UpdateLba = 0;
+ UpdateBuffer = ImageBuffer;
+
+ //
+ // Perform the update now
+ //
+ while (TRUE) {
+ if ((PtrMap->NumBlocks == 0) || (PtrMap->Length == 0)) {
+ break;
+ }
+ UpdateSize = (UINTN)PtrMap->Length;
+ for (Index = 0; Index < PtrMap->NumBlocks; Index++) {
+ Status = UpdateOneBlock (
+ FvbProtocol,
+ UpdateLba,
+ UpdateSize,
+ UpdateBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ UpdateLba++;
+ UpdateBuffer = (UINT8 *) ((UINTN)UpdateBuffer + UpdateSize);
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ PtrMap++;
+ }
+
+ return Status;
+}
+
+/**
+ Update the whole FV image, and reinsall FVB protocol for the updated FV image.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+
+ @retval EFI_INVALID_PARAMETER Update type is not UpdateWholeFV.
+ Or Image size is not same to the size of whole FV.
+ @retval EFI_OUT_OF_RESOURCES No enoug memory is allocated.
+ @retval EFI_SUCCESS FV image is updated, and its FVB protocol is reinstalled.
+
+**/
+EFI_STATUS
+PerformUpdateOnWholeFv (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize
+)
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;
+ CHAR16 *TmpStr;
+
+ if (ConfigData->UpdateType != UpdateWholeFV) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Get the header of the firmware volume
+ //
+ FwVolHeader = NULL;
+ FwVolHeader = AllocatePool (((EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) (ConfigData->BaseAddress)))->HeaderLength);
+ if (FwVolHeader == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (
+ FwVolHeader,
+ (VOID *) ((UINTN) (ConfigData->BaseAddress)),
+ ((EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) (ConfigData->BaseAddress)))->HeaderLength
+ );
+
+ //
+ // Check if ImageSize is the same as the size of the whole FV
+ //
+ if ((UINT64)ImageSize != FwVolHeader->FvLength) {
+ FreePool (FwVolHeader);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Print on screen
+ //
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_FIRMWARE_VOLUME), NULL);
+ if (TmpStr != NULL) {
+ Print (TmpStr, ConfigData->BaseAddress, (FwVolHeader->FvLength + ConfigData->BaseAddress));
+ FreePool (TmpStr);
+ }
+
+ DEBUG ((EFI_D_UPDATE, "UpdateDriver: updating whole FV from %08LX to %08LX\n",
+ ConfigData->BaseAddress, (FwVolHeader->FvLength + ConfigData->BaseAddress)));
+
+ //
+ // Get the block map of the firmware volume
+ //
+ BlockMap = &(FwVolHeader->BlockMap[0]);
+
+ //
+ // It is about the same if we are going to fault tolerantly update
+ // a certain FV in our current design. But we divide non-fault tolerant
+ // and fault tolerant udpate here for better maintenance as fault
+ // tolerance may change and may be done more wisely if we have space.
+ //
+ if (ConfigData->FaultTolerant) {
+ Status = FaultTolerantUpdateOnWholeFv (
+ FvbHandle,
+ FvbProtocol,
+ BlockMap,
+ ConfigData,
+ ImageBuffer,
+ ImageSize
+ );
+ } else {
+ Status = NonFaultTolerantUpdateOnWholeFv (
+ FvbHandle,
+ FvbProtocol,
+ BlockMap,
+ ConfigData,
+ ImageBuffer,
+ ImageSize
+ );
+ }
+
+ FreePool (FwVolHeader);
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // As the whole FV has been replaced, the FV driver shall re-parse the
+ // firmware volume. So re-install FVB protocol here
+ //
+ Status = gBS->ReinstallProtocolInterface (
+ FvbHandle,
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ FvbProtocol,
+ FvbProtocol
+ );
+
+ return Status;
+}
+
+/**
+ Update certain file in the FV.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+ @param FileType FFS file type.
+ @param FileAttributes FFS file attribute
+
+ @retval EFI_INVALID_PARAMETER Update type is not UpdateFvFile.
+ Or Image size is not same to the size of whole FV.
+ @retval EFI_UNSUPPORTED PEIM FFS is unsupported to be updated.
+ @retval EFI_SUCCESS The FFS file is added into FV.
+
+**/
+EFI_STATUS
+PerformUpdateOnFvFile (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *FwVolProtocol;
+ EFI_FV_WRITE_FILE_DATA FileData;
+ CHAR16 *TmpStr;
+
+ if (ConfigData->UpdateType != UpdateFvFile) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Print on screen
+ //
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_FIRMWARE_VOLUME_FILE), NULL);
+ if (TmpStr != NULL) {
+ Print (TmpStr, &(ConfigData->FileGuid));
+ FreePool (TmpStr);
+ }
+
+ DEBUG ((EFI_D_UPDATE, "UpdateDriver: updating file: %g\n",
+ &(ConfigData->FileGuid)));
+
+ //
+ // Get Firmware volume protocol on this FVB protocol
+ //
+ Status = gBS->HandleProtocol (
+ FvbHandle,
+ &gEfiFirmwareVolume2ProtocolGuid,
+ (VOID **) &FwVolProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // If it is a PEIM, we need first to rebase it before committing
+ // the write to target
+ //
+ if ((FileType == EFI_FV_FILETYPE_PEI_CORE) || (FileType == EFI_FV_FILETYPE_PEIM )
+ || (FileType == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ FileData.NameGuid = &(ConfigData->FileGuid);
+ FileData.Type = FileType;
+ FileData.FileAttributes = FileAttributes;
+ FileData.Buffer = ImageBuffer;
+ FileData.BufferSize = (UINT32) ImageSize;
+
+ Status = FwVolProtocol->WriteFile (
+ FwVolProtocol,
+ 1, // NumberOfFiles
+ (EFI_FV_WRITE_POLICY)ConfigData->FaultTolerant,
+ &FileData
+ );
+ return Status;
+}
+
+/**
+ Update the buffer into flash area in fault tolerant write method.
+
+ @param ImageBuffer Image buffer to be updated.
+ @param SizeLeft Size of the image buffer.
+ @param UpdatedSize Size of the updated buffer.
+ @param ConfigData Config data on updating driver.
+ @param FlashAddress Flash address to be updated as start address.
+ @param FvbProtocol FVB protocol.
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+
+ @retval EFI_SUCCESS Buffer data is updated into flash.
+ @retval EFI_INVALID_PARAMETER Base flash address is not in FVB flash area.
+ @retval EFI_NOT_FOUND FTW protocol doesn't exist.
+ @retval EFI_OUT_OF_RESOURCES No enough backup space.
+ @retval EFI_ABORTED Error happen when update flash area.
+
+**/
+EFI_STATUS
+FaultTolerantUpdateOnPartFv (
+ IN UINT8 *ImageBuffer,
+ IN UINTN SizeLeft,
+ IN OUT UINTN *UpdatedSize,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN EFI_PHYSICAL_ADDRESS FlashAddress,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_HANDLE FvbHandle
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeaderTmp;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_PHYSICAL_ADDRESS FvBase;
+ EFI_PHYSICAL_ADDRESS NextBlock;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;
+ EFI_FV_BLOCK_MAP_ENTRY *PtrMap;
+ UINTN NumOfUpdates;
+ UINTN TotalSize;
+ EFI_PHYSICAL_ADDRESS StartAddress;
+ EFI_FAULT_TOLERANT_WRITE_PROTOCOL *FtwProtocol;
+ UINTN MaxBlockSize;
+ UINTN FtwMaxBlockSize;
+ BOOLEAN Pending;
+ UPDATE_PRIVATE_DATA PrivateData;
+ EFI_LBA PendingLba;
+ EFI_LBA Lba;
+ UINTN BlockSize;
+ UINTN PendingOffset;
+ UINTN Offset;
+ UINTN PendingLength;
+ UINTN Length;
+ UINTN Index;
+ UINT8 *Image;
+
+ //
+ // Get the block map to update the block one by one
+ //
+ Status = FvbProtocol->GetPhysicalAddress (
+ FvbProtocol,
+ &FvBase
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ FwVolHeaderTmp = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;
+ if ((FlashAddress < FvBase) || (FlashAddress > (FvBase + FwVolHeaderTmp->FvLength))) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)AllocateCopyPool (
+ FwVolHeaderTmp->HeaderLength,
+ FwVolHeaderTmp
+ );
+ if (FwVolHeader == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // For fault tolerant write, we have to know how many blocks we need to
+ // update. So we will calculate number of updates and max block size first
+ //
+ NumOfUpdates = 0;
+ MaxBlockSize = 0;
+ TotalSize = SizeLeft;
+ StartAddress = FlashAddress;
+ BaseAddress = FvBase;
+ BlockMap = &(FwVolHeader->BlockMap[0]);
+ PtrMap = BlockMap;
+
+ while (TotalSize > 0) {
+ if ((PtrMap->NumBlocks == 0) || (PtrMap->Length == 0)) {
+ break;
+ }
+
+ BlockSize = PtrMap->Length;
+ for (Index = 0; Index < PtrMap->NumBlocks; Index++) {
+ NextBlock = BaseAddress + BlockSize;
+ //
+ // Check if this block need to be updated
+ //
+ if ((StartAddress >= BaseAddress) && (StartAddress < NextBlock)) {
+ //
+ // Get the maximum block size
+ //
+ if (MaxBlockSize < BlockSize) {
+ MaxBlockSize = BlockSize;
+ }
+
+ //
+ // This block shall be udpated. So increment number of updates
+ //
+ NumOfUpdates++;
+ Offset = (UINTN) (StartAddress - BaseAddress);
+ Length = TotalSize;
+ if ((Length + Offset ) > BlockSize) {
+ Length = BlockSize - Offset;
+ }
+
+ StartAddress = StartAddress + Length;
+ TotalSize = TotalSize - Length;
+ if (TotalSize <= 0) {
+ break;
+ }
+ }
+ BaseAddress = NextBlock;
+ }
+ PtrMap++;
+ }
+
+ //
+ // Get the FTW protocol
+ //
+ Status = gBS->LocateProtocol (
+ &gEfiFaultTolerantWriteProtocolGuid,
+ NULL,
+ (VOID **) &FtwProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (FwVolHeader);
+ return EFI_NOT_FOUND;
+ }
+
+ FtwProtocol->GetMaxBlockSize (FtwProtocol, &FtwMaxBlockSize);
+
+ //
+ // Not enough backup space. return directly
+ //
+ if (FtwMaxBlockSize < MaxBlockSize) {
+ FreePool (FwVolHeader);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ PendingLba = 0;
+ PendingOffset = 0;
+ PendingLength = 0;
+ Pending = FALSE;
+
+ //
+ // Fault Tolerant Write can only support actual fault tolerance if the write
+ // is a reclaim operation, which means the data buffer (new and old) are
+ // acutally both stored in flash. But for component update write, the data
+ // are now in memory. So we cannot actually recover the data after power
+ // failure.
+ //
+ Status = RetrieveLastWrite (
+ FvbHandle,
+ FtwProtocol,
+ ConfigData,
+ sizeof (UPDATE_PRIVATE_DATA),
+ &PrivateData,
+ &PendingLba,
+ &PendingOffset,
+ &PendingLength,
+ &Pending
+ );
+ if (Pending && (Status == EFI_NOT_FOUND)) {
+ //
+ // I'm not the owner of the pending fault tolerant write record
+ // Cannot continue with the write operation
+ //
+ FreePool (FwVolHeader);
+ return EFI_ABORTED;
+ }
+
+ if (EFI_ERROR(Status)) {
+ FreePool (FwVolHeader);
+ return EFI_ABORTED;
+ }
+
+ //
+ // Currently we start from the pending write if there is any. But if the
+ // caller is exactly the same, and the new data is already a in memory, (it
+ // cannot be stored in flash in last write,) we can just abort last write
+ // and start from the very begining.
+ //
+ if (!Pending) {
+ //
+ // Now allocte the update private data in FTW. If there is pending
+ // write, it has already been allocated and no need to allocate here.
+ //
+ Status = FtwProtocol->Allocate (
+ FtwProtocol,
+ &gEfiCallerIdGuid,
+ sizeof (UPDATE_PRIVATE_DATA),
+ NumOfUpdates
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (FwVolHeader);
+ return Status;
+ }
+ }
+
+ //
+ // Perform the update now. If there are pending writes, we need to
+ // start from the pending write instead of the very beginning.
+ //
+ TotalSize = SizeLeft;
+ Lba = 0;
+ StartAddress = FlashAddress;
+ BaseAddress = FvBase;
+ PtrMap = BlockMap;
+ Image = ImageBuffer;
+ CopyMem (
+ (VOID *) &PrivateData.FileGuid,
+ (VOID *) &ConfigData->FileGuid,
+ sizeof (EFI_GUID)
+ );
+
+ while (TotalSize > 0) {
+ if ((PtrMap->NumBlocks == 0) || (PtrMap->Length == 0)) {
+ break;
+ }
+
+ BlockSize = (UINTN)PtrMap->Length;
+ for (Index = 0; Index < PtrMap->NumBlocks; Index++) {
+ NextBlock = BaseAddress + BlockSize;
+ if ((StartAddress >= BaseAddress) && (StartAddress < NextBlock)) {
+ //
+ // So we need to update this block
+ //
+ Offset = (UINTN) (StartAddress - BaseAddress);
+ Length = TotalSize;
+ if ((Length + Offset ) > BlockSize) {
+ Length = BlockSize - Offset;
+ }
+
+ //
+ // Add an extra check here to see if the pending record is correct
+ //
+ if (Pending && (Lba == PendingLba)) {
+ if ((PendingOffset != Offset) || (PendingLength != Length)) {
+ //
+ // Error.
+ //
+ Status = EFI_ABORTED;
+ break;
+ }
+ }
+
+ if ((!Pending) || (Lba >= PendingLba)) {
+ DEBUG ((EFI_D_UPDATE, "Update Flash area from %08LX to %08LX\n", StartAddress, (UINT64)StartAddress + Length));
+ Status = FtwProtocol->Write (
+ FtwProtocol,
+ Lba, // Lba
+ Offset, // Offset
+ Length, // Size
+ &PrivateData, // Private Data
+ FvbHandle, // FVB handle
+ Image // Buffer
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+
+ //
+ // Now increment StartAddress, ImageBuffer and decrease the
+ // left size to prepare for the next block update.
+ //
+ StartAddress = StartAddress + Length;
+ Image = Image + Length;
+ TotalSize = TotalSize - Length;
+ if (TotalSize <= 0) {
+ break;
+ }
+ }
+ BaseAddress = NextBlock;
+ Lba++;
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ PtrMap++;
+ }
+
+ FreePool (FwVolHeader);
+
+ *UpdatedSize = SizeLeft - TotalSize;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Directly update the buffer into flash area without fault tolerant write method.
+
+ @param ImageBuffer Image buffer to be updated.
+ @param SizeLeft Size of the image buffer.
+ @param UpdatedSize Size of the updated buffer.
+ @param FlashAddress Flash address to be updated as start address.
+ @param FvbProtocol FVB protocol.
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+
+ @retval EFI_SUCCESS Buffer data is updated into flash.
+ @retval EFI_INVALID_PARAMETER Base flash address is not in FVB flash area.
+ @retval EFI_OUT_OF_RESOURCES No enough backup space.
+
+**/
+EFI_STATUS
+NonFaultTolerantUpdateOnPartFv (
+ IN UINT8 *ImageBuffer,
+ IN UINTN SizeLeft,
+ IN OUT UINTN *UpdatedSize,
+ IN EFI_PHYSICAL_ADDRESS FlashAddress,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_HANDLE FvbHandle
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeaderTmp;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_PHYSICAL_ADDRESS NextBlock;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;
+ UINTN Index;
+ UINTN TotalSize;
+ UINTN BlockSize;
+ EFI_LBA Lba;
+ UINTN Offset;
+ UINTN Length;
+ UINT8 *Image;
+
+ //
+ // Get the block map to update the block one by one
+ //
+ Status = FvbProtocol->GetPhysicalAddress (
+ FvbProtocol,
+ &BaseAddress
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ FwVolHeaderTmp = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;
+ if ((FlashAddress < BaseAddress) || (FlashAddress > ( BaseAddress + FwVolHeaderTmp->FvLength ))) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)AllocateCopyPool (
+ FwVolHeaderTmp->HeaderLength,
+ FwVolHeaderTmp
+ );
+ if (FwVolHeader == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Image = ImageBuffer;
+ TotalSize = SizeLeft;
+ BlockMap = &(FwVolHeader->BlockMap[0]);
+ Lba = 0;
+
+ while (TotalSize > 0) {
+ if ((BlockMap->NumBlocks == 0) || (BlockMap->Length == 0)) {
+ break;
+ }
+
+ BlockSize = BlockMap->Length;
+ for (Index = 0 ; Index < BlockMap->NumBlocks ; Index++) {
+ NextBlock = BaseAddress + BlockSize;
+ if ((FlashAddress >= BaseAddress) && (FlashAddress < NextBlock)) {
+ //
+ // So we need to update this block
+ //
+ Offset = (UINTN) FlashAddress - (UINTN) BaseAddress;
+ Length = TotalSize;
+ if ((Length + Offset ) > BlockSize) {
+ Length = BlockSize - Offset;
+ }
+
+ DEBUG ((EFI_D_UPDATE, "Update Flash area from %08LX to %08LX\n", FlashAddress, (UINT64)FlashAddress + Length));
+ //
+ // Update the block
+ //
+ Status = UpdateBufferInOneBlock (
+ FvbProtocol,
+ Lba,
+ Offset,
+ Length,
+ BlockSize,
+ Image
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (FwVolHeader);
+ return Status;
+ }
+
+ //
+ // Now increment FlashAddress, ImageBuffer and decrease the
+ // left size to prepare for the next block update.
+ //
+ FlashAddress = FlashAddress + Length;
+ Image = Image + Length;
+ TotalSize = TotalSize - Length;
+ if (TotalSize <= 0) {
+ break;
+ }
+ }
+ BaseAddress = NextBlock;
+ Lba++;
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ BlockMap++;
+ }
+
+ FreePool (FwVolHeader);
+
+ *UpdatedSize = SizeLeft - TotalSize;
+
+ return EFI_SUCCESS;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/ParseUpdateProfile.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/ParseUpdateProfile.c
new file mode 100644
index 0000000000..023506e6ee
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/ParseUpdateProfile.c
@@ -0,0 +1,1133 @@
+/** @file
+ Source file for the component update driver. It parse the update
+ configuration file and pass the information to the update driver
+ so that the driver can perform updates accordingly.
+
+ Copyright (c) 2002 - 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.
+
+**/
+
+#include "UpdateDriver.h"
+
+/**
+ Copy one line data from buffer data to the line buffer.
+
+ @param Buffer Buffer data.
+ @param BufferSize Buffer Size.
+ @param LineBuffer Line buffer to store the found line data.
+ @param LineSize On input, size of the input line buffer.
+ On output, size of the actual line buffer.
+
+ @retval EFI_BUFFER_TOO_SMALL The size of input line buffer is not enough.
+ @retval EFI_SUCCESS Copy line data into the line buffer.
+
+**/
+EFI_STATUS
+ProfileGetLine (
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize,
+ IN OUT UINT8 *LineBuffer,
+ IN OUT UINTN *LineSize
+ )
+{
+ UINTN Length;
+ UINT8 *PtrBuf;
+ UINTN PtrEnd;
+
+ PtrBuf = Buffer;
+ PtrEnd = (UINTN)Buffer + BufferSize;
+
+ //
+ // 0x0D indicates a line break. Otherwise there is no line break
+ //
+ while ((UINTN)PtrBuf < PtrEnd) {
+ if (*PtrBuf == 0x0D) {
+ break;
+ }
+ PtrBuf++;
+ }
+
+ if ((UINTN)PtrBuf >= (PtrEnd - 1)) {
+ //
+ // The buffer ends without any line break
+ // or it is the last character of the buffer
+ //
+ Length = BufferSize;
+ } else if (*(PtrBuf + 1) == 0x0A) {
+ //
+ // Further check if a 0x0A follows. If yes, count 0xA
+ //
+ Length = (UINTN) PtrBuf - (UINTN) Buffer + 2;
+ } else {
+ Length = (UINTN) PtrBuf - (UINTN) Buffer + 1;
+ }
+
+ if (Length > (*LineSize)) {
+ *LineSize = Length;
+ return EFI_BUFFER_TOO_SMALL;
+ }
+
+ SetMem (LineBuffer, *LineSize, 0x0);
+ *LineSize = Length;
+ CopyMem (LineBuffer, Buffer, Length);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Trim Buffer by removing all CR, LF, TAB, and SPACE chars in its head and tail.
+
+ @param Buffer On input, buffer data to be trimed.
+ On output, the trimmed buffer.
+ @param BufferSize On input, size of original buffer data.
+ On output, size of the trimmed buffer.
+
+**/
+VOID
+ProfileTrim (
+ IN OUT UINT8 *Buffer,
+ IN OUT UINTN *BufferSize
+ )
+{
+ UINTN Length;
+ UINT8 *PtrBuf;
+ UINT8 *PtrEnd;
+
+ if (*BufferSize == 0) {
+ return;
+ }
+
+ //
+ // Trim the tail first, include CR, LF, TAB, and SPACE.
+ //
+ Length = *BufferSize;
+ PtrBuf = (UINT8 *) ((UINTN) Buffer + Length - 1);
+ while (PtrBuf >= Buffer) {
+ if ((*PtrBuf != 0x0D) && (*PtrBuf != 0x0A )
+ && (*PtrBuf != 0x20) && (*PtrBuf != 0x09)) {
+ break;
+ }
+ PtrBuf --;
+ }
+
+ //
+ // all spaces, a blank line, return directly;
+ //
+ if (PtrBuf < Buffer) {
+ *BufferSize = 0;
+ return;
+ }
+
+ Length = (UINTN)PtrBuf - (UINTN)Buffer + 1;
+ PtrEnd = PtrBuf;
+ PtrBuf = Buffer;
+
+ //
+ // Now skip the heading CR, LF, TAB and SPACE
+ //
+ while (PtrBuf <= PtrEnd) {
+ if ((*PtrBuf != 0x0D) && (*PtrBuf != 0x0A )
+ && (*PtrBuf != 0x20) && (*PtrBuf != 0x09)) {
+ break;
+ }
+ PtrBuf++;
+ }
+
+ //
+ // If no heading CR, LF, TAB or SPACE, directly return
+ //
+ if (PtrBuf == Buffer) {
+ *BufferSize = Length;
+ return;
+ }
+
+ *BufferSize = (UINTN)PtrEnd - (UINTN)PtrBuf + 1;
+
+ //
+ // The first Buffer..PtrBuf characters are CR, LF, TAB or SPACE.
+ // Now move out all these characters.
+ //
+ while (PtrBuf <= PtrEnd) {
+ *Buffer = *PtrBuf;
+ Buffer++;
+ PtrBuf++;
+ }
+
+ return;
+}
+
+/**
+ Insert new comment item into comment head.
+
+ @param Buffer Comment buffer to be added.
+ @param BufferSize Size of comment buffer.
+ @param CommentHead Comment Item head entry.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS New comment item is inserted.
+
+**/
+EFI_STATUS
+ProfileGetComments (
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize,
+ IN OUT COMMENT_LINE **CommentHead
+ )
+{
+ COMMENT_LINE *CommentItem;
+
+ CommentItem = NULL;
+ CommentItem = AllocatePool (sizeof (COMMENT_LINE));
+ if (CommentItem == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ CommentItem->ptrNext = *CommentHead;
+ *CommentHead = CommentItem;
+
+ //
+ // Add a trailing '\0'
+ //
+ CommentItem->ptrComment = AllocatePool (BufferSize + 1);
+ if (CommentItem->ptrComment == NULL) {
+ FreePool (CommentItem);
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (CommentItem->ptrComment, Buffer, BufferSize);
+ *(CommentItem->ptrComment + BufferSize) = '\0';
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Add new section item into Section head.
+
+ @param Buffer Section item data buffer.
+ @param BufferSize Size of section item.
+ @param SectionHead Section item head entry.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS Section item is NULL or Section item is added.
+
+**/
+EFI_STATUS
+ProfileGetSection (
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize,
+ IN OUT SECTION_ITEM **SectionHead
+ )
+{
+ EFI_STATUS Status;
+ SECTION_ITEM *SectionItem;
+ UINTN Length;
+ UINT8 *PtrBuf;
+
+ Status = EFI_SUCCESS;
+ //
+ // The first character of Buffer is '[', now we want for ']'
+ //
+ PtrBuf = (UINT8 *)((UINTN)Buffer + BufferSize - 1);
+ while (PtrBuf > Buffer) {
+ if (*PtrBuf == ']') {
+ break;
+ }
+ PtrBuf --;
+ }
+ if (PtrBuf <= Buffer) {
+ //
+ // Not found. Omit this line
+ //
+ return Status;
+ }
+
+ //
+ // excluding the heading '[' and tailing ']'
+ //
+ Length = PtrBuf - Buffer - 1;
+ ProfileTrim (
+ Buffer + 1,
+ &Length
+ );
+
+ //
+ // omit this line if the section name is null
+ //
+ if (Length == 0) {
+ return Status;
+ }
+
+ SectionItem = AllocatePool (sizeof (SECTION_ITEM));
+ if (SectionItem == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ SectionItem->ptrSection = NULL;
+ SectionItem->SecNameLen = Length;
+ SectionItem->ptrEntry = NULL;
+ SectionItem->ptrValue = NULL;
+ SectionItem->ptrNext = *SectionHead;
+ *SectionHead = SectionItem;
+
+ //
+ // Add a trailing '\0'
+ //
+ SectionItem->ptrSection = AllocatePool (Length + 1);
+ if (SectionItem->ptrSection == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // excluding the heading '['
+ //
+ CopyMem (SectionItem->ptrSection, Buffer + 1, Length);
+ *(SectionItem->ptrSection + Length) = '\0';
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Add new section entry and entry value into Section head.
+
+ @param Buffer Section entry data buffer.
+ @param BufferSize Size of section entry.
+ @param SectionHead Section item head entry.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS Section entry is NULL or Section entry is added.
+
+**/
+EFI_STATUS
+ProfileGetEntry (
+ IN UINT8 *Buffer,
+ IN UINTN BufferSize,
+ IN OUT SECTION_ITEM **SectionHead
+ )
+{
+ EFI_STATUS Status;
+ SECTION_ITEM *SectionItem;
+ SECTION_ITEM *PtrSection;
+ UINTN Length;
+ UINT8 *PtrBuf;
+ UINT8 *PtrEnd;
+
+ Status = EFI_SUCCESS;
+ PtrBuf = Buffer;
+ PtrEnd = (UINT8 *) ((UINTN)Buffer + BufferSize - 1);
+
+ //
+ // First search for '='
+ //
+ while (PtrBuf <= PtrEnd) {
+ if (*PtrBuf == '=') {
+ break;
+ }
+ PtrBuf++;
+ }
+ if (PtrBuf > PtrEnd) {
+ //
+ // Not found. Omit this line
+ //
+ return Status;
+ }
+
+ //
+ // excluding the tailing '='
+ //
+ Length = PtrBuf - Buffer;
+ ProfileTrim (
+ Buffer,
+ &Length
+ );
+
+ //
+ // Omit this line if the entry name is null
+ //
+ if (Length == 0) {
+ return Status;
+ }
+
+ //
+ // Omit this line if no section header has been found before
+ //
+ if (*SectionHead == NULL) {
+ return Status;
+ }
+ PtrSection = *SectionHead;
+
+ SectionItem = AllocatePool (sizeof (SECTION_ITEM));
+ if (SectionItem == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ SectionItem->ptrSection = NULL;
+ SectionItem->ptrEntry = NULL;
+ SectionItem->ptrValue = NULL;
+ SectionItem->SecNameLen = PtrSection->SecNameLen;
+ SectionItem->ptrNext = *SectionHead;
+ *SectionHead = SectionItem;
+
+ //
+ // SectionName, add a trailing '\0'
+ //
+ SectionItem->ptrSection = AllocatePool (PtrSection->SecNameLen + 1);
+ if (SectionItem->ptrSection == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (SectionItem->ptrSection, PtrSection->ptrSection, PtrSection->SecNameLen + 1);
+
+ //
+ // EntryName, add a trailing '\0'
+ //
+ SectionItem->ptrEntry = AllocatePool (Length + 1);
+ if (SectionItem->ptrEntry == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (SectionItem->ptrEntry, Buffer, Length);
+ *(SectionItem->ptrEntry + Length) = '\0';
+
+ //
+ // Next search for '#'
+ //
+ PtrBuf = PtrBuf + 1;
+ Buffer = PtrBuf;
+ while (PtrBuf <= PtrEnd) {
+ if (*PtrBuf == '#') {
+ break;
+ }
+ PtrBuf++;
+ }
+ Length = PtrBuf - Buffer;
+ ProfileTrim (
+ Buffer,
+ &Length
+ );
+
+ if (Length > 0) {
+ //
+ // EntryValue, add a trailing '\0'
+ //
+ SectionItem->ptrValue = AllocatePool (Length + 1);
+ if (SectionItem->ptrValue == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (SectionItem->ptrValue, Buffer, Length);
+ *(SectionItem->ptrValue + Length) = '\0';
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Free all comment entry and section entry.
+
+ @param Section Section entry list.
+ @param Comment Comment entry list.
+
+**/
+VOID
+FreeAllList (
+ IN SECTION_ITEM *Section,
+ IN COMMENT_LINE *Comment
+ )
+{
+ SECTION_ITEM *PtrSection;
+ COMMENT_LINE *PtrComment;
+
+ while (Section != NULL) {
+ PtrSection = Section;
+ Section = Section->ptrNext;
+ if (PtrSection->ptrEntry != NULL) {
+ FreePool (PtrSection->ptrEntry);
+ }
+ if (PtrSection->ptrSection != NULL) {
+ FreePool (PtrSection->ptrSection);
+ }
+ if (PtrSection->ptrValue != NULL) {
+ FreePool (PtrSection->ptrValue);
+ }
+ FreePool (PtrSection);
+ }
+
+ while (Comment != NULL) {
+ PtrComment = Comment;
+ Comment = Comment->ptrNext;
+ if (PtrComment->ptrComment != NULL) {
+ FreePool (PtrComment->ptrComment);
+ }
+ FreePool (PtrComment);
+ }
+
+ return;
+}
+
+/**
+ Get section entry value.
+
+ @param Section Section entry list.
+ @param SectionName Section name.
+ @param EntryName Section entry name.
+ @param EntryValue Point to the got entry value.
+
+ @retval EFI_NOT_FOUND Section is not found.
+ @retval EFI_SUCCESS Section entry value is got.
+
+**/
+EFI_STATUS
+UpdateGetProfileString (
+ IN SECTION_ITEM *Section,
+ IN UINT8 *SectionName,
+ IN UINT8 *EntryName,
+ OUT UINT8 **EntryValue
+ )
+{
+ *EntryValue = NULL;
+
+ while (Section != NULL) {
+ if (AsciiStrCmp ((CONST CHAR8 *) Section->ptrSection, (CONST CHAR8 *) SectionName) == 0) {
+ if (Section->ptrEntry != NULL) {
+ if (AsciiStrCmp ((CONST CHAR8 *) Section->ptrEntry, (CONST CHAR8 *) EntryName) == 0) {
+ break;
+ }
+ }
+ }
+ Section = Section->ptrNext;
+ }
+
+ if (Section == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ *EntryValue = (UINT8 *) Section->ptrValue;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Convert the dec or hex ascii string to value.
+
+ @param Str ascii string to be converted.
+
+ @return the converted value.
+
+**/
+UINTN
+UpdateAtoi (
+ IN UINT8 *Str
+ )
+{
+ UINTN Number;
+
+ Number = 0;
+
+ //
+ // Skip preceeding while spaces
+ //
+ while (*Str != '\0') {
+ if (*Str != 0x20) {
+ break;
+ }
+ Str++;
+ }
+
+ if (*Str == '\0') {
+ return Number;
+ }
+
+ //
+ // Find whether the string is prefixed by 0x.
+ // That is, it should be xtoi or atoi.
+ //
+ if (*Str == '0') {
+ if ((*(Str+1) == 'x' ) || ( *(Str+1) == 'X')) {
+ return AsciiStrHexToUintn ((CONST CHAR8 *) Str);
+ }
+ }
+
+ while (*Str != '\0') {
+ if ((*Str >= '0') && (*Str <= '9')) {
+ Number = Number * 10 + *Str - '0';
+ } else {
+ break;
+ }
+ Str++;
+ }
+
+ return Number;
+}
+
+/**
+ Converts a decimal value to a Null-terminated ascii string.
+
+ @param Buffer Pointer to the output buffer for the produced Null-terminated
+ ASCII string.
+ @param Value The 64-bit sgned value to convert to a string.
+
+ @return The number of ASCII characters in Buffer not including the Null-terminator.
+
+**/
+UINTN
+UpdateValueToString (
+ IN OUT UINT8 *Buffer,
+ IN INT64 Value
+ )
+{
+ UINT8 TempBuffer[30];
+ UINT8 *TempStr;
+ UINT8 *BufferPtr;
+ UINTN Count;
+ UINT32 Remainder;
+
+ TempStr = TempBuffer;
+ BufferPtr = Buffer;
+ Count = 0;
+
+ if (Value < 0) {
+ *BufferPtr = '-';
+ BufferPtr++;
+ Value = -Value;
+ Count++;
+ }
+
+ do {
+ Value = (INT64) DivU64x32Remainder ((UINT64)Value, 10, &Remainder);
+ //
+ // The first item of TempStr is not occupied. It's kind of flag
+ //
+ TempStr++;
+ Count++;
+ *TempStr = (UINT8) ((UINT8)Remainder + '0');
+ } while (Value != 0);
+
+ //
+ // Reverse temp string into Buffer.
+ //
+ while (TempStr != TempBuffer) {
+ *BufferPtr = *TempStr;
+ BufferPtr++;
+ TempStr --;
+ }
+
+ *BufferPtr = 0;
+
+ return Count;
+}
+
+/**
+ Convert the input value to a ascii string,
+ and concatenates this string to the input string.
+
+ @param Str Pointer to a Null-terminated ASCII string.
+ @param Number The unsgned value to convert to a string.
+
+**/
+VOID
+UpdateStrCatNumber (
+ IN OUT UINT8 *Str,
+ IN UINTN Number
+ )
+{
+ UINTN Count;
+
+ while (*Str != '\0') {
+ Str++;
+ }
+
+ Count = UpdateValueToString (Str, (INT64)Number);
+
+ *(Str + Count) = '\0';
+
+ return;
+}
+
+/**
+ Convert the input ascii string into GUID value.
+
+ @param Str Ascii GUID string to be converted.
+ @param Guid Pointer to the converted GUID value.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_NOT_FOUND The input ascii string is not a valid GUID format string.
+ @retval EFI_SUCCESS GUID value is got.
+
+**/
+EFI_STATUS
+UpdateStringToGuid (
+ IN UINT8 *Str,
+ IN OUT EFI_GUID *Guid
+ )
+{
+ UINT8 *PtrBuffer;
+ UINT8 *PtrPosition;
+ UINT8 *Buffer;
+ UINTN Data;
+ UINTN StrLen;
+ UINTN Index;
+ UINT8 Digits[3];
+
+ StrLen = AsciiStrLen ((CONST CHAR8 *) Str);
+ Buffer = AllocateCopyPool (StrLen + 1, Str);
+ if (Buffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Data1
+ //
+ PtrBuffer = Buffer;
+ PtrPosition = PtrBuffer;
+ while (*PtrBuffer != '\0') {
+ if (*PtrBuffer == '-') {
+ break;
+ }
+ PtrBuffer++;
+ }
+ if (*PtrBuffer == '\0') {
+ FreePool (Buffer);
+ return EFI_NOT_FOUND;
+ }
+
+ *PtrBuffer = '\0';
+ Data = AsciiStrHexToUintn ((CONST CHAR8 *) PtrPosition);
+ Guid->Data1 = (UINT32)Data;
+
+ //
+ // Data2
+ //
+ PtrBuffer++;
+ PtrPosition = PtrBuffer;
+ while (*PtrBuffer != '\0') {
+ if (*PtrBuffer == '-') {
+ break;
+ }
+ PtrBuffer++;
+ }
+ if (*PtrBuffer == '\0') {
+ FreePool (Buffer);
+ return EFI_NOT_FOUND;
+ }
+ *PtrBuffer = '\0';
+ Data = AsciiStrHexToUintn ((CONST CHAR8 *) PtrPosition);
+ Guid->Data2 = (UINT16)Data;
+
+ //
+ // Data3
+ //
+ PtrBuffer++;
+ PtrPosition = PtrBuffer;
+ while (*PtrBuffer != '\0') {
+ if (*PtrBuffer == '-') {
+ break;
+ }
+ PtrBuffer++;
+ }
+ if (*PtrBuffer == '\0') {
+ FreePool (Buffer);
+ return EFI_NOT_FOUND;
+ }
+ *PtrBuffer = '\0';
+ Data = AsciiStrHexToUintn ((CONST CHAR8 *) PtrPosition);
+ Guid->Data3 = (UINT16)Data;
+
+ //
+ // Data4[0..1]
+ //
+ for ( Index = 0 ; Index < 2 ; Index++) {
+ PtrBuffer++;
+ if ((*PtrBuffer == '\0') || ( *(PtrBuffer + 1) == '\0')) {
+ FreePool (Buffer);
+ return EFI_NOT_FOUND;
+ }
+ Digits[0] = *PtrBuffer;
+ PtrBuffer++;
+ Digits[1] = *PtrBuffer;
+ Digits[2] = '\0';
+ Data = AsciiStrHexToUintn ((CONST CHAR8 *) Digits);
+ Guid->Data4[Index] = (UINT8)Data;
+ }
+
+ //
+ // skip the '-'
+ //
+ PtrBuffer++;
+ if ((*PtrBuffer != '-' ) || ( *PtrBuffer == '\0')) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Data4[2..7]
+ //
+ for ( ; Index < 8; Index++) {
+ PtrBuffer++;
+ if ((*PtrBuffer == '\0') || ( *(PtrBuffer + 1) == '\0')) {
+ FreePool (Buffer);
+ return EFI_NOT_FOUND;
+ }
+ Digits[0] = *PtrBuffer;
+ PtrBuffer++;
+ Digits[1] = *PtrBuffer;
+ Digits[2] = '\0';
+ Data = AsciiStrHexToUintn ((CONST CHAR8 *) Digits);
+ Guid->Data4[Index] = (UINT8)Data;
+ }
+
+ FreePool (Buffer);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Pre process config data buffer into Section entry list and Comment entry list.
+
+ @param DataBuffer Config raw file buffer.
+ @param BufferSize Size of raw buffer.
+ @param SectionHead Pointer to the section entry list.
+ @param CommentHead Pointer to the comment entry list.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS Config data buffer is preprocessed.
+
+**/
+EFI_STATUS
+PreProcessDataFile (
+ IN UINT8 *DataBuffer,
+ IN UINTN BufferSize,
+ IN OUT SECTION_ITEM **SectionHead,
+ IN OUT COMMENT_LINE **CommentHead
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *Source;
+ CHAR8 *CurrentPtr;
+ CHAR8 *BufferEnd;
+ CHAR8 *PtrLine;
+ UINTN LineLength;
+ UINTN SourceLength;
+ UINTN MaxLineLength;
+
+ *SectionHead = NULL;
+ *CommentHead = NULL;
+ BufferEnd = (CHAR8 *) ( (UINTN) DataBuffer + BufferSize);
+ CurrentPtr = (CHAR8 *) DataBuffer;
+ MaxLineLength = MAX_LINE_LENGTH;
+ Status = EFI_SUCCESS;
+
+ PtrLine = AllocatePool (MaxLineLength);
+ if (PtrLine == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ while (CurrentPtr < BufferEnd) {
+ Source = CurrentPtr;
+ SourceLength = (UINTN)BufferEnd - (UINTN)CurrentPtr;
+ LineLength = MaxLineLength;
+ //
+ // With the assumption that line length is less than 512
+ // characters. Otherwise BUFFER_TOO_SMALL will be returned.
+ //
+ Status = ProfileGetLine (
+ (UINT8 *) Source,
+ SourceLength,
+ (UINT8 *) PtrLine,
+ &LineLength
+ );
+ if (EFI_ERROR (Status)) {
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ //
+ // If buffer too small, re-allocate the buffer according
+ // to the returned LineLength and try again.
+ //
+ FreePool (PtrLine);
+ PtrLine = NULL;
+ PtrLine = AllocatePool (LineLength);
+ if (PtrLine == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ break;
+ }
+ SourceLength = LineLength;
+ Status = ProfileGetLine (
+ (UINT8 *) Source,
+ SourceLength,
+ (UINT8 *) PtrLine,
+ &LineLength
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ MaxLineLength = LineLength;
+ } else {
+ break;
+ }
+ }
+ CurrentPtr = (CHAR8 *) ( (UINTN) CurrentPtr + LineLength);
+
+ //
+ // Line got. Trim the line before processing it.
+ //
+ ProfileTrim (
+ (UINT8 *) PtrLine,
+ &LineLength
+ );
+
+ //
+ // Blank line
+ //
+ if (LineLength == 0) {
+ continue;
+ }
+
+ if (PtrLine[0] == '#') {
+ Status = ProfileGetComments (
+ (UINT8 *) PtrLine,
+ LineLength,
+ CommentHead
+ );
+ } else if (PtrLine[0] == '[') {
+ Status = ProfileGetSection (
+ (UINT8 *) PtrLine,
+ LineLength,
+ SectionHead
+ );
+ } else {
+ Status = ProfileGetEntry (
+ (UINT8 *) PtrLine,
+ LineLength,
+ SectionHead
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+
+ //
+ // Free buffer
+ //
+ FreePool (PtrLine);
+
+ return Status;
+}
+
+/**
+ Parse Config data file to get the updated data array.
+
+ @param DataBuffer Config raw file buffer.
+ @param BufferSize Size of raw buffer.
+ @param NumOfUpdates Pointer to the number of update data.
+ @param UpdateArray Pointer to the config of update data.
+
+ @retval EFI_NOT_FOUND No config data is found.
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS Parse the config file successfully.
+
+**/
+EFI_STATUS
+ParseUpdateDataFile (
+ IN UINT8 *DataBuffer,
+ IN UINTN BufferSize,
+ IN OUT UINTN *NumOfUpdates,
+ IN OUT UPDATE_CONFIG_DATA **UpdateArray
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *Value;
+ CHAR8 *SectionName;
+ CHAR8 Entry[MAX_LINE_LENGTH];
+ SECTION_ITEM *SectionHead;
+ COMMENT_LINE *CommentHead;
+ UINTN Num;
+ UINTN Index;
+ EFI_GUID FileGuid;
+
+ SectionHead = NULL;
+ CommentHead = NULL;
+
+ //
+ // First process the data buffer and get all sections and entries
+ //
+ Status = PreProcessDataFile (
+ DataBuffer,
+ BufferSize,
+ &SectionHead,
+ &CommentHead
+ );
+ if (EFI_ERROR (Status)) {
+ FreeAllList (SectionHead, CommentHead);
+ return Status;
+ }
+
+ //
+ // Now get NumOfUpdate
+ //
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) "Head",
+ (UINT8 *) "NumOfUpdate",
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+ Num = UpdateAtoi((UINT8 *) Value);
+ if (Num <= 0) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ *NumOfUpdates = Num;
+ *UpdateArray = AllocatePool ((sizeof (UPDATE_CONFIG_DATA) * Num));
+ if (*UpdateArray == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ for ( Index = 0 ; Index < *NumOfUpdates ; Index++) {
+ //
+ // Get the section name of each update
+ //
+ AsciiStrCpyS (Entry, MAX_LINE_LENGTH, "Update");
+ UpdateStrCatNumber ((UINT8 *) Entry, Index);
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) "Head",
+ (UINT8 *) Entry,
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // The section name of this update has been found.
+ // Now looks for all the config data of this update
+ //
+ SectionName = Value;
+
+ //
+ // UpdateType
+ //
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) SectionName,
+ (UINT8 *) "UpdateType",
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ Num = UpdateAtoi((UINT8 *) Value);
+ if (( Num >= (UINTN) UpdateOperationMaximum)) {
+ FreeAllList (SectionHead, CommentHead);
+ return Status;
+ }
+ (*UpdateArray)[Index].Index = Index;
+ (*UpdateArray)[Index].UpdateType = (UPDATE_OPERATION_TYPE) Num;
+
+ //
+ // FvBaseAddress
+ //
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) SectionName,
+ (UINT8 *) "FvBaseAddress",
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ Num = AsciiStrHexToUintn ((CONST CHAR8 *) Value);
+ (*UpdateArray)[Index].BaseAddress = (EFI_PHYSICAL_ADDRESS) Num;
+
+ //
+ // FileBuid
+ //
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) SectionName,
+ (UINT8 *) "FileGuid",
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ Status = UpdateStringToGuid ((UINT8 *) Value, &FileGuid);
+ if (EFI_ERROR (Status)) {
+ FreeAllList (SectionHead, CommentHead);
+ return Status;
+ }
+ CopyMem (&((*UpdateArray)[Index].FileGuid), &FileGuid, sizeof(EFI_GUID));
+
+ //
+ // FaultTolerant
+ // Default value is FALSE
+ //
+ Value = NULL;
+ (*UpdateArray)[Index].FaultTolerant = FALSE;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) SectionName,
+ (UINT8 *) "FaultTolerant",
+ (UINT8 **) &Value
+ );
+ if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
+ FreeAllList (SectionHead, CommentHead);
+ return Status;
+ } else if (Value != NULL) {
+ if (AsciiStriCmp ((CONST CHAR8 *) Value, (CONST CHAR8 *) "TRUE") == 0) {
+ (*UpdateArray)[Index].FaultTolerant = TRUE;
+ } else if (AsciiStriCmp ((CONST CHAR8 *) Value, (CONST CHAR8 *) "FALSE") == 0) {
+ (*UpdateArray)[Index].FaultTolerant = FALSE;
+ }
+ }
+
+ if ((*UpdateArray)[Index].UpdateType == UpdateFvRange) {
+ //
+ // Length
+ //
+ Value = NULL;
+ Status = UpdateGetProfileString (
+ SectionHead,
+ (UINT8 *) SectionName,
+ (UINT8 *) "Length",
+ (UINT8 **) &Value
+ );
+ if (Value == NULL) {
+ FreeAllList (SectionHead, CommentHead);
+ return EFI_NOT_FOUND;
+ }
+
+ Num = AsciiStrHexToUintn ((CONST CHAR8 *) Value);
+ (*UpdateArray)[Index].Length = (UINTN) Num;
+ }
+ }
+
+ //
+ // Now all configuration data got. Free those temporary buffers
+ //
+ FreeAllList (SectionHead, CommentHead);
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDispatcher.c b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDispatcher.c
new file mode 100644
index 0000000000..e1f1b023dc
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDispatcher.c
@@ -0,0 +1,846 @@
+/** @file
+ Functions in this file will mainly focus on looking through the capsule
+ for the image to be programmed, and the flash area that is going to be
+ programed.
+
+ Copyright (c) 2002 - 2014, Intel Corporation. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions
+ of the BSD License which accompanies this distribution. The
+ full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "UpdateDriver.h"
+
+EFI_HII_HANDLE gHiiHandle;
+
+/**
+ Update the whole FV, or certain files in the FV.
+
+ @param ConfigData Pointer to the config data on updating file.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+ @param FileType FFS file type.
+ @param FileAttributes FFS file attribute.
+
+ @retval EFI_NOT_FOUND The matched FVB protocol is not found.
+ @retval EFI_SUCCESS The image buffer is updated into FV.
+
+**/
+EFI_STATUS
+PerformUpdateOnFirmwareVolume (
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ )
+{
+ EFI_STATUS Status;
+ BOOLEAN Found;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;
+ UINTN Index;
+ UINTN NumOfHandles;
+ EFI_HANDLE *HandleBuffer;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_FVB_ATTRIBUTES_2 Attributes;
+
+ //
+ // Locate all Fvb protocol
+ //
+ HandleBuffer = NULL;
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ NULL,
+ &NumOfHandles,
+ &HandleBuffer
+ );
+ if ((EFI_ERROR (Status)) || (NumOfHandles == 0) || (HandleBuffer == NULL)) {
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ }
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Check the FVB protocol one by one
+ //
+ Found = FALSE;
+ FvbProtocol = NULL;
+ for (Index = 0; Index < NumOfHandles; Index++) {
+ Status = gBS->HandleProtocol (
+ HandleBuffer[Index],
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ (VOID **) &FvbProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ //
+ // Ensure this FVB protocol supported Write operation.
+ //
+ Status = FvbProtocol->GetAttributes (FvbProtocol, &Attributes);
+ if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
+ continue;
+ }
+
+ Status = FvbProtocol->GetPhysicalAddress (
+ FvbProtocol,
+ &BaseAddress
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ if (BaseAddress == ConfigData->BaseAddress) {
+ Found = TRUE;
+ break;
+ }
+ }
+
+ if (!Found) {
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ HandleBuffer = NULL;
+ }
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Now we have got the corresponding FVB protocol. Use the FVB protocol
+ // to update the whole FV, or certain files in the FV.
+ //
+ if (ConfigData->UpdateType == UpdateWholeFV) {
+ if (FileType != EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ Status = PerformUpdateOnWholeFv (
+ HandleBuffer[Index],
+ FvbProtocol,
+ ConfigData,
+ ImageBuffer,
+ ImageSize
+ );
+ }
+ } else if (ConfigData->UpdateType == UpdateFvFile) {
+ Status = PerformUpdateOnFvFile (
+ HandleBuffer[Index],
+ FvbProtocol,
+ ConfigData,
+ ImageBuffer,
+ ImageSize,
+ FileType,
+ FileAttributes
+ );
+ }
+
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ HandleBuffer = NULL;
+ }
+
+ return Status;
+}
+
+/**
+ Update the file directly into flash area.
+
+ @param ConfigData Pointer to the config data on updating file.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+
+ @retval EFI_SUCCESS The file is updated into flash area.
+ @retval EFI_NOT_FOUND The FVB protocol for the updated flash area is not found.
+
+**/
+EFI_STATUS
+PerformUpdateOnFlashArea (
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize
+ )
+{
+ EFI_STATUS Status;
+ UINTN SizeLeft;
+ EFI_PHYSICAL_ADDRESS FlashAddress;
+ UINT8 *PtrImage;
+ BOOLEAN Found;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;
+ UINTN Index;
+ UINTN NumOfHandles;
+ EFI_HANDLE *HandleBuffer;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_HANDLE FvbHandle;
+ UINTN SizeUpdated;
+ CHAR16 *TmpStr;
+ EFI_FVB_ATTRIBUTES_2 Attributes;
+
+ SizeLeft = ImageSize;
+ PtrImage = ImageBuffer;
+ FlashAddress = ConfigData->BaseAddress;
+ Status = EFI_SUCCESS;
+ HandleBuffer = NULL;
+
+ //
+ // Print on screen
+ //
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_FLASH_RANGE), NULL);
+ if (TmpStr != NULL) {
+ Print (TmpStr, FlashAddress, ((UINT64)SizeLeft + FlashAddress));
+ FreePool (TmpStr);
+ }
+
+ //
+ // Locate all Fvb protocol
+ //
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ NULL,
+ &NumOfHandles,
+ &HandleBuffer
+ );
+ if ((EFI_ERROR (Status)) || (NumOfHandles == 0) || (HandleBuffer == NULL)) {
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ }
+ return EFI_NOT_FOUND;
+ }
+
+ while (SizeLeft > 0) {
+ //
+ // First get the FVB protocols. If the flash area is a FV, or sub FV,
+ // we can directly locate all the FVB protocol. Otherwise we should use
+ // implementation specific method to get the alternate FVB protocol
+ //
+ Found = FALSE;
+ FvbProtocol = NULL;
+
+ //
+ // Check the FVB protocol one by one
+ //
+ for (Index = 0; Index < NumOfHandles; Index++) {
+ Status = gBS->HandleProtocol (
+ HandleBuffer[Index],
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ (VOID **) &FvbProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ //
+ // Ensure this FVB protocol supported Write operation.
+ //
+ Status = FvbProtocol->GetAttributes (FvbProtocol, &Attributes);
+ if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {
+ continue;
+ }
+
+ Status = FvbProtocol->GetPhysicalAddress (
+ FvbProtocol,
+ &BaseAddress
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;
+
+ //
+ // This sub area entry falls in the range of the FV
+ //
+ if ((FlashAddress >= BaseAddress) && (FlashAddress < (BaseAddress + FwVolHeader->FvLength))) {
+ Found = TRUE;
+ break;
+ }
+ }
+
+ if (!Found) {
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ HandleBuffer = NULL;
+ }
+ return EFI_NOT_FOUND;
+ }
+
+ FvbHandle = HandleBuffer[Index];
+ SizeUpdated = 0;
+
+ //
+ // If the flash area is boot required, the update must be fault tolerant
+ //
+ if (ConfigData->FaultTolerant) {
+ //
+ // Finally we are here. We have got the corresponding FVB protocol. Now
+ // we need to convert the physical address to LBA and offset and call
+ // FTW write. Also check if the flash range is larger than the FV.
+ //
+ Status = FaultTolerantUpdateOnPartFv (
+ PtrImage,
+ SizeLeft,
+ &SizeUpdated,
+ ConfigData,
+ FlashAddress,
+ FvbProtocol,
+ FvbHandle
+ );
+ } else {
+ //
+ // Finally we are here. We have got the corresponding FVB protocol. Now
+ // we need to convert the physical address to LBA and offset and call
+ // FVB write. Also check if the flash range is larger than the FV.
+ //
+ Status = NonFaultTolerantUpdateOnPartFv (
+ PtrImage,
+ SizeLeft,
+ &SizeUpdated,
+ FlashAddress,
+ FvbProtocol,
+ FvbHandle
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // As part of the FV has been replaced, the FV driver shall re-parse
+ // the firmware volume. So re-install FVB protocol here
+ //
+ Status = gBS->ReinstallProtocolInterface (
+ FvbHandle,
+ &gEfiFirmwareVolumeBlockProtocolGuid,
+ FvbProtocol,
+ FvbProtocol
+ );
+
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Check if we are done with the update
+ //
+ SizeLeft = SizeLeft - SizeUpdated;
+ FlashAddress = FlashAddress + SizeUpdated;
+ PtrImage = PtrImage + SizeUpdated;
+ }
+
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ HandleBuffer = NULL;
+ }
+
+ return Status;
+}
+
+/**
+ Find the updated file, and program it into the flash area based on the config data.
+
+ @param FwVolProtocol Pointer to FV protocol that contains the updated file.
+ @param ConfigData Pointer to the Config Data on updating file.
+
+ @retval EFI_INVALID_PARAMETER The update operation is not valid.
+ @retval EFI_NOT_FOUND The updated file is not found.
+ @retval EFI_SUCCESS The file is updated into the flash area.
+
+**/
+EFI_STATUS
+PerformUpdate (
+ IN EFI_FIRMWARE_VOLUME2_PROTOCOL *FwVolProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData
+ )
+{
+ EFI_STATUS Status;
+ UINT8 *FileBuffer;
+ UINTN FileBufferSize;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES Attrib;
+ EFI_SECTION_TYPE SectionType;
+ UINT32 AuthenticationStatus;
+ CHAR16 *TmpStr;
+ BOOLEAN StartToUpdate;
+
+ Status = EFI_SUCCESS;
+ FileBuffer = NULL;
+ FileBufferSize = 0;
+ Status = FwVolProtocol->ReadFile (
+ FwVolProtocol,
+ &(ConfigData->FileGuid),
+ (VOID **) &FileBuffer,
+ &FileBufferSize,
+ &FileType,
+ &Attrib,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ StartToUpdate = FALSE;
+
+ //
+ // Check if the update image is the one we require
+ // and then perform the update
+ //
+ switch (ConfigData->UpdateType) {
+
+ case UpdateWholeFV:
+
+ //
+ // For UpdateWholeFv, the update file shall be a firmware volume
+ // image file.
+ //
+ if (FileType != EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {
+ DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should be of TYPE EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE\n"));
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ if (FileBuffer != NULL) {
+ FreePool (FileBuffer);
+ }
+ SectionType = EFI_SECTION_FIRMWARE_VOLUME_IMAGE;
+ FileBuffer = NULL;
+ FileBufferSize = 0;
+ Status = FwVolProtocol->ReadSection (
+ FwVolProtocol,
+ &(ConfigData->FileGuid),
+ SectionType,
+ 0,
+ (VOID **) &FileBuffer,
+ &FileBufferSize,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+ //
+ // Execute the update. For UpdateWholeFv, the update
+ // will always execute on a whole FV
+ //
+ StartToUpdate = TRUE;
+ Status = PerformUpdateOnFirmwareVolume (
+ ConfigData,
+ FileBuffer,
+ FileBufferSize,
+ FileType,
+ Attrib
+ );
+
+ } else {
+ DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should be sectioned with TYPE EFI_SECTION_FIRMWARE_VOLUME_IMAGE\n"));
+ }
+ }
+ break;
+
+ case UpdateFvRange:
+
+ //
+ // For UpdateFvRange, the update file shall be a raw file
+ // which does not contain any sections. The contents of the file
+ // will be directly programmed.
+ //
+ if (FileType != EFI_FV_FILETYPE_RAW) {
+ DEBUG ((EFI_D_UPDATE, "UpdateDriver: Data file should of TYPE EFI_FV_FILETYPE_RAW\n"));
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ //
+ // For UpdateFvRange, the update may be performed on a sub area
+ // of a certain FV, or a flash area that is not FV, or part of FV.
+ // The update may also go across more than one FVs.
+ //
+ StartToUpdate = TRUE;
+ Status = PerformUpdateOnFlashArea (
+ ConfigData,
+ FileBuffer,
+ FileBufferSize
+ );
+ }
+ break;
+
+ case UpdateFvFile:
+
+ //
+ // No check will be done the the file got. The contents of the file
+ // will be directly programmed.
+ // Though UpdateFvFile will only update a single file, but the update
+ // will always execute on a FV
+ //
+ StartToUpdate = TRUE;
+ Status = PerformUpdateOnFirmwareVolume (
+ ConfigData,
+ FileBuffer,
+ FileBufferSize,
+ FileType,
+ Attrib
+ );
+ break;
+
+ default:
+ Status = EFI_INVALID_PARAMETER;
+ }
+
+ if (StartToUpdate) {
+ if (EFI_ERROR (Status)) {
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_DRIVER_ABORTED), NULL);
+ } else {
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_DRIVER_DONE), NULL);
+ }
+ if (TmpStr != NULL) {
+ Print (TmpStr);
+ FreePool (TmpStr);
+ }
+ }
+
+ if (FileBuffer != NULL) {
+ FreePool(FileBuffer);
+ FileBuffer = NULL;
+ }
+
+ return Status;
+}
+
+/**
+ Process the input firmware volume by using DXE service ProcessFirmwareVolume.
+
+ @param DataBuffer Point to the FV image to be processed.
+ @param BufferSize Size of the FV image buffer.
+ @param FwVolProtocol Point to the installed FV protocol for the input FV image.
+
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_VOLUME_CORRUPTED FV image is corrupted.
+ @retval EFI_SUCCESS FV image is processed and FV protocol is installed.
+
+**/
+EFI_STATUS
+ProcessUpdateImage (
+ UINT8 *DataBuffer,
+ UINTN BufferSize,
+ EFI_FIRMWARE_VOLUME2_PROTOCOL **FwVolProtocol
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_HANDLE FwVolHandle;
+ EFI_STATUS Status;
+ UINT8 *ProcessedDataBuffer;
+ UINT32 FvAlignment;
+
+ ProcessedDataBuffer = NULL;
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) DataBuffer;
+ if (FwVolHeader->FvLength != BufferSize) {
+ return EFI_VOLUME_CORRUPTED;
+ }
+
+ FvAlignment = 1 << ((FwVolHeader->Attributes & EFI_FVB2_ALIGNMENT) >> 16);
+ //
+ // FvAlignment must be greater than or equal to 8 bytes of the minimum FFS alignment value.
+ //
+ if (FvAlignment < 8) {
+ FvAlignment = 8;
+ }
+ //
+ // Check FvImage Align is required.
+ //
+ if (((UINTN) FwVolHeader % FvAlignment) == 0) {
+ ProcessedDataBuffer = DataBuffer;
+ } else {
+ //
+ // Allocate new aligned buffer to store DataBuffer.
+ //
+ ProcessedDataBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), (UINTN) FvAlignment);
+ if (ProcessedDataBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (ProcessedDataBuffer, DataBuffer, BufferSize);
+ }
+ //
+ // Process the firmware volume
+ //
+ gDS->ProcessFirmwareVolume (
+ ProcessedDataBuffer,
+ BufferSize,
+ &FwVolHandle
+ );
+
+ //
+ // Get the FwVol protocol
+ //
+ Status = gBS->HandleProtocol (
+ FwVolHandle,
+ &gEfiFirmwareVolume2ProtocolGuid,
+ (VOID **) FwVolProtocol
+ );
+
+ return Status;
+}
+
+/**
+ Find the image in the same FV and program it in a target Firmware Volume device.
+ After update image, it will reset system and no return.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_ABORTED System reset failed.
+ @retval EFI_NOT_FOUND The updated image is not found in the same FV.
+
+**/
+EFI_STATUS
+EFIAPI
+InitializeUpdateDriver (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_LOADED_IMAGE_PROTOCOL *LoadedImageProtocol;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *FwVolProtocol;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *DataFwVolProtocol;
+ MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FwVolFilePathNode;
+ MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *AlignedDevPathNode;
+ EFI_DEVICE_PATH_PROTOCOL *FilePathNode;
+ EFI_SECTION_TYPE SectionType;
+ UINT8 *FileBuffer;
+ UINTN FileBufferSize;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES Attrib;
+ UINT32 AuthenticationStatus;
+ UPDATE_CONFIG_DATA *ConfigData;
+ UPDATE_CONFIG_DATA *UpdateConfigData;
+ UINTN NumOfUpdates;
+ UINTN Index;
+ CHAR16 *TmpStr;
+
+ //
+ // Clear screen
+ //
+ if (gST->ConOut != NULL) {
+ gST->ConOut->ClearScreen (gST->ConOut);
+ gST->ConOut->SetAttribute (gST->ConOut, EFI_YELLOW | EFI_BRIGHT);
+ gST->ConOut->EnableCursor (gST->ConOut, FALSE);
+ }
+
+ gHiiHandle = HiiAddPackages (
+ &gEfiCallerIdGuid,
+ NULL,
+ UpdateDriverDxeStrings,
+ NULL
+ );
+ ASSERT (gHiiHandle != NULL);
+
+ //
+ // In order to look for the update data file and programmed image file
+ // from the same volume which this driver is dispatched from, we need
+ // to get the device path of this driver image. It is done by first
+ // locate the LoadedImageProtocol and then get its device path
+ //
+ Status = gBS->OpenProtocol (
+ ImageHandle,
+ &gEfiLoadedImageProtocolGuid,
+ (VOID **)&LoadedImageProtocol,
+ ImageHandle,
+ NULL,
+ EFI_OPEN_PROTOCOL_GET_PROTOCOL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Get the firmware volume protocol where this file resides
+ //
+ Status = gBS->HandleProtocol (
+ LoadedImageProtocol->DeviceHandle,
+ &gEfiFirmwareVolume2ProtocolGuid,
+ (VOID **) &FwVolProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Shall do some extra check to see if it is really contained in the FV?
+ // Should be able to find the section of this driver in the the FV.
+ //
+ FilePathNode = LoadedImageProtocol->FilePath;
+ FwVolFilePathNode = NULL;
+ while (!IsDevicePathEnd (FilePathNode)) {
+ if (EfiGetNameGuidFromFwVolDevicePathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)FilePathNode)!= NULL) {
+ FwVolFilePathNode = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) FilePathNode;
+ break;
+ }
+ FilePathNode = NextDevicePathNode (FilePathNode);
+ }
+
+ if (FwVolFilePathNode != NULL) {
+ AlignedDevPathNode = AllocateCopyPool (DevicePathNodeLength (FwVolFilePathNode), FwVolFilePathNode);
+
+ SectionType = EFI_SECTION_PE32;
+ FileBuffer = NULL;
+ FileBufferSize = 0;
+ Status = FwVolProtocol->ReadSection (
+ FwVolProtocol,
+ &(AlignedDevPathNode->FvFileName),
+ SectionType,
+ 0,
+ (VOID **) &FileBuffer,
+ &FileBufferSize,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (AlignedDevPathNode);
+ return Status;
+ }
+
+ if (FileBuffer != NULL) {
+ FreePool(FileBuffer);
+ FileBuffer = NULL;
+ }
+
+ //
+ // Check the NameGuid of the udpate driver so that it can be
+ // used as the CallerId in fault tolerant write protocol
+ //
+ if (!CompareGuid (&gEfiCallerIdGuid, &(AlignedDevPathNode->FvFileName))) {
+ FreePool (AlignedDevPathNode);
+ return EFI_NOT_FOUND;
+ }
+ FreePool (AlignedDevPathNode);
+ } else {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Now try to find the script file. The script file is usually
+ // a raw data file which does not contain any sections.
+ //
+ FileBuffer = NULL;
+ FileBufferSize = 0;
+ Status = FwVolProtocol->ReadFile (
+ FwVolProtocol,
+ &gEfiConfigFileNameGuid,
+ (VOID **) &FileBuffer,
+ &FileBufferSize,
+ &FileType,
+ &Attrib,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ if (FileType != EFI_FV_FILETYPE_RAW) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // Parse the configuration file.
+ //
+ ConfigData = NULL;
+ NumOfUpdates = 0;
+ Status = ParseUpdateDataFile (
+ FileBuffer,
+ FileBufferSize,
+ &NumOfUpdates,
+ &ConfigData
+ );
+ if (FileBuffer != NULL) {
+ FreePool (FileBuffer);
+ FileBuffer = NULL;
+ }
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ ASSERT (ConfigData != NULL);
+
+ //
+ // Now find the update image. The update image should be put in a FV, and then
+ // encapsulated as a raw FFS file. This is to prevent the update image from
+ // being dispatched. So the raw data we get here should be an FV. We need to
+ // process this FV and read the files that is going to be updated.
+ //
+ FileBuffer = NULL;
+ FileBufferSize = 0;
+ Status = FwVolProtocol->ReadFile (
+ FwVolProtocol,
+ &gEfiUpdateDataFileGuid,
+ (VOID **) &FileBuffer,
+ &FileBufferSize,
+ &FileType,
+ &Attrib,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ if (FileType != EFI_FV_FILETYPE_RAW) {
+ return EFI_NOT_FOUND;
+ }
+
+ //
+ // FileBuffer should be an FV. Process the FV
+ //
+ DataFwVolProtocol = NULL;
+ Status = ProcessUpdateImage (
+ FileBuffer,
+ FileBufferSize,
+ &DataFwVolProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (FileBuffer);
+ return Status;
+ }
+
+ //
+ // Print on screen
+ //
+ TmpStr = HiiGetString (gHiiHandle, STRING_TOKEN(UPDATE_PROCESS_DATA), NULL);
+ if (TmpStr != NULL) {
+ Print (TmpStr);
+ FreePool(TmpStr);
+ }
+
+ //
+ // Execute the update
+ //
+ Index = 0;
+ UpdateConfigData = ConfigData;
+ while (Index < NumOfUpdates) {
+ Status = PerformUpdate (
+ DataFwVolProtocol,
+ UpdateConfigData
+ );
+ //
+ // Shall updates be serialized so that if an update is not successfully completed,
+ // the remaining updates won't be performed.
+ //
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Index++;
+ UpdateConfigData++;
+ }
+
+ if (EFI_ERROR (Status)) {
+ if (ConfigData != NULL) {
+ FreePool(ConfigData);
+ ConfigData = NULL;
+ }
+ return Status;
+ }
+
+ //
+ // Call system reset
+ //
+ gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL);
+
+ //
+ // Hopefully it won't be reached
+ //
+ return EFI_ABORTED;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriver.h b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriver.h
new file mode 100644
index 0000000000..e1f22a9d5a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriver.h
@@ -0,0 +1,213 @@
+/** @file
+ Common defines and definitions for a component update driver.
+
+ Copyright (c) 2002 - 2010, 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 _EFI_UPDATE_DRIVER_H_
+#define _EFI_UPDATE_DRIVER_H_
+
+#include <PiDxe.h>
+
+#include <Protocol/LoadedImage.h>
+#include <Guid/Capsule.h>
+#include <Guid/CapsuleDataFile.h>
+#include <Protocol/FaultTolerantWrite.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+#include <Protocol/FirmwareVolume2.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DxeServicesTableLib.h>
+#include <Library/HiiLib.h>
+#include <Library/PrintLib.h>
+#include <Library/DevicePathLib.h>
+
+extern EFI_HII_HANDLE gHiiHandle;
+
+typedef enum {
+ UpdateWholeFV = 0, // 0, update whole FV
+ UpdateFvFile, // 1, update a set of FV files asynchronously
+ UpdateFvRange, // 2, update part of FV or flash
+ UpdateOperationMaximum // 3
+} UPDATE_OPERATION_TYPE;
+
+typedef struct {
+ UINTN Index;
+ UPDATE_OPERATION_TYPE UpdateType;
+ EFI_DEVICE_PATH_PROTOCOL DevicePath;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_GUID FileGuid;
+ UINTN Length;
+ BOOLEAN FaultTolerant;
+} UPDATE_CONFIG_DATA;
+
+typedef struct _SECTION_ITEM SECTION_ITEM;
+struct _SECTION_ITEM {
+ CHAR8 *ptrSection;
+ UINTN SecNameLen;
+ CHAR8 *ptrEntry;
+ CHAR8 *ptrValue;
+ SECTION_ITEM *ptrNext;
+};
+
+typedef struct _COMMENT_LINE COMMENT_LINE;
+struct _COMMENT_LINE {
+ CHAR8 *ptrComment;
+ COMMENT_LINE *ptrNext;
+};
+
+typedef struct {
+ EFI_GUID FileGuid;
+} UPDATE_PRIVATE_DATA;
+
+#define MAX_LINE_LENGTH 512
+#define EFI_D_UPDATE EFI_D_ERROR
+
+#define MIN_ALIGNMENT_SIZE 4
+#define ALIGN_SIZE(a) ((a % MIN_ALIGNMENT_SIZE) ? MIN_ALIGNMENT_SIZE - (a % MIN_ALIGNMENT_SIZE) : 0)
+
+/**
+ Parse Config data file to get the updated data array.
+
+ @param DataBuffer Config raw file buffer.
+ @param BufferSize Size of raw buffer.
+ @param NumOfUpdates Pointer to the number of update data.
+ @param UpdateArray Pointer to the config of update data.
+
+ @retval EFI_NOT_FOUND No config data is found.
+ @retval EFI_OUT_OF_RESOURCES No enough memory is allocated.
+ @retval EFI_SUCCESS Parse the config file successfully.
+
+**/
+EFI_STATUS
+ParseUpdateDataFile (
+ IN UINT8 *DataBuffer,
+ IN UINTN BufferSize,
+ IN OUT UINTN *NumOfUpdates,
+ IN OUT UPDATE_CONFIG_DATA **UpdateArray
+ );
+
+/**
+ Update the whole FV image, and reinsall FVB protocol for the updated FV image.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+
+ @retval EFI_INVALID_PARAMETER Update type is not UpdateWholeFV.
+ Or Image size is not same to the size of whole FV.
+ @retval EFI_OUT_OF_RESOURCES No enoug memory is allocated.
+ @retval EFI_SUCCESS FV image is updated, and its FVB protocol is reinstalled.
+
+**/
+EFI_STATUS
+PerformUpdateOnWholeFv (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize
+ );
+
+/**
+ Update certain file in the FV.
+
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+ @param FvbProtocol FVB protocol.
+ @param ConfigData Config data on updating driver.
+ @param ImageBuffer Image buffer to be updated.
+ @param ImageSize Image size.
+ @param FileType FFS file type.
+ @param FileAttributes FFS file attribute
+
+ @retval EFI_INVALID_PARAMETER Update type is not UpdateFvFile.
+ Or Image size is not same to the size of whole FV.
+ @retval EFI_UNSUPPORTED PEIM FFS is unsupported to be updated.
+ @retval EFI_SUCCESS The FFS file is added into FV.
+
+**/
+EFI_STATUS
+PerformUpdateOnFvFile (
+ IN EFI_HANDLE FvbHandle,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN UINT8 *ImageBuffer,
+ IN UINTN ImageSize,
+ IN EFI_FV_FILETYPE FileType,
+ IN EFI_FV_FILE_ATTRIBUTES FileAttributes
+ );
+
+/**
+ Update the buffer into flash area in fault tolerant write method.
+
+ @param ImageBuffer Image buffer to be updated.
+ @param SizeLeft Size of the image buffer.
+ @param UpdatedSize Size of the updated buffer.
+ @param ConfigData Config data on updating driver.
+ @param FlashAddress Flash address to be updated as start address.
+ @param FvbProtocol FVB protocol.
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+
+ @retval EFI_SUCCESS Buffer data is updated into flash.
+ @retval EFI_INVALID_PARAMETER Base flash address is not in FVB flash area.
+ @retval EFI_NOT_FOUND FTW protocol doesn't exist.
+ @retval EFI_OUT_OF_RESOURCES No enough backup space.
+ @retval EFI_ABORTED Error happen when update flash area.
+
+**/
+EFI_STATUS
+FaultTolerantUpdateOnPartFv (
+ IN UINT8 *ImageBuffer,
+ IN UINTN SizeLeft,
+ IN OUT UINTN *UpdatedSize,
+ IN UPDATE_CONFIG_DATA *ConfigData,
+ IN EFI_PHYSICAL_ADDRESS FlashAddress,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_HANDLE FvbHandle
+ );
+
+/**
+ Directly update the buffer into flash area without fault tolerant write method.
+
+ @param ImageBuffer Image buffer to be updated.
+ @param SizeLeft Size of the image buffer.
+ @param UpdatedSize Size of the updated buffer.
+ @param FlashAddress Flash address to be updated as start address.
+ @param FvbProtocol FVB protocol.
+ @param FvbHandle Handle of FVB protocol for the updated flash range.
+
+ @retval EFI_SUCCESS Buffer data is updated into flash.
+ @retval EFI_INVALID_PARAMETER Base flash address is not in FVB flash area.
+ @retval EFI_OUT_OF_RESOURCES No enough backup space.
+
+**/
+EFI_STATUS
+NonFaultTolerantUpdateOnPartFv (
+ IN UINT8 *ImageBuffer,
+ IN UINTN SizeLeft,
+ IN OUT UINTN *UpdatedSize,
+ IN EFI_PHYSICAL_ADDRESS FlashAddress,
+ IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol,
+ IN EFI_HANDLE FvbHandle
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.inf b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.inf
new file mode 100644
index 0000000000..d83a1ecb57
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.inf
@@ -0,0 +1,76 @@
+## @file
+# Update Driver for Capulse update.
+#
+# This driver is intended to be put in a capsule (FV). If all goes well,
+# then it should be dispatched from the capsule FV, then find the image
+# in the same FV and program it in a target Firmware Volume device.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials are
+# licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = UpdateDriverDxe
+ MODULE_UNI_FILE = UpdateDriverDxe.uni
+ FILE_GUID = 0E84FC69-29CC-4C6D-92AC-6D476921850F
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = InitializeUpdateDriver
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ UpdateDriver.h
+ UpdateStrings.uni
+ UpdateDispatcher.c
+ ParseUpdateProfile.c
+ FlashUpdate.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ BaseLib
+ PrintLib
+ HiiLib
+ DxeServicesTableLib
+ MemoryAllocationLib
+ UefiLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ UefiRuntimeServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ DevicePathLib
+
+[Guids]
+ gEfiConfigFileNameGuid ## CONSUMES ## File # FileName to store ConfigFile
+ gEfiUpdateDataFileGuid ## CONSUMES ## File # FileName to store Capsule Data.
+
+[Protocols]
+ gEfiFaultTolerantWriteProtocolGuid ## CONSUMES
+ gEfiFirmwareVolume2ProtocolGuid ## CONSUMES
+ gEfiFirmwareVolumeBlockProtocolGuid ## CONSUMES
+ gEfiLoadedImageProtocolGuid ## CONSUMES
+
+[Depex]
+ gEfiFirmwareVolumeBlockProtocolGuid AND gEfiFaultTolerantWriteProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ UpdateDriverDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.uni b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.uni
new file mode 100644
index 0000000000..dd240520da
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxe.uni
@@ -0,0 +1,24 @@
+// /** @file
+// Update Driver for Capulse update.
+//
+// This driver is intended to be put in a capsule (FV). If all goes well,
+// then it should be dispatched from the capsule FV, then find the image
+// in the same FV and program it in a target Firmware Volume device.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Update Driver for Capsule update"
+
+#string STR_MODULE_DESCRIPTION #language en-US "This driver is intended to be put in a capsule (FV). If all goes correctly, it should be dispatched from the capsule FV, and then it finds the image in the same FV, and programs it in a target Firmware Volume device."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxeExtra.uni
new file mode 100644
index 0000000000..8336074989
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateDriverDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// UpdateDriverDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Firmware Update DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateStrings.uni b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateStrings.uni
new file mode 100644
index 0000000000..6aacd5961f
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/FirmwareVolume/UpdateDriverDxe/UpdateStrings.uni
@@ -0,0 +1,25 @@
+/// @file
+// String definitions for UpdateDispatcher formset.
+//
+// Copyright (c) 2003 - 2014, 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.
+//
+///
+
+/=#
+
+#langdef en-US "English"
+
+#string UPDATE_PROCESS_DATA #language en-US "Update driver loaded, processing update image\n\r"
+#string UPDATE_DRIVER_DONE #language en-US "Done\n\r"
+#string UPDATE_FLASH_RANGE #language en-US "Updating flash area from %08LX to %08LX ...\n\r"
+#string UPDATE_DRIVER_ABORTED #language en-US "Aborted\n\r"
+#string UPDATE_FIRMWARE_VOLUME_FILE #language en-US "Update firmware volume file %g ..\n\r"
+#string UPDATE_FIRMWARE_VOLUME #language en-US "Updating whole firmware volume from %08LX to %08LX ..\n\r"
diff --git a/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegion.c b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegion.c
new file mode 100644
index 0000000000..e432cf4403
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegion.c
@@ -0,0 +1,170 @@
+/** @file
+ Produces the Legacy Region Protocol.
+
+ This generic implementation of the Legacy Region Protocol does not actually
+ perform any lock/unlock operations. This module may be used on platforms
+ that do not provide HW locking of the legacy memory regions. It can also
+ be used as a template driver for implementing the Legacy Region Protocol on
+ a platform that does support HW locking of the legacy memory regions.
+
+Copyright (c) 2009, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PiDxe.h>
+#include <Protocol/LegacyRegion.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+/**
+ Sets hardware to decode or not decode a region.
+
+ @param This Indicates the EFI_LEGACY_REGION_PROTOCOL instance
+ @param Start Start of region to decode.
+ @param Length Size in bytes of the region.
+ @param On Decode/nondecode flag.
+
+ @retval EFI_SUCCESS Decode range successfully changed.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyRegionDecode (
+ IN EFI_LEGACY_REGION_PROTOCOL *This,
+ IN UINT32 Start,
+ IN UINT32 Length,
+ IN BOOLEAN *On
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets a region to read only.
+
+ @param This Indicates the EFI_LEGACY_REGION_PROTOCOL instance
+ @param Start Start of region to lock.
+ @param Length Size in bytes of the region.
+ @param Granularity Lock attribute affects this granularity in bytes.
+
+ @retval EFI_SUCCESS The region was made read only.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyRegionLock (
+ IN EFI_LEGACY_REGION_PROTOCOL *This,
+ IN UINT32 Start,
+ IN UINT32 Length,
+ OUT UINT32 *Granularity OPTIONAL
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets a region to read only and ensures that flash is locked from being
+ inadvertently modified.
+
+ @param This Indicates the EFI_LEGACY_REGION_PROTOCOL instance
+ @param Start Start of region to lock.
+ @param Length Size in bytes of the region.
+ @param Granularity Lock attribute affects this granularity in bytes.
+
+ @retval EFI_SUCCESS The region was made read only and flash is locked.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyRegionBootLock (
+ IN EFI_LEGACY_REGION_PROTOCOL *This,
+ IN UINT32 Start,
+ IN UINT32 Length,
+ OUT UINT32 *Granularity OPTIONAL
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets a region to read-write.
+
+ @param This Indicates the EFI_LEGACY_REGION_PROTOCOL instance
+ @param Start Start of region to lock.
+ @param Length Size in bytes of the region.
+ @param Granularity Lock attribute affects this granularity in bytes.
+
+ @retval EFI_SUCCESS The region was successfully made read-write.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyRegionUnlock (
+ IN EFI_LEGACY_REGION_PROTOCOL *This,
+ IN UINT32 Start,
+ IN UINT32 Length,
+ OUT UINT32 *Granularity OPTIONAL
+ )
+{
+ return EFI_SUCCESS;
+}
+
+//
+// Module global for the handle the Legacy Region Protocol is installed
+//
+EFI_HANDLE mLegacyRegionHandle = NULL;
+
+//
+// Module global for the Legacy Region Protocol instance that is installed onto
+// mLegacyRegionHandle
+//
+EFI_LEGACY_REGION_PROTOCOL mLegacyRegion = {
+ LegacyRegionDecode,
+ LegacyRegionLock,
+ LegacyRegionBootLock,
+ LegacyRegionUnlock
+};
+
+/**
+ The user Entry Point for module LegacyRegionDxe. The user code starts with this function.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+ @retval other Some error occurs when executing this entry point.
+
+**/
+EFI_STATUS
+EFIAPI
+LegacyRegionInstall (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Make sure the Legacy Region Protocol is not already installed in the system
+ //
+ ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiLegacyRegionProtocolGuid);
+
+ //
+ // Install the protocol on a new handle.
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &mLegacyRegionHandle,
+ &gEfiLegacyRegionProtocolGuid, &mLegacyRegion,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.inf b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.inf
new file mode 100644
index 0000000000..f8e5639dec
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.inf
@@ -0,0 +1,55 @@
+## @file
+# Produces Framework Legacy Region Protocol.
+#
+# This generic implementation of the Legacy Region Protocol does not actually
+# perform any lock/unlock operations. This module may be used on platforms
+# that do not provide HW locking of the legacy memory regions. It can also
+# be used as a template driver for implementing the Legacy Region Protocol on
+# a platform that does support HW locking of the legacy memory regions.
+#
+# Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = LegacyRegionDxe
+ MODULE_UNI_FILE = LegacyRegionDxe.uni
+ FILE_GUID = 8C439043-85CA-467a-96F1-CB14F4D0DCDA
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = LegacyRegionInstall
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ LegacyRegion.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+
+[LibraryClasses]
+ UefiDriverEntryPoint
+ DebugLib
+ UefiBootServicesTableLib
+
+[Protocols]
+ gEfiLegacyRegionProtocolGuid ## PRODUCES
+
+[Depex]
+ TRUE
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ LegacyRegionDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.uni b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.uni
new file mode 100644
index 0000000000..385e2701b5
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxe.uni
@@ -0,0 +1,26 @@
+// /** @file
+// Produces Framework Legacy Region Protocol.
+//
+// This generic implementation of the Legacy Region Protocol does not actually
+// perform any lock/unlock operations. This module may be used on platforms
+// that do not provide HW locking of the legacy memory regions. It can also
+// be used as a template driver for implementing the Legacy Region Protocol on
+// a platform that does support HW locking of the legacy memory regions.
+//
+// Copyright (c) 2009 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces Framework Legacy Region Protocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "This generic implementation of the Legacy Region Protocol does not actually perform any lock/unlock operations. This module may be used on platforms that do not provide HW locking of the legacy memory regions. It can also be used as a template driver for implementing the Legacy Region Protocol on a platform that does support HW locking of the legacy memory regions."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxeExtra.uni
new file mode 100644
index 0000000000..f94ed593c9
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/LegacyRegionDxe/LegacyRegionDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// LegacyRegionDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Legacy Region DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtraction.c b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtraction.c
new file mode 100644
index 0000000000..cacac486bb
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtraction.c
@@ -0,0 +1,1456 @@
+/** @file
+ Section Extraction Protocol implementation.
+
+ Stream database is implemented as a linked list of section streams,
+ where each stream contains a linked list of children, which may be leaves or
+ encapsulations.
+
+ Children that are encapsulations generate new stream entries
+ when they are created. Streams can also be created by calls to
+ SEP->OpenSectionStream().
+
+ The database is only created far enough to return the requested data from
+ any given stream, or to determine that the requested data is not found.
+
+ If a GUIDed encapsulation is encountered, there are three possiblilites.
+
+ 1) A support protocol is found, in which the stream is simply processed with
+ the support protocol.
+
+ 2) A support protocol is not found, but the data is available to be read
+ without processing. In this case, the database is built up through the
+ recursions to return the data, and a RPN event is set that will enable
+ the stream in question to be refreshed if and when the required section
+ extraction protocol is published.This insures the AuthenticationStatus
+ does not become stale in the cache.
+
+ 3) A support protocol is not found, and the data is not available to be read
+ without it. This results in EFI_PROTOCOL_ERROR.
+
+Copyright (c) 2006 - 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.
+
+**/
+
+#include <FrameworkDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiLib.h>
+#include <Protocol/Decompress.h>
+#include <Protocol/GuidedSectionExtraction.h>
+#include <Protocol/SectionExtraction.h>
+
+//
+// Local defines and typedefs
+//
+#define FRAMEWORK_SECTION_CHILD_SIGNATURE SIGNATURE_32('S','X','F','S')
+#define CHILD_SECTION_NODE_FROM_LINK(Node) \
+ CR (Node, FRAMEWORK_SECTION_CHILD_NODE, Link, FRAMEWORK_SECTION_CHILD_SIGNATURE)
+
+typedef struct {
+ UINT32 Signature;
+ LIST_ENTRY Link;
+ UINT32 Type;
+ UINT32 Size;
+ //
+ // StreamBase + OffsetInStream == pointer to section header in stream. The
+ // stream base is always known when walking the sections within.
+ //
+ UINT32 OffsetInStream;
+ //
+ // Then EncapsulatedStreamHandle below is always 0 if the section is NOT an
+ // encapsulating section. Otherwise, it contains the stream handle
+ // of the encapsulated stream. This handle is ALWAYS produced any time an
+ // encapsulating child is encountered, irrespective of whether the
+ // encapsulated stream is processed further.
+ //
+ UINTN EncapsulatedStreamHandle;
+ EFI_GUID *EncapsulationGuid;
+ //
+ // If the section REQUIRES an extraction protocol, register for RPN
+ // when the required GUIDed extraction protocol becomes available.
+ //
+ EFI_EVENT Event;
+} FRAMEWORK_SECTION_CHILD_NODE;
+
+#define FRAMEWORK_SECTION_STREAM_SIGNATURE SIGNATURE_32('S','X','S','S')
+#define STREAM_NODE_FROM_LINK(Node) \
+ CR (Node, FRAMEWORK_SECTION_STREAM_NODE, Link, FRAMEWORK_SECTION_STREAM_SIGNATURE)
+
+typedef struct {
+ UINT32 Signature;
+ LIST_ENTRY Link;
+ UINTN StreamHandle;
+ UINT8 *StreamBuffer;
+ UINTN StreamLength;
+ LIST_ENTRY Children;
+ //
+ // Authentication status is from GUIDed encapsulations.
+ //
+ UINT32 AuthenticationStatus;
+} FRAMEWORK_SECTION_STREAM_NODE;
+
+#define NULL_STREAM_HANDLE 0
+
+typedef struct {
+ FRAMEWORK_SECTION_CHILD_NODE *ChildNode;
+ FRAMEWORK_SECTION_STREAM_NODE *ParentStream;
+ VOID *Registration;
+} RPN_EVENT_CONTEXT;
+
+/**
+ SEP member function. This function creates and returns a new section stream
+ handle to represent the new section stream.
+
+ @param This Indicates the calling context.
+ @param SectionStreamLength Size in bytes of the section stream.
+ @param SectionStream Buffer containing the new section stream.
+ @param SectionStreamHandle A pointer to a caller allocated UINTN that on output
+ contains the new section stream handle.
+
+ @retval EFI_SUCCESS Section wase opened successfully.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_INVALID_PARAMETER Section stream does not end concident with end of
+ last section.
+
+**/
+EFI_STATUS
+EFIAPI
+OpenSectionStream (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN SectionStreamLength,
+ IN VOID *SectionStream,
+ OUT UINTN *SectionStreamHandle
+ )
+;
+
+/**
+ SEP member function. Retrieves requested section from section stream.
+
+ @param This Pointer to SEP instance.
+ @param SectionStreamHandle The section stream from which to extract the requested
+ section.
+ @param SectionType A pointer to the type of section to search for.
+ @param SectionDefinitionGuid If the section type is EFI_SECTION_GUID_DEFINED, then
+ SectionDefinitionGuid indicates which of these types
+ of sections to search for.
+ @param SectionInstance Indicates which instance of the requested section to
+ return.
+ @param Buffer Double indirection to buffer. If *Buffer is non-null on
+ input, then the buffer is caller allocated. If
+ *Buffer is NULL, then the buffer is callee allocated.
+ In either case, the required buffer size is returned
+ in *BufferSize.
+ @param BufferSize On input, indicates the size of *Buffer if *Buffer is
+ non-null on input. On output, indicates the required
+ size (allocated size if callee allocated) of *Buffer.
+ @param AuthenticationStatus Indicates the authentication status of the retrieved
+ section.
+
+
+ @retval EFI_SUCCESS Section was retrieved successfully
+ @retval EFI_PROTOCOL_ERROR A GUID defined section was encountered in the section
+ stream with its EFI_GUIDED_SECTION_PROCESSING_REQUIRED
+ bit set, but there was no corresponding GUIDed Section
+ Extraction Protocol in the handle database. *Buffer is
+ unmodified.
+ @retval EFI_NOT_FOUND An error was encountered when parsing the SectionStream.
+ This indicates the SectionStream is not correctly
+ formatted.
+ @retval EFI_NOT_FOUND The requested section does not exist.
+ @retval EFI_OUT_OF_RESOURCES The system has insufficient resources to process the
+ request.
+ @retval EFI_INVALID_PARAMETER The SectionStreamHandle does not exist.
+ @retval EFI_WARN_TOO_SMALL The size of the caller allocated input buffer is
+ insufficient to contain the requested section. The
+ input buffer is filled and contents are section contents
+ are truncated.
+
+**/
+EFI_STATUS
+EFIAPI
+GetSection (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN SectionStreamHandle,
+ IN EFI_SECTION_TYPE *SectionType,
+ IN EFI_GUID *SectionDefinitionGuid,
+ IN UINTN SectionInstance,
+ IN VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT UINT32 *AuthenticationStatus
+ )
+;
+
+/**
+ SEP member function. Deletes an existing section stream
+
+ @param This Indicates the calling context.
+ @param StreamHandleToClose Indicates the stream to close
+
+ @retval EFI_SUCCESS Section stream was closed successfully.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_INVALID_PARAMETER Section stream does not end concident with end of
+ last section.
+
+**/
+EFI_STATUS
+EFIAPI
+CloseSectionStream (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN StreamHandleToClose
+ )
+;
+
+//
+// Module globals
+//
+LIST_ENTRY mStreamRoot = INITIALIZE_LIST_HEAD_VARIABLE (mStreamRoot);
+
+EFI_HANDLE mSectionExtractionHandle = NULL;
+
+EFI_SECTION_EXTRACTION_PROTOCOL mSectionExtraction = {
+ OpenSectionStream,
+ GetSection,
+ CloseSectionStream
+};
+
+/**
+ Entry point of the section extraction code. Initializes an instance of the
+ section extraction interface and installs it on a new handle.
+
+ @param ImageHandle A handle for the image that is initializing this driver
+ @param SystemTable A pointer to the EFI system table
+
+ @retval EFI_SUCCESS Driver initialized successfully
+ @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources
+
+**/
+EFI_STATUS
+EFIAPI
+SectionExtractionEntryPoint (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Install SEP to a new handle
+ //
+ Status = gBS->InstallProtocolInterface (
+ &mSectionExtractionHandle,
+ &gEfiSectionExtractionProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &mSectionExtraction
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
+
+/**
+
+ Check if a stream is valid.
+
+ @param SectionStream The section stream to be checked
+ @param SectionStreamLength The length of section stream
+
+ @return A boolean value indicating the validness of the section stream.
+
+**/
+BOOLEAN
+IsValidSectionStream (
+ IN VOID *SectionStream,
+ IN UINTN SectionStreamLength
+ )
+{
+ UINTN TotalLength;
+ UINTN SectionLength;
+ EFI_COMMON_SECTION_HEADER *SectionHeader;
+ EFI_COMMON_SECTION_HEADER *NextSectionHeader;
+
+ TotalLength = 0;
+ SectionHeader = (EFI_COMMON_SECTION_HEADER *)SectionStream;
+
+ while (TotalLength < SectionStreamLength) {
+ if (IS_SECTION2 (SectionHeader)) {
+ SectionLength = SECTION2_SIZE (SectionHeader);
+ } else {
+ SectionLength = SECTION_SIZE (SectionHeader);
+ }
+ TotalLength += SectionLength;
+
+ if (TotalLength == SectionStreamLength) {
+ return TRUE;
+ }
+
+ //
+ // Move to the next byte following the section...
+ //
+ SectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) SectionHeader + SectionLength);
+
+ //
+ // Figure out where the next section begins
+ //
+ NextSectionHeader = ALIGN_POINTER(SectionHeader, 4);
+ TotalLength += (UINTN) NextSectionHeader - (UINTN) SectionHeader;
+ SectionHeader = NextSectionHeader;
+ }
+
+ ASSERT (FALSE);
+ return FALSE;
+}
+
+/**
+ Worker function. Constructor for section streams.
+
+ @param SectionStreamLength Size in bytes of the section stream.
+ @param SectionStream Buffer containing the new section stream.
+ @param AllocateBuffer Indicates whether the stream buffer is to be copied
+ or the input buffer is to be used in place.
+ @param AuthenticationStatus Indicates the default authentication status for the
+ new stream.
+ @param SectionStreamHandle A pointer to a caller allocated section stream handle.
+
+ @retval EFI_SUCCESS Stream was added to stream database.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+
+**/
+EFI_STATUS
+OpenSectionStreamEx (
+ IN UINTN SectionStreamLength,
+ IN VOID *SectionStream,
+ IN BOOLEAN AllocateBuffer,
+ IN UINT32 AuthenticationStatus,
+ OUT UINTN *SectionStreamHandle
+ )
+{
+ FRAMEWORK_SECTION_STREAM_NODE *NewStream;
+ EFI_TPL OldTpl;
+
+ //
+ // Allocate a new stream
+ //
+ NewStream = AllocatePool (sizeof (FRAMEWORK_SECTION_STREAM_NODE));
+ if (NewStream == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ if (AllocateBuffer) {
+ //
+ // if we're here, we're double buffering, allocate the buffer and copy the
+ // data in
+ //
+ if (SectionStreamLength > 0) {
+ NewStream->StreamBuffer = AllocatePool (SectionStreamLength);
+ if (NewStream->StreamBuffer == NULL) {
+ FreePool (NewStream);
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Copy in stream data
+ //
+ CopyMem (NewStream->StreamBuffer, SectionStream, SectionStreamLength);
+ } else {
+ //
+ // It's possible to have a zero length section stream.
+ //
+ NewStream->StreamBuffer = NULL;
+ }
+ } else {
+ //
+ // If were here, the caller has supplied the buffer (it's an internal call)
+ // so just assign the buffer. This happens when we open section streams
+ // as a result of expanding an encapsulating section.
+ //
+ NewStream->StreamBuffer = SectionStream;
+ }
+
+ //
+ // Initialize the rest of the section stream
+ //
+ NewStream->Signature = FRAMEWORK_SECTION_STREAM_SIGNATURE;
+ NewStream->StreamHandle = (UINTN) NewStream;
+ NewStream->StreamLength = SectionStreamLength;
+ InitializeListHead (&NewStream->Children);
+ NewStream->AuthenticationStatus = AuthenticationStatus;
+
+ //
+ // Add new stream to stream list
+ //
+ OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
+ InsertTailList (&mStreamRoot, &NewStream->Link);
+ gBS->RestoreTPL (OldTpl);
+
+ *SectionStreamHandle = NewStream->StreamHandle;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ SEP member function. This function creates and returns a new section stream
+ handle to represent the new section stream.
+
+ @param This Indicates the calling context.
+ @param SectionStreamLength Size in bytes of the section stream.
+ @param SectionStream Buffer containing the new section stream.
+ @param SectionStreamHandle A pointer to a caller allocated UINTN that on output
+ contains the new section stream handle.
+
+ @retval EFI_SUCCESS Section wase opened successfully.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_INVALID_PARAMETER Section stream does not end concident with end of
+ last section.
+
+**/
+EFI_STATUS
+EFIAPI
+OpenSectionStream (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN SectionStreamLength,
+ IN VOID *SectionStream,
+ OUT UINTN *SectionStreamHandle
+ )
+{
+ //
+ // Check to see section stream looks good...
+ //
+ if (!IsValidSectionStream (SectionStream, SectionStreamLength)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ return OpenSectionStreamEx (
+ SectionStreamLength,
+ SectionStream,
+ TRUE,
+ 0,
+ SectionStreamHandle
+ );
+}
+
+/**
+ Worker function. Determine if the input stream:child matches the input type.
+
+ @param Stream Indicates the section stream associated with the child
+ @param Child Indicates the child to check
+ @param SearchType Indicates the type of section to check against for
+ @param SectionDefinitionGuid Indicates the GUID to check against if the type is
+ EFI_SECTION_GUID_DEFINED
+
+ @retval TRUE The child matches
+ @retval FALSE The child doesn't match
+
+**/
+BOOLEAN
+ChildIsType (
+ IN FRAMEWORK_SECTION_STREAM_NODE *Stream,
+ IN FRAMEWORK_SECTION_CHILD_NODE *Child,
+ IN EFI_SECTION_TYPE SearchType,
+ IN EFI_GUID *SectionDefinitionGuid
+ )
+{
+ EFI_GUID_DEFINED_SECTION *GuidedSection;
+
+ if (SearchType == EFI_SECTION_ALL) {
+ return TRUE;
+ }
+ if (Child->Type != SearchType) {
+ return FALSE;
+ }
+ if ((SearchType != EFI_SECTION_GUID_DEFINED) || (SectionDefinitionGuid == NULL)) {
+ return TRUE;
+ }
+ GuidedSection = (EFI_GUID_DEFINED_SECTION * )(Stream->StreamBuffer + Child->OffsetInStream);
+ if (IS_SECTION2 (GuidedSection)) {
+ return CompareGuid (&(((EFI_GUID_DEFINED_SECTION2 *) GuidedSection)->SectionDefinitionGuid), SectionDefinitionGuid);
+ } else {
+ return CompareGuid (&GuidedSection->SectionDefinitionGuid, SectionDefinitionGuid);
+ }
+}
+
+/**
+ Create a protocol notification event and return it.
+
+ @param ProtocolGuid Protocol to register notification event on.
+ @param NotifyTpl Maximum TPL to signal the NotifyFunction.
+ @param NotifyFunction EFI notification routine.
+ @param NotifyContext Context passed into Event when it is created.
+ @param Registration Registration key returned from RegisterProtocolNotify().
+ @param SignalFlag Boolean value to decide whether kick the event after register or not.
+
+ @return The EFI_EVENT that has been registered to be signaled when a ProtocolGuid
+ is added to the system.
+
+**/
+EFI_EVENT
+CreateProtocolNotifyEvent (
+ IN EFI_GUID *ProtocolGuid,
+ IN EFI_TPL NotifyTpl,
+ IN EFI_EVENT_NOTIFY NotifyFunction,
+ IN VOID *NotifyContext,
+ OUT VOID **Registration,
+ IN BOOLEAN SignalFlag
+ )
+{
+ EFI_STATUS Status;
+ EFI_EVENT Event;
+
+ //
+ // Create the event
+ //
+
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ NotifyTpl,
+ NotifyFunction,
+ NotifyContext,
+ &Event
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Register for protocol notifactions on this event
+ //
+
+ Status = gBS->RegisterProtocolNotify (
+ ProtocolGuid,
+ Event,
+ Registration
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ if (SignalFlag) {
+ //
+ // Kick the event so we will perform an initial pass of
+ // current installed drivers
+ //
+ gBS->SignalEvent (Event);
+ }
+
+ return Event;
+}
+
+/**
+ Verify the Guided Section GUID by checking if there is the Guided Section GUID configuration table recorded the GUID itself.
+
+ @param GuidedSectionGuid The Guided Section GUID.
+ @param GuidedSectionExtraction A pointer to the pointer to the supported Guided Section Extraction Protocol
+ for the Guided Section.
+
+ @return TRUE The GuidedSectionGuid could be identified, and the pointer to
+ the Guided Section Extraction Protocol will be returned to *GuidedSectionExtraction.
+ @return FALSE The GuidedSectionGuid could not be identified, or
+ the Guided Section Extraction Protocol has not been installed yet.
+
+**/
+BOOLEAN
+VerifyGuidedSectionGuid (
+ IN EFI_GUID *GuidedSectionGuid,
+ OUT EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL **GuidedSectionExtraction
+ )
+{
+ EFI_GUID *GuidRecorded;
+ VOID *Interface;
+ EFI_STATUS Status;
+
+ //
+ // Check if there is the Guided Section GUID configuration table recorded the GUID itself.
+ //
+ Status = EfiGetSystemConfigurationTable (GuidedSectionGuid, (VOID **) &GuidRecorded);
+ if (Status == EFI_SUCCESS) {
+ if (CompareGuid (GuidRecorded, GuidedSectionGuid)) {
+ //
+ // Found the recorded GuidedSectionGuid.
+ //
+ Status = gBS->LocateProtocol (GuidedSectionGuid, NULL, (VOID **) &Interface);
+ if (!EFI_ERROR (Status) && Interface != NULL) {
+ //
+ // Found the supported Guided Section Extraction Porotocol for the Guided Section.
+ //
+ *GuidedSectionExtraction = (EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *) Interface;
+ return TRUE;
+ }
+ return FALSE;
+ }
+ }
+
+ return FALSE;
+}
+
+/**
+ RPN callback function.
+ 1. Initialize the section stream when the GUIDED_SECTION_EXTRACTION_PROTOCOL is installed.
+ 2. Removes a stale section stream and re-initializes it with an updated AuthenticationStatus.
+
+ @param Event The event that fired
+ @param RpnContext A pointer to the context that allows us to identify
+ the relevent encapsulation.
+
+**/
+VOID
+EFIAPI
+NotifyGuidedExtraction (
+ IN EFI_EVENT Event,
+ IN VOID *RpnContext
+ )
+{
+ EFI_STATUS Status;
+ EFI_GUID_DEFINED_SECTION *GuidedHeader;
+ EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *GuidedExtraction;
+ VOID *NewStreamBuffer;
+ UINTN NewStreamBufferSize;
+ UINT32 AuthenticationStatus;
+ RPN_EVENT_CONTEXT *Context;
+
+ Context = RpnContext;
+ Status = EFI_SUCCESS;
+ if (Context->ChildNode->EncapsulatedStreamHandle != NULL_STREAM_HANDLE) {
+ Status = CloseSectionStream (&mSectionExtraction, Context->ChildNode->EncapsulatedStreamHandle);
+ }
+ if (!EFI_ERROR (Status)) {
+ //
+ // The stream is not initialized, open it.
+ // Or the stream closed successfully, so re-open the stream with correct AuthenticationStatus.
+ //
+
+ GuidedHeader = (EFI_GUID_DEFINED_SECTION *)
+ (Context->ParentStream->StreamBuffer + Context->ChildNode->OffsetInStream);
+ ASSERT (GuidedHeader->CommonHeader.Type == EFI_SECTION_GUID_DEFINED);
+
+ if (!VerifyGuidedSectionGuid (Context->ChildNode->EncapsulationGuid, &GuidedExtraction)) {
+ return;
+ }
+
+ Status = GuidedExtraction->ExtractSection (
+ GuidedExtraction,
+ GuidedHeader,
+ &NewStreamBuffer,
+ &NewStreamBufferSize,
+ &AuthenticationStatus
+ );
+ ASSERT_EFI_ERROR (Status);
+ //
+ // OR in the parent stream's aggregate status.
+ //
+ AuthenticationStatus |= Context->ParentStream->AuthenticationStatus & EFI_AGGREGATE_AUTH_STATUS_ALL;
+ Status = OpenSectionStreamEx (
+ NewStreamBufferSize,
+ NewStreamBuffer,
+ FALSE,
+ AuthenticationStatus,
+ &Context->ChildNode->EncapsulatedStreamHandle
+ );
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ //
+ // If above, the stream did not close successfully, it indicates it's
+ // already been closed by someone, so just destroy the event and be done with
+ // it.
+ //
+
+ gBS->CloseEvent (Event);
+ Context->ChildNode->Event = NULL;
+ FreePool (Context);
+}
+
+/**
+ Worker function. Constructor for RPN event if needed to keep AuthenticationStatus
+ cache correct when a missing GUIDED_SECTION_EXTRACTION_PROTOCOL appears...
+
+ @param ParentStream Indicates the parent of the ecnapsulation section (child)
+ @param ChildNode Indicates the child node that is the encapsulation section.
+
+**/
+VOID
+CreateGuidedExtractionRpnEvent (
+ IN FRAMEWORK_SECTION_STREAM_NODE *ParentStream,
+ IN FRAMEWORK_SECTION_CHILD_NODE *ChildNode
+ )
+{
+ RPN_EVENT_CONTEXT *Context;
+
+ //
+ // Allocate new event structure and context
+ //
+ Context = AllocatePool (sizeof (RPN_EVENT_CONTEXT));
+ ASSERT (Context != NULL);
+
+ Context->ChildNode = ChildNode;
+ Context->ParentStream = ParentStream;
+
+ Context->ChildNode->Event = CreateProtocolNotifyEvent (
+ Context->ChildNode->EncapsulationGuid,
+ TPL_NOTIFY,
+ NotifyGuidedExtraction,
+ Context,
+ &Context->Registration,
+ FALSE
+ );
+}
+
+/**
+ Worker function. Constructor for new child nodes.
+
+ @param Stream Indicates the section stream in which to add the child.
+ @param ChildOffset Indicates the offset in Stream that is the beginning
+ of the child section.
+ @param ChildNode Indicates the Callee allocated and initialized child.
+
+ @retval EFI_SUCCESS Child node was found and returned.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_PROTOCOL_ERROR Encapsulation sections produce new stream handles when
+ the child node is created. If the section type is GUID
+ defined, and the extraction GUID does not exist, and
+ producing the stream requires the GUID, then a protocol
+ error is generated and no child is produced.
+ Values returned by OpenSectionStreamEx.
+
+**/
+EFI_STATUS
+CreateChildNode (
+ IN FRAMEWORK_SECTION_STREAM_NODE *Stream,
+ IN UINT32 ChildOffset,
+ OUT FRAMEWORK_SECTION_CHILD_NODE **ChildNode
+ )
+{
+ EFI_STATUS Status;
+ EFI_COMMON_SECTION_HEADER *SectionHeader;
+ EFI_COMPRESSION_SECTION *CompressionHeader;
+ EFI_GUID_DEFINED_SECTION *GuidedHeader;
+ EFI_DECOMPRESS_PROTOCOL *Decompress;
+ EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *GuidedExtraction;
+ VOID *NewStreamBuffer;
+ VOID *ScratchBuffer;
+ UINT32 ScratchSize;
+ UINTN NewStreamBufferSize;
+ UINT32 AuthenticationStatus;
+ VOID *CompressionSource;
+ UINT32 CompressionSourceSize;
+ UINT32 UncompressedLength;
+ UINT8 CompressionType;
+ UINT16 GuidedSectionAttributes;
+
+ FRAMEWORK_SECTION_CHILD_NODE *Node;
+
+ SectionHeader = (EFI_COMMON_SECTION_HEADER *) (Stream->StreamBuffer + ChildOffset);
+
+ //
+ // Allocate a new node
+ //
+ *ChildNode = AllocateZeroPool (sizeof (FRAMEWORK_SECTION_CHILD_NODE));
+ Node = *ChildNode;
+ if (Node == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Now initialize it
+ //
+ Node->Signature = FRAMEWORK_SECTION_CHILD_SIGNATURE;
+ Node->Type = SectionHeader->Type;
+ if (IS_SECTION2 (SectionHeader)) {
+ Node->Size = SECTION2_SIZE (SectionHeader);
+ } else {
+ Node->Size = SECTION_SIZE (SectionHeader);
+ }
+ Node->OffsetInStream = ChildOffset;
+ Node->EncapsulatedStreamHandle = NULL_STREAM_HANDLE;
+ Node->EncapsulationGuid = NULL;
+
+ //
+ // If it's an encapsulating section, then create the new section stream also
+ //
+ switch (Node->Type) {
+ case EFI_SECTION_COMPRESSION:
+ //
+ // Get the CompressionSectionHeader
+ //
+ if (Node->Size < sizeof (EFI_COMPRESSION_SECTION)) {
+ FreePool (Node);
+ return EFI_NOT_FOUND;
+ }
+
+ CompressionHeader = (EFI_COMPRESSION_SECTION *) SectionHeader;
+
+ if (IS_SECTION2 (CompressionHeader)) {
+ CompressionSource = (VOID *) ((UINT8 *) CompressionHeader + sizeof (EFI_COMPRESSION_SECTION2));
+ CompressionSourceSize = (UINT32) (SECTION2_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION2));
+ UncompressedLength = ((EFI_COMPRESSION_SECTION2 *) CompressionHeader)->UncompressedLength;
+ CompressionType = ((EFI_COMPRESSION_SECTION2 *) CompressionHeader)->CompressionType;
+ } else {
+ CompressionSource = (VOID *) ((UINT8 *) CompressionHeader + sizeof (EFI_COMPRESSION_SECTION));
+ CompressionSourceSize = (UINT32) (SECTION_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION));
+ UncompressedLength = CompressionHeader->UncompressedLength;
+ CompressionType = CompressionHeader->CompressionType;
+ }
+
+ //
+ // Allocate space for the new stream
+ //
+ if (UncompressedLength > 0) {
+ NewStreamBufferSize = UncompressedLength;
+ NewStreamBuffer = AllocatePool (NewStreamBufferSize);
+ if (NewStreamBuffer == NULL) {
+ FreePool (Node);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ if (CompressionType == EFI_NOT_COMPRESSED) {
+ //
+ // stream is not actually compressed, just encapsulated. So just copy it.
+ //
+ CopyMem (NewStreamBuffer, CompressionSource, NewStreamBufferSize);
+ } else if (CompressionType == EFI_STANDARD_COMPRESSION) {
+ //
+ // Only support the EFI_SATNDARD_COMPRESSION algorithm.
+ //
+
+ //
+ // Decompress the stream
+ //
+ Status = gBS->LocateProtocol (&gEfiDecompressProtocolGuid, NULL, (VOID **)&Decompress);
+
+ ASSERT_EFI_ERROR (Status);
+
+ Status = Decompress->GetInfo (
+ Decompress,
+ CompressionSource,
+ CompressionSourceSize,
+ (UINT32 *)&NewStreamBufferSize,
+ &ScratchSize
+ );
+ if (EFI_ERROR (Status) || (NewStreamBufferSize != UncompressedLength)) {
+ FreePool (Node);
+ FreePool (NewStreamBuffer);
+ if (!EFI_ERROR (Status)) {
+ Status = EFI_BAD_BUFFER_SIZE;
+ }
+ return Status;
+ }
+
+ ScratchBuffer = AllocatePool (ScratchSize);
+ if (ScratchBuffer == NULL) {
+ FreePool (Node);
+ FreePool (NewStreamBuffer);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Status = Decompress->Decompress (
+ Decompress,
+ CompressionSource,
+ CompressionSourceSize,
+ NewStreamBuffer,
+ (UINT32)NewStreamBufferSize,
+ ScratchBuffer,
+ ScratchSize
+ );
+ FreePool (ScratchBuffer);
+ if (EFI_ERROR (Status)) {
+ FreePool (Node);
+ FreePool (NewStreamBuffer);
+ return Status;
+ }
+ }
+ } else {
+ NewStreamBuffer = NULL;
+ NewStreamBufferSize = 0;
+ }
+
+ Status = OpenSectionStreamEx (
+ NewStreamBufferSize,
+ NewStreamBuffer,
+ FALSE,
+ Stream->AuthenticationStatus,
+ &Node->EncapsulatedStreamHandle
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Node);
+ FreePool (NewStreamBuffer);
+ return Status;
+ }
+ break;
+
+ case EFI_SECTION_GUID_DEFINED:
+ GuidedHeader = (EFI_GUID_DEFINED_SECTION *) SectionHeader;
+ if (IS_SECTION2 (GuidedHeader)) {
+ Node->EncapsulationGuid = &(((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->SectionDefinitionGuid);
+ GuidedSectionAttributes = ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->Attributes;
+ } else {
+ Node->EncapsulationGuid = &GuidedHeader->SectionDefinitionGuid;
+ GuidedSectionAttributes = GuidedHeader->Attributes;
+ }
+ if (VerifyGuidedSectionGuid (Node->EncapsulationGuid, &GuidedExtraction)) {
+ //
+ // NewStreamBuffer is always allocated by ExtractSection... No caller
+ // allocation here.
+ //
+ Status = GuidedExtraction->ExtractSection (
+ GuidedExtraction,
+ GuidedHeader,
+ &NewStreamBuffer,
+ &NewStreamBufferSize,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (*ChildNode);
+ return EFI_PROTOCOL_ERROR;
+ }
+
+ //
+ // Make sure we initialize the new stream with the correct
+ // authentication status for both aggregate and local status fields.
+ //
+ if ((GuidedSectionAttributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) == EFI_GUIDED_SECTION_AUTH_STATUS_VALID) {
+ //
+ // OR in the parent stream's aggregate status.
+ //
+ AuthenticationStatus |= Stream->AuthenticationStatus & EFI_AGGREGATE_AUTH_STATUS_ALL;
+ } else {
+ //
+ // since there's no authentication data contributed by the section,
+ // just inherit the full value from our immediate parent.
+ //
+ AuthenticationStatus = Stream->AuthenticationStatus;
+ }
+
+ Status = OpenSectionStreamEx (
+ NewStreamBufferSize,
+ NewStreamBuffer,
+ FALSE,
+ AuthenticationStatus,
+ &Node->EncapsulatedStreamHandle
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (*ChildNode);
+ FreePool (NewStreamBuffer);
+ return Status;
+ }
+ } else {
+ //
+ // There's no GUIDed section extraction protocol available.
+ //
+ if ((GuidedSectionAttributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == EFI_GUIDED_SECTION_PROCESSING_REQUIRED) {
+ //
+ // If the section REQUIRES an extraction protocol, register for RPN
+ // when the required GUIDed extraction protocol becomes available.
+ //
+ AuthenticationStatus = 0;
+ CreateGuidedExtractionRpnEvent (Stream, Node);
+ } else {
+ //
+ // Figure out the proper authentication status
+ //
+ AuthenticationStatus = Stream->AuthenticationStatus;
+ if ((GuidedSectionAttributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) == EFI_GUIDED_SECTION_AUTH_STATUS_VALID) {
+ //
+ // The local status of the new stream is contained in
+ // AuthenticaionStatus. This value needs to be ORed into the
+ // Aggregate bits also...
+ //
+
+ //
+ // Clear out and initialize the local status
+ //
+ AuthenticationStatus &= ~EFI_LOCAL_AUTH_STATUS_ALL;
+ AuthenticationStatus |= EFI_LOCAL_AUTH_STATUS_IMAGE_SIGNED | EFI_LOCAL_AUTH_STATUS_NOT_TESTED;
+ //
+ // OR local status into aggregate status
+ //
+ AuthenticationStatus |= AuthenticationStatus >> 16;
+ }
+
+ if (IS_SECTION2 (GuidedHeader)) {
+ Status = OpenSectionStreamEx (
+ SECTION2_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->DataOffset,
+ (UINT8 *) GuidedHeader + ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->DataOffset,
+ TRUE,
+ AuthenticationStatus,
+ &Node->EncapsulatedStreamHandle
+ );
+ } else {
+ Status = OpenSectionStreamEx (
+ SECTION_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION *) GuidedHeader)->DataOffset,
+ (UINT8 *) GuidedHeader + ((EFI_GUID_DEFINED_SECTION *) GuidedHeader)->DataOffset,
+ TRUE,
+ AuthenticationStatus,
+ &Node->EncapsulatedStreamHandle
+ );
+ }
+ if (EFI_ERROR (Status)) {
+ FreePool (Node);
+ return Status;
+ }
+ }
+ }
+
+ if ((AuthenticationStatus & EFI_LOCAL_AUTH_STATUS_ALL) ==
+ (EFI_LOCAL_AUTH_STATUS_IMAGE_SIGNED | EFI_LOCAL_AUTH_STATUS_NOT_TESTED)) {
+ //
+ // Need to register for RPN for when the required GUIDed extraction
+ // protocol becomes available. This will enable us to refresh the
+ // AuthenticationStatus cached in the Stream if it's ever requested
+ // again.
+ //
+ CreateGuidedExtractionRpnEvent (Stream, Node);
+ }
+
+ break;
+
+ default:
+
+ //
+ // Nothing to do if it's a leaf
+ //
+ break;
+ }
+
+ //
+ // Last, add the new child node to the stream
+ //
+ InsertTailList (&Stream->Children, &Node->Link);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Worker function Recursively searches / builds section stream database
+ looking for requested section.
+
+
+ @param SourceStream Indicates the section stream in which to do the search.
+ @param SearchType Indicates the type of section to search for.
+ @param SectionInstance Indicates which instance of section to find. This is
+ an in/out parameter to deal with recursions.
+ @param SectionDefinitionGuid Guid of section definition
+ @param FoundChild Output indicating the child node that is found.
+ @param FoundStream Output indicating which section stream the child was
+ found in. If this stream was generated as a result of
+ an encapsulation section, the streamhandle is visible
+ within the SEP driver only.
+ @param AuthenticationStatus Indicates the authentication status of the found section.
+
+ @retval EFI_SUCCESS Child node was found and returned.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_NOT_FOUND Requested child node does not exist.
+ @retval EFI_PROTOCOL_ERROR A required GUIDED section extraction protocol does not
+ exist
+
+**/
+EFI_STATUS
+FindChildNode (
+ IN FRAMEWORK_SECTION_STREAM_NODE *SourceStream,
+ IN EFI_SECTION_TYPE SearchType,
+ IN OUT UINTN *SectionInstance,
+ IN EFI_GUID *SectionDefinitionGuid,
+ OUT FRAMEWORK_SECTION_CHILD_NODE **FoundChild,
+ OUT FRAMEWORK_SECTION_STREAM_NODE **FoundStream,
+ OUT UINT32 *AuthenticationStatus
+ )
+{
+ FRAMEWORK_SECTION_CHILD_NODE *CurrentChildNode;
+ FRAMEWORK_SECTION_CHILD_NODE *RecursedChildNode;
+ FRAMEWORK_SECTION_STREAM_NODE *RecursedFoundStream;
+ UINT32 NextChildOffset;
+ EFI_STATUS ErrorStatus;
+ EFI_STATUS Status;
+
+ CurrentChildNode = NULL;
+ ErrorStatus = EFI_NOT_FOUND;
+
+ if (SourceStream->StreamLength == 0) {
+ return EFI_NOT_FOUND;
+ }
+
+ if (IsListEmpty (&SourceStream->Children) &&
+ SourceStream->StreamLength >= sizeof (EFI_COMMON_SECTION_HEADER)) {
+ //
+ // This occurs when a section stream exists, but no child sections
+ // have been parsed out yet. Therefore, extract the first child and add it
+ // to the list of children so we can get started.
+ // Section stream may contain an array of zero or more bytes.
+ // So, its size should be >= the size of commen section header.
+ //
+ Status = CreateChildNode (SourceStream, 0, &CurrentChildNode);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ //
+ // At least one child has been parsed out of the section stream. So, walk
+ // through the sections that have already been parsed out looking for the
+ // requested section, if necessary, continue parsing section stream and
+ // adding children until either the requested section is found, or we run
+ // out of data
+ //
+ CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetFirstNode(&SourceStream->Children));
+
+ for (;;) {
+ ASSERT (CurrentChildNode != NULL);
+ if (ChildIsType (SourceStream, CurrentChildNode, SearchType, SectionDefinitionGuid)) {
+ //
+ // The type matches, so check the instance count to see if it's the one we want
+ //
+ (*SectionInstance)--;
+ if (*SectionInstance == 0) {
+ //
+ // Got it!
+ //
+ *FoundChild = CurrentChildNode;
+ *FoundStream = SourceStream;
+ *AuthenticationStatus = SourceStream->AuthenticationStatus;
+ return EFI_SUCCESS;
+ }
+ }
+
+ if (CurrentChildNode->EncapsulatedStreamHandle != NULL_STREAM_HANDLE) {
+ //
+ // If the current node is an encapsulating node, recurse into it...
+ //
+ Status = FindChildNode (
+ (FRAMEWORK_SECTION_STREAM_NODE *)CurrentChildNode->EncapsulatedStreamHandle,
+ SearchType,
+ SectionInstance,
+ SectionDefinitionGuid,
+ &RecursedChildNode,
+ &RecursedFoundStream,
+ AuthenticationStatus
+ );
+ //
+ // If the status is not EFI_SUCCESS, just save the error code and continue
+ // to find the request child node in the rest stream.
+ //
+ if (*SectionInstance == 0) {
+ ASSERT_EFI_ERROR (Status);
+ *FoundChild = RecursedChildNode;
+ *FoundStream = RecursedFoundStream;
+ return EFI_SUCCESS;
+ } else {
+ ErrorStatus = Status;
+ }
+ } else if ((CurrentChildNode->Type == EFI_SECTION_GUID_DEFINED) && (SearchType != EFI_SECTION_GUID_DEFINED)) {
+ //
+ // When Node Type is GUIDED section, but Node has no encapsulated data, Node data should not be parsed
+ // because a required GUIDED section extraction protocol does not exist.
+ // If SearchType is not GUIDED section, EFI_PROTOCOL_ERROR should return.
+ //
+ ErrorStatus = EFI_PROTOCOL_ERROR;
+ }
+
+ if (!IsNodeAtEnd (&SourceStream->Children, &CurrentChildNode->Link)) {
+ //
+ // We haven't found the child node we're interested in yet, but there's
+ // still more nodes that have already been parsed so get the next one
+ // and continue searching..
+ //
+ CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetNextNode (&SourceStream->Children, &CurrentChildNode->Link));
+ } else {
+ //
+ // We've exhausted children that have already been parsed, so see if
+ // there's any more data and continue parsing out more children if there
+ // is.
+ //
+ NextChildOffset = CurrentChildNode->OffsetInStream + CurrentChildNode->Size;
+ //
+ // Round up to 4 byte boundary
+ //
+ NextChildOffset += 3;
+ NextChildOffset &= ~(UINTN)3;
+ if (NextChildOffset <= SourceStream->StreamLength - sizeof (EFI_COMMON_SECTION_HEADER)) {
+ //
+ // There's an unparsed child remaining in the stream, so create a new child node
+ //
+ Status = CreateChildNode (SourceStream, NextChildOffset, &CurrentChildNode);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ } else {
+ ASSERT (EFI_ERROR (ErrorStatus));
+ return ErrorStatus;
+ }
+ }
+ }
+}
+
+/**
+ Worker function. Search stream database for requested stream handle.
+
+ @param SearchHandle Indicates which stream to look for.
+ @param FoundStream Output pointer to the found stream.
+
+ @retval EFI_SUCCESS StreamHandle was found and *FoundStream contains
+ the stream node.
+ @retval EFI_NOT_FOUND SearchHandle was not found in the stream database.
+
+**/
+EFI_STATUS
+FindStreamNode (
+ IN UINTN SearchHandle,
+ OUT FRAMEWORK_SECTION_STREAM_NODE **FoundStream
+ )
+{
+ FRAMEWORK_SECTION_STREAM_NODE *StreamNode;
+
+ if (!IsListEmpty (&mStreamRoot)) {
+ StreamNode = STREAM_NODE_FROM_LINK (GetFirstNode (&mStreamRoot));
+ for (;;) {
+ if (StreamNode->StreamHandle == SearchHandle) {
+ *FoundStream = StreamNode;
+ return EFI_SUCCESS;
+ } else if (IsNodeAtEnd (&mStreamRoot, &StreamNode->Link)) {
+ break;
+ } else {
+ StreamNode = STREAM_NODE_FROM_LINK (GetNextNode (&mStreamRoot, &StreamNode->Link));
+ }
+ }
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+/**
+ SEP member function. Retrieves requested section from section stream.
+
+ @param This Pointer to SEP instance.
+ @param SectionStreamHandle The section stream from which to extract the requested
+ section.
+ @param SectionType A pointer to the type of section to search for.
+ @param SectionDefinitionGuid If the section type is EFI_SECTION_GUID_DEFINED, then
+ SectionDefinitionGuid indicates which of these types
+ of sections to search for.
+ @param SectionInstance Indicates which instance of the requested section to
+ return.
+ @param Buffer Double indirection to buffer. If *Buffer is non-null on
+ input, then the buffer is caller allocated. If
+ *Buffer is NULL, then the buffer is callee allocated.
+ In either case, the required buffer size is returned
+ in *BufferSize.
+ @param BufferSize On input, indicates the size of *Buffer if *Buffer is
+ non-null on input. On output, indicates the required
+ size (allocated size if callee allocated) of *Buffer.
+ @param AuthenticationStatus Indicates the authentication status of the retrieved
+ section.
+
+
+ @retval EFI_SUCCESS Section was retrieved successfully
+ @retval EFI_PROTOCOL_ERROR A GUID defined section was encountered in the section
+ stream with its EFI_GUIDED_SECTION_PROCESSING_REQUIRED
+ bit set, but there was no corresponding GUIDed Section
+ Extraction Protocol in the handle database. *Buffer is
+ unmodified.
+ @retval EFI_NOT_FOUND An error was encountered when parsing the SectionStream.
+ This indicates the SectionStream is not correctly
+ formatted.
+ @retval EFI_NOT_FOUND The requested section does not exist.
+ @retval EFI_OUT_OF_RESOURCES The system has insufficient resources to process the
+ request.
+ @retval EFI_INVALID_PARAMETER The SectionStreamHandle does not exist.
+ @retval EFI_WARN_TOO_SMALL The size of the caller allocated input buffer is
+ insufficient to contain the requested section. The
+ input buffer is filled and contents are section contents
+ are truncated.
+
+**/
+EFI_STATUS
+EFIAPI
+GetSection (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN SectionStreamHandle,
+ IN EFI_SECTION_TYPE *SectionType,
+ IN EFI_GUID *SectionDefinitionGuid,
+ IN UINTN SectionInstance,
+ IN VOID **Buffer,
+ IN OUT UINTN *BufferSize,
+ OUT UINT32 *AuthenticationStatus
+ )
+{
+ FRAMEWORK_SECTION_STREAM_NODE *StreamNode;
+ EFI_TPL OldTpl;
+ EFI_STATUS Status;
+ FRAMEWORK_SECTION_CHILD_NODE *ChildNode;
+ FRAMEWORK_SECTION_STREAM_NODE *ChildStreamNode;
+ UINTN CopySize;
+ UINT32 ExtractedAuthenticationStatus;
+ UINTN Instance;
+ UINT8 *CopyBuffer;
+ UINTN SectionSize;
+ EFI_COMMON_SECTION_HEADER *Section;
+
+
+ OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
+ Instance = SectionInstance + 1;
+ ChildStreamNode = NULL;
+
+ //
+ // Locate target stream
+ //
+ Status = FindStreamNode (SectionStreamHandle, &StreamNode);
+ if (EFI_ERROR (Status)) {
+ Status = EFI_INVALID_PARAMETER;
+ goto GetSection_Done;
+ }
+
+ //
+ // Found the stream, now locate and return the appropriate section
+ //
+ if (SectionType == NULL) {
+ //
+ // SectionType == NULL means return the WHOLE section stream...
+ //
+ CopySize = StreamNode->StreamLength;
+ CopyBuffer = StreamNode->StreamBuffer;
+ *AuthenticationStatus = StreamNode->AuthenticationStatus;
+ } else {
+ //
+ // There's a requested section type, so go find it and return it...
+ //
+ Status = FindChildNode (
+ StreamNode,
+ *SectionType,
+ &Instance,
+ SectionDefinitionGuid,
+ &ChildNode,
+ &ChildStreamNode,
+ &ExtractedAuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ goto GetSection_Done;
+ }
+ ASSERT (ChildNode != NULL);
+ ASSERT (ChildStreamNode != NULL);
+ Section = (EFI_COMMON_SECTION_HEADER *) (ChildStreamNode->StreamBuffer + ChildNode->OffsetInStream);
+
+ if (IS_SECTION2 (Section)) {
+ CopySize = SECTION2_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER2);
+ CopyBuffer = (UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER2);
+ } else {
+ CopySize = SECTION_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER);
+ CopyBuffer = (UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER);
+ }
+ *AuthenticationStatus = ExtractedAuthenticationStatus;
+ }
+
+ SectionSize = CopySize;
+ if (*Buffer != NULL) {
+ //
+ // Caller allocated buffer. Fill to size and return required size...
+ //
+ if (*BufferSize < CopySize) {
+ Status = EFI_WARN_BUFFER_TOO_SMALL;
+ CopySize = *BufferSize;
+ }
+ } else {
+ //
+ // Callee allocated buffer. Allocate buffer and return size.
+ //
+ *Buffer = AllocatePool (CopySize);
+ if (*Buffer == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto GetSection_Done;
+ }
+ }
+ CopyMem (*Buffer, CopyBuffer, CopySize);
+ *BufferSize = SectionSize;
+
+GetSection_Done:
+ gBS->RestoreTPL (OldTpl);
+ return Status;
+}
+
+/**
+ Worker function. Destructor for child nodes.
+
+ @param ChildNode Indicates the node to destroy
+
+**/
+VOID
+FreeChildNode (
+ IN FRAMEWORK_SECTION_CHILD_NODE *ChildNode
+ )
+{
+ ASSERT (ChildNode->Signature == FRAMEWORK_SECTION_CHILD_SIGNATURE);
+ //
+ // Remove the child from it's list
+ //
+ RemoveEntryList (&ChildNode->Link);
+
+ if (ChildNode->EncapsulatedStreamHandle != NULL_STREAM_HANDLE) {
+ //
+ // If it's an encapsulating section, we close the resulting section stream.
+ // CloseSectionStream will free all memory associated with the stream.
+ //
+ CloseSectionStream (&mSectionExtraction, ChildNode->EncapsulatedStreamHandle);
+ }
+
+ if (ChildNode->Event != NULL) {
+ gBS->CloseEvent (ChildNode->Event);
+ }
+
+ //
+ // Last, free the child node itself
+ //
+ FreePool (ChildNode);
+}
+
+/**
+ SEP member function. Deletes an existing section stream
+
+ @param This Indicates the calling context.
+ @param StreamHandleToClose Indicates the stream to close
+
+ @retval EFI_SUCCESS Section stream was closed successfully.
+ @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
+ @retval EFI_INVALID_PARAMETER Section stream does not end concident with end of
+ last section.
+
+**/
+EFI_STATUS
+EFIAPI
+CloseSectionStream (
+ IN EFI_SECTION_EXTRACTION_PROTOCOL *This,
+ IN UINTN StreamHandleToClose
+ )
+{
+ FRAMEWORK_SECTION_STREAM_NODE *StreamNode;
+ EFI_TPL OldTpl;
+ EFI_STATUS Status;
+ LIST_ENTRY *Link;
+ FRAMEWORK_SECTION_CHILD_NODE *ChildNode;
+
+ OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
+
+ //
+ // Locate target stream
+ //
+ Status = FindStreamNode (StreamHandleToClose, &StreamNode);
+ if (!EFI_ERROR (Status)) {
+ //
+ // Found the stream, so close it
+ //
+ RemoveEntryList (&StreamNode->Link);
+ while (!IsListEmpty (&StreamNode->Children)) {
+ Link = GetFirstNode (&StreamNode->Children);
+ ChildNode = CHILD_SECTION_NODE_FROM_LINK (Link);
+ FreeChildNode (ChildNode);
+ }
+ FreePool (StreamNode->StreamBuffer);
+ FreePool (StreamNode);
+ Status = EFI_SUCCESS;
+ } else {
+ Status = EFI_INVALID_PARAMETER;
+ }
+
+ gBS->RestoreTPL (OldTpl);
+ return Status;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.inf b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.inf
new file mode 100644
index 0000000000..ab0bd63076
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.inf
@@ -0,0 +1,57 @@
+## @file
+# Section Extraction Dxe Driver produces framework section extract protocol.
+#
+# The section is implemented as a linked list of section streams,
+# where each stream contains a linked list of children, which may be leaves or
+# encapsulations. Encapsulation section will further generate new section stream entries.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SectionExtractionDxe
+ MODULE_UNI_FILE = SectionExtractionDxe.uni
+ FILE_GUID = 801ADCA0-815E-46a4-84F7-657F53621A57
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = SectionExtractionEntryPoint
+
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ SectionExtraction.c
+
+[LibraryClasses]
+ UefiBootServicesTableLib
+ MemoryAllocationLib
+ DebugLib
+ BaseLib
+ BaseMemoryLib
+ UefiDriverEntryPoint
+ UefiLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+
+[Protocols]
+ gEfiSectionExtractionProtocolGuid ## PRODUCES
+ gEfiDecompressProtocolGuid ## SOMETIMES_CONSUMES
+
+[Depex]
+ gEfiDecompressProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ SectionExtractionDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.uni b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.uni
new file mode 100644
index 0000000000..ecbd251b12
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.uni
@@ -0,0 +1,24 @@
+// /** @file
+// Section Extraction Dxe Driver produces framework section extract protocol.
+//
+// The section is implemented as a linked list of section streams,
+// where each stream contains a linked list of children, which may be leaves or
+// encapsulations. Encapsulation section will further generate new section stream entries.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces the framework section extract protocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The section is implemented as a linked list of section streams, where each stream contains a linked list of children, which may be leaves or encapsulations. An encapsulation section will further generate new section of stream entries."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxeExtra.uni
new file mode 100644
index 0000000000..c53ee6bdfb
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxeExtra.uni
@@ -0,0 +1,20 @@
+// /** @file
+// SectionExtractionDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Firmware Storage Extraction DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DataHubStatusCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DataHubStatusCodeWorker.c
new file mode 100644
index 0000000000..5b42395dbd
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DataHubStatusCodeWorker.c
@@ -0,0 +1,376 @@
+/** @file
+ Data Hub status code worker.
+
+ Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "DatahubStatusCodeHandlerDxe.h"
+
+//
+// Initialize FIFO to cache records.
+//
+LIST_ENTRY mRecordsFifo = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsFifo);
+LIST_ENTRY mRecordsBuffer = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsBuffer);
+UINT32 mLogDataHubStatus = 0;
+EFI_EVENT mLogDataHubEvent;
+//
+// Cache data hub protocol.
+//
+EFI_DATA_HUB_PROTOCOL *mDataHubProtocol = NULL;
+
+
+/**
+ Retrieve one record of from free record buffer. This record is removed from
+ free record buffer.
+
+ This function retrieves one record from free record buffer.
+ If the pool has been exhausted, then new memory would be allocated for it.
+
+ @return Pointer to the free record.
+ NULL means failure to allocate new memeory for free record buffer.
+
+**/
+DATA_HUB_STATUS_CODE_DATA_RECORD *
+AcquireRecordBuffer (
+ VOID
+ )
+{
+ DATAHUB_STATUSCODE_RECORD *Record;
+ EFI_TPL CurrentTpl;
+ LIST_ENTRY *Node;
+ UINT32 Index;
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ if (!IsListEmpty (&mRecordsBuffer)) {
+ //
+ // Strip one entry from free record buffer.
+ //
+ Node = GetFirstNode (&mRecordsBuffer);
+ RemoveEntryList (Node);
+
+ Record = BASE_CR (Node, DATAHUB_STATUSCODE_RECORD, Node);
+ } else {
+ if (CurrentTpl > TPL_NOTIFY) {
+ //
+ // Memory management should work at <=TPL_NOTIFY
+ //
+ gBS->RestoreTPL (CurrentTpl);
+ return NULL;
+ }
+
+ //
+ // If free record buffer is exhausted, then allocate 16 new records for it.
+ //
+ gBS->RestoreTPL (CurrentTpl);
+ Record = (DATAHUB_STATUSCODE_RECORD *) AllocateZeroPool (sizeof (DATAHUB_STATUSCODE_RECORD) * 16);
+ if (Record == NULL) {
+ return NULL;
+ }
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+ //
+ // Here we only insert 15 new records to the free record buffer, for the first record
+ // will be returned immediately.
+ //
+ for (Index = 1; Index < 16; Index++) {
+ InsertTailList (&mRecordsBuffer, &Record[Index].Node);
+ }
+ }
+
+ Record->Signature = DATAHUB_STATUS_CODE_SIGNATURE;
+ InsertTailList (&mRecordsFifo, &Record->Node);
+
+ gBS->RestoreTPL (CurrentTpl);
+
+ return (DATA_HUB_STATUS_CODE_DATA_RECORD *) (Record->Data);
+}
+
+
+/**
+ Retrieve one record from Records FIFO. The record would be removed from FIFO.
+
+ @return Point to record, which is ready to be logged.
+ NULL means the FIFO of record is empty.
+
+**/
+DATA_HUB_STATUS_CODE_DATA_RECORD *
+RetrieveRecord (
+ VOID
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *RecordData;
+ DATAHUB_STATUSCODE_RECORD *Record;
+ LIST_ENTRY *Node;
+ EFI_TPL CurrentTpl;
+
+ RecordData = NULL;
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ if (!IsListEmpty (&mRecordsFifo)) {
+ Node = GetFirstNode (&mRecordsFifo);
+ Record = CR (Node, DATAHUB_STATUSCODE_RECORD, Node, DATAHUB_STATUS_CODE_SIGNATURE);
+ ASSERT (Record != NULL);
+
+ RemoveEntryList (&Record->Node);
+ RecordData = (DATA_HUB_STATUS_CODE_DATA_RECORD *) Record->Data;
+ }
+
+ gBS->RestoreTPL (CurrentTpl);
+
+ return RecordData;
+}
+
+/**
+ Release given record and return it to free record buffer.
+
+ @param RecordData Pointer to the record to release.
+
+**/
+VOID
+ReleaseRecord (
+ DATA_HUB_STATUS_CODE_DATA_RECORD *RecordData
+ )
+{
+ DATAHUB_STATUSCODE_RECORD *Record;
+ EFI_TPL CurrentTpl;
+
+ Record = CR (RecordData, DATAHUB_STATUSCODE_RECORD, Data[0], DATAHUB_STATUS_CODE_SIGNATURE);
+ ASSERT (Record != NULL);
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ InsertTailList (&mRecordsBuffer, &Record->Node);
+ Record->Signature = 0;
+
+ gBS->RestoreTPL (CurrentTpl);
+}
+
+/**
+ Report status code into DataHub.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+ @retval EFI_DEVICE_ERROR Function is reentered.
+ @retval EFI_DEVICE_ERROR Function is called at runtime.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory for free record buffer.
+
+**/
+EFI_STATUS
+EFIAPI
+DataHubStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
+ UINT32 ErrorLevel;
+ BASE_LIST Marker;
+ CHAR8 *Format;
+ UINTN CharCount;
+
+ //
+ // Use atom operation to avoid the reentant of report.
+ // If current status is not zero, then the function is reentrancy.
+ //
+ if (InterlockedCompareExchange32 (&mLogDataHubStatus, 0, 0) == 1) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ Record = AcquireRecordBuffer ();
+ if (Record == NULL) {
+ //
+ // There are no empty record buffer in private buffers
+ //
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Construct Data Hub Extended Data
+ //
+ Record->CodeType = CodeType;
+ Record->Value = Value;
+ Record->Instance = Instance;
+
+ if (CallerId != NULL) {
+ CopyMem (&Record->CallerId, CallerId, sizeof (EFI_GUID));
+ }
+
+ if (Data != NULL) {
+ if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
+ CharCount = UnicodeBSPrintAsciiFormat (
+ (CHAR16 *) (Record + 1),
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ Format,
+ Marker
+ );
+ //
+ // Change record data type to DebugType.
+ //
+ CopyGuid (&Record->Data.Type, &gEfiStatusCodeDataTypeDebugGuid);
+ Record->Data.HeaderSize = Data->HeaderSize;
+ Record->Data.Size = (UINT16) ((CharCount + 1) * sizeof (CHAR16));
+ } else {
+ //
+ // Copy status code data header
+ //
+ CopyMem (&Record->Data, Data, sizeof (EFI_STATUS_CODE_DATA));
+
+ if (Data->Size > EFI_STATUS_CODE_DATA_MAX_SIZE) {
+ Record->Data.Size = EFI_STATUS_CODE_DATA_MAX_SIZE;
+ }
+ CopyMem ((VOID *) (Record + 1), Data + 1, Record->Data.Size);
+ }
+ }
+
+ gBS->SignalEvent (mLogDataHubEvent);
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ The Event handler which will be notified to log data in Data Hub.
+
+ @param Event Instance of the EFI_EVENT to signal whenever data is
+ available to be logged in the system.
+ @param Context Context of the event.
+
+**/
+VOID
+EFIAPI
+LogDataHubEventCallBack (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
+ UINT32 Size;
+ UINT64 DataRecordClass;
+
+ //
+ // Use atom operation to avoid the reentant of report.
+ // If current status is not zero, then the function is reentrancy.
+ //
+ if (InterlockedCompareExchange32 (&mLogDataHubStatus, 0, 1) == 1) {
+ return;
+ }
+
+ //
+ // Log DataRecord in Data Hub.
+ // Journal records fifo to find all record entry.
+ //
+ while (TRUE) {
+ //
+ // Retrieve record from record FIFO until no more record can be retrieved.
+ //
+ Record = RetrieveRecord ();
+ if (Record == NULL) {
+ break;
+ }
+ //
+ // Add in the size of the header we added.
+ //
+ Size = sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD) + (UINT32) Record->Data.Size;
+
+ if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+ } else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_ERROR;
+ } else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG;
+ } else {
+ //
+ // Should never get here.
+ //
+ DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG |
+ EFI_DATA_RECORD_CLASS_ERROR |
+ EFI_DATA_RECORD_CLASS_DATA |
+ EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+ }
+
+ //
+ // Log DataRecord in Data Hub
+ //
+ mDataHubProtocol->LogData (
+ mDataHubProtocol,
+ &gEfiDataHubStatusCodeRecordGuid,
+ &gEfiStatusCodeRuntimeProtocolGuid,
+ DataRecordClass,
+ Record,
+ Size
+ );
+
+ ReleaseRecord (Record);
+ }
+
+ //
+ // Restore the nest status of report
+ //
+ InterlockedCompareExchange32 (&mLogDataHubStatus, 1, 0);
+}
+
+
+/**
+ Locate Data Hub Protocol and create event for logging data
+ as initialization for data hub status code worker.
+
+ @retval EFI_SUCCESS Initialization is successful.
+
+**/
+EFI_STATUS
+DataHubStatusCodeInitializeWorker (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol (
+ &gEfiDataHubProtocolGuid,
+ NULL,
+ (VOID **) &mDataHubProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ mDataHubProtocol = NULL;
+ return Status;
+ }
+
+ //
+ // Create a Notify Event to log data in Data Hub
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ LogDataHubEventCallBack,
+ NULL,
+ &mLogDataHubEvent
+ );
+
+ ASSERT_EFI_ERROR (Status);
+
+ return EFI_SUCCESS;
+}
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.c
new file mode 100644
index 0000000000..ee7bdd36af
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.c
@@ -0,0 +1,88 @@
+/** @file
+ Status Code Handler Driver which produces datahub handler and hook it
+ onto the DXE status code router.
+
+ Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "DatahubStatusCodeHandlerDxe.h"
+
+EFI_EVENT mExitBootServicesEvent = NULL;
+EFI_RSC_HANDLER_PROTOCOL *mRscHandlerProtocol = NULL;
+
+/**
+ Unregister status code callback functions only available at boot time from
+ report status code router when exiting boot services.
+
+ @param Event Event whose notification function is being invoked.
+ @param Context Pointer to the notification function's context, which is
+ always zero in current implementation.
+
+**/
+VOID
+EFIAPI
+UnregisterBootTimeHandlers (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ mRscHandlerProtocol->Unregister (DataHubStatusCodeReportWorker);
+}
+
+/**
+ Entry point of DXE Status Code Driver.
+
+ This function is the entry point of this DXE Status Code Driver.
+ It initializes registers status code handlers, and registers event for EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
+
+ @param ImageHandle The firmware allocated handle for the EFI image.
+ @param SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+DatahubStatusCodeHandlerDxeEntry (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ if (FeaturePcdGet (PcdStatusCodeUseDataHub)) {
+ Status = gBS->LocateProtocol (
+ &gEfiRscHandlerProtocolGuid,
+ NULL,
+ (VOID **) &mRscHandlerProtocol
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Dispatch initialization request to supported devices
+ //
+ DataHubStatusCodeInitializeWorker ();
+
+ mRscHandlerProtocol->Register (DataHubStatusCodeReportWorker, TPL_HIGH_LEVEL);
+
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_NOTIFY,
+ UnregisterBootTimeHandlers,
+ NULL,
+ &gEfiEventExitBootServicesGuid,
+ &mExitBootServicesEvent
+ );
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.h b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.h
new file mode 100644
index 0000000000..8ee0b55fa8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.h
@@ -0,0 +1,91 @@
+/** @file
+ Internal include file for Datahub Status Code Handler Driver.
+
+ Copyright (c) 2010, 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 __DATAHUB_STATUS_CODE_HANDLER_DXE_H__
+#define __DATAHUB_STATUS_CODE_HANDLER_DXE_H__
+
+#include <Protocol/ReportStatusCodeHandler.h>
+#include <Protocol/DataHub.h>
+#include <Protocol/StatusCode.h>
+
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/StatusCodeDataTypeDebug.h>
+#include <Guid/DataHubStatusCodeRecord.h>
+#include <Guid/EventGroup.h>
+
+#include <Library/BaseLib.h>
+#include <Library/SynchronizationLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/PrintLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/MemoryAllocationLib.h>
+
+//
+// Data hub worker definition
+//
+#define DATAHUB_STATUS_CODE_SIGNATURE SIGNATURE_32 ('B', 'D', 'H', 'S')
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Node;
+ UINT8 Data[sizeof(DATA_HUB_STATUS_CODE_DATA_RECORD) + EFI_STATUS_CODE_DATA_MAX_SIZE];
+} DATAHUB_STATUSCODE_RECORD;
+
+/**
+ Report status code into DataHub.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+ @retval EFI_DEVICE_ERROR Function is reentered.
+ @retval EFI_DEVICE_ERROR Function is called at runtime.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory for free record buffer.
+
+**/
+EFI_STATUS
+EFIAPI
+DataHubStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+/**
+ Locate Data Hub Protocol and create event for logging data
+ as initialization for data hub status code worker.
+
+ @retval EFI_SUCCESS Initialization is successful.
+
+**/
+EFI_STATUS
+DataHubStatusCodeInitializeWorker (
+ VOID
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.inf b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.inf
new file mode 100644
index 0000000000..1a576772a3
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.inf
@@ -0,0 +1,72 @@
+## @file
+# Status Code Handler Driver which produces datahub handler.
+#
+# Copyright (c) 2011 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DatahubStatusCodeHandlerDxe
+ MODULE_UNI_FILE = DatahubStatusCodeHandlerDxe.uni
+ FILE_GUID = 863D214F-0920-437B-8CAD-88EA83A24E97
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DatahubStatusCodeHandlerDxeEntry
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ DatahubStatusCodeHandlerDxe.h
+ DatahubStatusCodeHandlerDxe.c
+ DataHubStatusCodeWorker.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ BaseLib
+ MemoryAllocationLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ PcdLib
+ PrintLib
+ ReportStatusCodeLib
+ DebugLib
+ SynchronizationLib
+ BaseMemoryLib
+
+[Guids]
+ gEfiEventExitBootServicesGuid ## CONSUMES ## Event
+ gEfiDataHubStatusCodeRecordGuid ## PRODUCES ## UNDEFINED # DataRecord Guid
+ gEfiStatusCodeDataTypeDebugGuid ## SOMETIMES_PRODUCES ## UNDEFINED # Record data type
+
+[Protocols]
+ gEfiRscHandlerProtocolGuid ## CONSUMES
+ gEfiDataHubProtocolGuid ## CONSUMES
+ gEfiStatusCodeRuntimeProtocolGuid ## UNDEFINED
+
+[FeaturePcd]
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdStatusCodeUseDataHub ## CONSUMES
+
+[Depex]
+ gEfiRscHandlerProtocolGuid AND
+ gEfiDataHubProtocolGuid
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ DatahubStatusCodeHandlerDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.uni
new file mode 100644
index 0000000000..73b0c16a88
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxe.uni
@@ -0,0 +1,21 @@
+// /** @file
+// Status Code Handler Driver which produces datahub handler.
+//
+// The Status Code Handler Driver which produces a datahub handler.
+//
+// Copyright (c) 2011 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces a datahub handler"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The Status Code Handler Driver which produces a datahub handler."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxeExtra.uni
new file mode 100644
index 0000000000..15c62b419f
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/DatahubStatusCodeHandlerDxe/DatahubStatusCodeHandlerDxeExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// DatahubStatusCodeHandlerDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Data Hub Status Code DXE Driver"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/MemoryStausCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/MemoryStausCodeWorker.c
new file mode 100644
index 0000000000..f0b36f23a2
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/MemoryStausCodeWorker.c
@@ -0,0 +1,118 @@
+/** @file
+ PEI memory status code worker.
+
+ Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodePei.h"
+
+/**
+ Create the first memory status code GUID'ed HOB as initialization for memory status code worker.
+
+ @retval EFI_SUCCESS The GUID'ed HOB is created successfully.
+
+**/
+EFI_STATUS
+MemoryStatusCodeInitializeWorker (
+ VOID
+ )
+{
+ //
+ // Create memory status code GUID'ed HOB.
+ //
+ MEMORY_STATUSCODE_PACKET_HEADER *PacketHeader;
+
+ //
+ // Build GUID'ed HOB with PCD defined size.
+ //
+ PacketHeader = BuildGuidHob (
+ &gMemoryStatusCodeRecordGuid,
+ PcdGet16 (PcdStatusCodeMemorySize) * 1024 + sizeof (MEMORY_STATUSCODE_PACKET_HEADER)
+ );
+ ASSERT (PacketHeader != NULL);
+
+ PacketHeader->MaxRecordsNumber = (PcdGet16 (PcdStatusCodeMemorySize) * 1024) / sizeof (MEMORY_STATUSCODE_RECORD);
+ PacketHeader->PacketIndex = 0;
+ PacketHeader->RecordIndex = 0;
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Report status code into GUID'ed HOB.
+
+ This function reports status code into GUID'ed HOB. If not all packets are full, then
+ write status code into available entry. Otherwise, create a new packet for it.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+
+ @retval EFI_SUCCESS The function always return EFI_SUCCESS.
+
+**/
+EFI_STATUS
+MemoryStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance
+ )
+{
+
+ EFI_PEI_HOB_POINTERS Hob;
+ MEMORY_STATUSCODE_PACKET_HEADER *PacketHeader;
+ MEMORY_STATUSCODE_RECORD *Record;
+
+ //
+ // Find GUID'ed HOBs to locate current record buffer.
+ //
+ Hob.Raw = GetFirstGuidHob (&gMemoryStatusCodeRecordGuid);
+ ASSERT (Hob.Raw != NULL);
+
+ PacketHeader = (MEMORY_STATUSCODE_PACKET_HEADER *) GET_GUID_HOB_DATA (Hob.Guid);
+ Record = (MEMORY_STATUSCODE_RECORD *) (PacketHeader + 1);
+ Record = &Record[PacketHeader->RecordIndex++];
+
+ //
+ // Save status code.
+ //
+ Record->CodeType = CodeType;
+ Record->Instance = Instance;
+ Record->Value = Value;
+
+ //
+ // If record index equals to max record number, then wrap around record index to zero.
+ //
+ // The reader of status code should compare the number of records with max records number,
+ // If it is equal to or larger than the max number, then the wrap-around had happened,
+ // so the first record is pointed by record index.
+ // If it is less then max number, index of the first record is zero.
+ //
+ if (PacketHeader->RecordIndex == PacketHeader->MaxRecordsNumber) {
+ //
+ // Wrap around record index.
+ //
+ PacketHeader->RecordIndex = 0;
+ PacketHeader->PacketIndex ++;
+ }
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/SerialStatusCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/SerialStatusCodeWorker.c
new file mode 100644
index 0000000000..d62cb8f8c8
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/SerialStatusCodeWorker.c
@@ -0,0 +1,162 @@
+/** @file
+ Serial I/O status code reporting worker.
+
+ Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+**/
+
+#include "StatusCodePei.h"
+
+/**
+ Convert status code value and extended data to readable ASCII string, send string to serial I/O device.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS Status code reported to serial I/O successfully.
+
+**/
+EFI_STATUS
+SerialStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ CHAR8 *Filename;
+ CHAR8 *Description;
+ CHAR8 *Format;
+ CHAR8 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];
+ UINT32 ErrorLevel;
+ UINT32 LineNumber;
+ UINTN CharCount;
+ BASE_LIST Marker;
+
+ Buffer[0] = '\0';
+
+ if (Data != NULL &&
+ ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
+ //
+ // Print ASSERT() information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "\n\rPEI_ASSERT!: %a (%d): %a\n\r",
+ Filename,
+ LineNumber,
+ Description
+ );
+ } else if (Data != NULL &&
+ ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
+ //
+ // Print DEBUG() information into output buffer.
+ //
+ CharCount = AsciiBSPrint (
+ Buffer,
+ sizeof (Buffer),
+ Format,
+ Marker
+ );
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
+ //
+ // Print ERROR information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "ERROR: C%08x:V%08x I%x",
+ CodeType,
+ Value,
+ Instance
+ );
+
+ if (CallerId != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ " %g",
+ CallerId
+ );
+ }
+
+ if (Data != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ " %x",
+ Data
+ );
+ }
+
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ "\n\r"
+ );
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
+ //
+ // Print PROGRESS information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "PROGRESS CODE: V%08x I%x\n\r",
+ Value,
+ Instance
+ );
+ } else if (Data != NULL &&
+ CompareGuid (&Data->Type, &gEfiStatusCodeDataTypeStringGuid) &&
+ ((EFI_STATUS_CODE_STRING_DATA *) Data)->StringType == EfiStringAscii) {
+ //
+ // EFI_STATUS_CODE_STRING_DATA
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "%a\n\r",
+ ((EFI_STATUS_CODE_STRING_DATA *) Data)->String.Ascii
+ );
+ } else {
+ //
+ // Code type is not defined.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "Undefined: C%08x:V%08x I%x\n\r",
+ CodeType,
+ Value,
+ Instance
+ );
+ }
+
+ //
+ // Call SerialPort Lib function to do print.
+ //
+ SerialPortWrite ((UINT8 *) Buffer, CharCount);
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.c
new file mode 100644
index 0000000000..5b17df3862
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.c
@@ -0,0 +1,146 @@
+/** @file
+ Status code PEIM which produces Status Code PPI.
+
+ Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodePei.h"
+
+EFI_PEI_PROGRESS_CODE_PPI mStatusCodePpi = {
+ ReportDispatcher
+ };
+
+EFI_PEI_PPI_DESCRIPTOR mStatusCodePpiDescriptor = {
+ EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
+ &gEfiPeiStatusCodePpiGuid,
+ &mStatusCodePpi
+ };
+
+/**
+ Publishes an interface that allows PEIMs to report status codes.
+
+ This function implements EFI_PEI_PROGRESS_CODE_PPI.ReportStatusCode().
+ It publishes an interface that allows PEIMs to report status codes.
+
+ @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation.
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+ReportDispatcher (
+ IN CONST EFI_PEI_SERVICES **PeiServices,
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId OPTIONAL,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ if (FeaturePcdGet (PcdStatusCodeUseSerial)) {
+ SerialStatusCodeReportWorker (
+ CodeType,
+ Value,
+ Instance,
+ CallerId,
+ Data
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseMemory)) {
+ MemoryStatusCodeReportWorker (
+ CodeType,
+ Value,
+ Instance
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseOEM)) {
+ //
+ // Call OEM hook status code library API to report status code to OEM device
+ //
+ OemHookStatusCodeReport (
+ CodeType,
+ Value,
+ Instance,
+ (EFI_GUID *)CallerId,
+ (EFI_STATUS_CODE_DATA *)Data
+ );
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Entry point of Status Code PEIM.
+
+ This function is the entry point of this Status Code PEIM.
+ It initializes supported status code devices according to PCD settings,
+ and installs Status Code PPI.
+
+ @param FileHandle Handle of the file being invoked.
+ @param PeiServices Describes the list of possible PEI Services.
+
+ @retval EFI_SUCESS The entry point of DXE IPL PEIM executes successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+PeiStatusCodeDriverEntry (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ IN CONST EFI_PEI_SERVICES **PeiServices
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Dispatch initialization request to sub-statuscode-devices.
+ // If enable UseSerial, then initialize serial port.
+ // if enable UseMemory, then initialize memory status code worker.
+ // if enable UseOEM, then initialize Oem status code.
+ //
+ if (FeaturePcdGet (PcdStatusCodeUseSerial)) {
+ Status = SerialPortInitialize();
+ ASSERT_EFI_ERROR (Status);
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseMemory)) {
+ Status = MemoryStatusCodeInitializeWorker ();
+ ASSERT_EFI_ERROR (Status);
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseOEM)) {
+ Status = OemHookStatusCodeInitialize ();
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ //
+ // Install Status Code PPI.
+ // It serves the PEI Service ReportStatusCode.
+ //
+ Status = PeiServicesInstallPpi (&mStatusCodePpiDescriptor);
+ ASSERT_EFI_ERROR (Status);
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.h b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.h
new file mode 100644
index 0000000000..75078d0ef4
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.h
@@ -0,0 +1,147 @@
+/** @file
+ Internal include file for Status Code PEIM.
+
+ Copyright (c) 2006 - 2009, 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 __PEI_STATUS_CODE_H__
+#define __PEI_STATUS_CODE_H__
+
+#include <FrameworkPei.h>
+
+#include <Guid/MemoryStatusCodeRecord.h>
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/StatusCodeDataTypeDebug.h>
+#include <Ppi/StatusCode.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PrintLib.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/SerialPortLib.h>
+#include <Library/HobLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/OemHookStatusCodeLib.h>
+#include <Library/PeimEntryPoint.h>
+
+/**
+ Convert status code value and extended data to readable ASCII string, send string to serial I/O device.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS Status code reported to serial I/O successfully.
+
+**/
+EFI_STATUS
+SerialStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+
+/**
+ Create the first memory status code GUID'ed HOB as initialization for memory status code worker.
+
+ @retval EFI_SUCCESS The GUID'ed HOB is created successfully.
+
+**/
+EFI_STATUS
+MemoryStatusCodeInitializeWorker (
+ VOID
+ );
+
+/**
+ Report status code into GUID'ed HOB.
+
+ This function reports status code into GUID'ed HOB. If not all packets are full, then
+ write status code into available entry. Otherwise, create a new packet for it.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+
+ @retval EFI_SUCCESS The function always return EFI_SUCCESS.
+
+**/
+EFI_STATUS
+MemoryStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance
+ );
+
+/**
+ Publishes an interface that allows PEIMs to report status codes.
+
+ This function implements EFI_PEI_PROGRESS_CODE_PPI.ReportStatusCode().
+ It publishes an interface that allows PEIMs to report status codes.
+
+ @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation.
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or
+ software entity. This includes information about the class and
+ subclass that is used to classify the entity as well as an operation.
+ For progress codes, the operation is the current activity.
+ For error codes, it is the exception.For debug codes,it is not defined at this time.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. A system may contain multiple entities that match a class/subclass
+ pairing. The instance differentiates between them. An instance of 0 indicates
+ that instance information is unavailable, not meaningful, or not relevant.
+ Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+ReportDispatcher (
+ IN CONST EFI_PEI_SERVICES **PeiServices,
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId OPTIONAL,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+#endif
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
new file mode 100644
index 0000000000..04cef4a2f4
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
@@ -0,0 +1,78 @@
+## @file
+# Status code PEIM which produces Status Code PPI.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = StatusCodePei
+ MODULE_UNI_FILE = StatusCodePei.uni
+ FILE_GUID = 1EC0F53A-FDE0-4576-8F25-7A1A410F58EB
+ MODULE_TYPE = PEIM
+ VERSION_STRING = 1.0
+ ENTRY_POINT = PeiStatusCodeDriverEntry
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 IPF EBC
+#
+
+[Sources]
+ StatusCodePei.c
+ StatusCodePei.h
+ MemoryStausCodeWorker.c
+ SerialStatusCodeWorker.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ PeimEntryPoint
+ OemHookStatusCodeLib
+ PeiServicesLib
+ PcdLib
+ HobLib
+ SerialPortLib
+ ReportStatusCodeLib
+ PrintLib
+ DebugLib
+ BaseLib
+
+
+[Guids]
+ gMemoryStatusCodeRecordGuid ## SOMETIMES_CONSUMES ## HOB
+ gEfiStatusCodeDataTypeStringGuid ## SOMETIMES_CONSUMES ## UNDEFINED # String Data Type
+
+[Ppis]
+ gEfiPeiStatusCodePpiGuid ## PRODUCES
+
+
+[FeaturePcd]
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdStatusCodeUseOEM ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial ## CONSUMES
+
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1|gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory ## SOMETIMES_CONSUMES
+
+[Depex]
+ TRUE
+
+[UserExtensions.TianoCore."ExtraFiles"]
+ StatusCodePeiExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.uni
new file mode 100644
index 0000000000..f1138a357b
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.uni
@@ -0,0 +1,21 @@
+// /** @file
+// Status code PEIM which produces Status Code PPI.
+//
+// The status code PEIM that produces a Status Code PPI.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces a Status Code PPI"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The status code PEIM that produces a Status Code PPI."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePeiExtra.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePeiExtra.uni
new file mode 100644
index 0000000000..f321048582
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePeiExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// StatusCodePei Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Status Code PEI Module"
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/DataHubStatusCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/DataHubStatusCodeWorker.c
new file mode 100644
index 0000000000..ffee2f9c2a
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/DataHubStatusCodeWorker.c
@@ -0,0 +1,390 @@
+/** @file
+ Data Hub status code worker.
+
+ Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodeRuntimeDxe.h"
+
+//
+// Initialize FIFO to cache records.
+//
+LIST_ENTRY mRecordsFifo = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsFifo);
+LIST_ENTRY mRecordsBuffer = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsBuffer);
+UINT32 mLogDataHubStatus = 0;
+EFI_EVENT mLogDataHubEvent;
+//
+// Cache data hub protocol.
+//
+EFI_DATA_HUB_PROTOCOL *mDataHubProtocol = NULL;
+
+
+/**
+ Retrieve one record of from free record buffer. This record is removed from
+ free record buffer.
+
+ This function retrieves one record from free record buffer.
+ If the pool has been exhausted, then new memory would be allocated for it.
+
+ @return Pointer to the free record.
+ NULL means failure to allocate new memeory for free record buffer.
+
+**/
+DATA_HUB_STATUS_CODE_DATA_RECORD *
+AcquireRecordBuffer (
+ VOID
+ )
+{
+ DATAHUB_STATUSCODE_RECORD *Record;
+ EFI_TPL CurrentTpl;
+ LIST_ENTRY *Node;
+ UINT32 Index;
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ if (!IsListEmpty (&mRecordsBuffer)) {
+ //
+ // Strip one entry from free record buffer.
+ //
+ Node = GetFirstNode (&mRecordsBuffer);
+ RemoveEntryList (Node);
+
+ Record = BASE_CR (Node, DATAHUB_STATUSCODE_RECORD, Node);
+ } else {
+ if (CurrentTpl > TPL_NOTIFY) {
+ //
+ // Memory management should work at <=TPL_NOTIFY
+ //
+ gBS->RestoreTPL (CurrentTpl);
+ return NULL;
+ }
+
+ //
+ // If free record buffer is exhausted, then allocate 16 new records for it.
+ //
+ gBS->RestoreTPL (CurrentTpl);
+ Record = (DATAHUB_STATUSCODE_RECORD *) AllocateZeroPool (sizeof (DATAHUB_STATUSCODE_RECORD) * 16);
+ if (Record == NULL) {
+ return NULL;
+ }
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+ //
+ // Here we only insert 15 new records to the free record buffer, for the first record
+ // will be returned immediately.
+ //
+ for (Index = 1; Index < 16; Index++) {
+ InsertTailList (&mRecordsBuffer, &Record[Index].Node);
+ }
+ }
+
+ Record->Signature = DATAHUB_STATUS_CODE_SIGNATURE;
+ InsertTailList (&mRecordsFifo, &Record->Node);
+
+ gBS->RestoreTPL (CurrentTpl);
+
+ return (DATA_HUB_STATUS_CODE_DATA_RECORD *) (Record->Data);
+}
+
+
+/**
+ Retrieve one record from Records FIFO. The record would be removed from FIFO.
+
+ @return Point to record, which is ready to be logged.
+ NULL means the FIFO of record is empty.
+
+**/
+DATA_HUB_STATUS_CODE_DATA_RECORD *
+RetrieveRecord (
+ VOID
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *RecordData;
+ DATAHUB_STATUSCODE_RECORD *Record;
+ LIST_ENTRY *Node;
+ EFI_TPL CurrentTpl;
+
+ RecordData = NULL;
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ if (!IsListEmpty (&mRecordsFifo)) {
+ Node = GetFirstNode (&mRecordsFifo);
+ Record = CR (Node, DATAHUB_STATUSCODE_RECORD, Node, DATAHUB_STATUS_CODE_SIGNATURE);
+ ASSERT (Record != NULL);
+
+ RemoveEntryList (&Record->Node);
+ RecordData = (DATA_HUB_STATUS_CODE_DATA_RECORD *) Record->Data;
+ }
+
+ gBS->RestoreTPL (CurrentTpl);
+
+ return RecordData;
+}
+
+/**
+ Release given record and return it to free record buffer.
+
+ @param RecordData Pointer to the record to release.
+
+**/
+VOID
+ReleaseRecord (
+ DATA_HUB_STATUS_CODE_DATA_RECORD *RecordData
+ )
+{
+ DATAHUB_STATUSCODE_RECORD *Record;
+ EFI_TPL CurrentTpl;
+
+ Record = CR (RecordData, DATAHUB_STATUSCODE_RECORD, Data[0], DATAHUB_STATUS_CODE_SIGNATURE);
+ ASSERT (Record != NULL);
+
+ CurrentTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ InsertTailList (&mRecordsBuffer, &Record->Node);
+ Record->Signature = 0;
+
+ gBS->RestoreTPL (CurrentTpl);
+}
+
+/**
+ Report status code into DataHub.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+ @retval EFI_DEVICE_ERROR Function is reentered.
+ @retval EFI_DEVICE_ERROR Function is called at runtime.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory for free record buffer.
+
+**/
+EFI_STATUS
+DataHubStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
+ UINT32 ErrorLevel;
+ BASE_LIST Marker;
+ CHAR8 *Format;
+ UINTN CharCount;
+ EFI_STATUS Status;
+
+ //
+ // Use atom operation to avoid the reentant of report.
+ // If current status is not zero, then the function is reentrancy.
+ //
+ if (InterlockedCompareExchange32 (&mLogDataHubStatus, 0, 0) == 1) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // See whether in runtime phase or not.
+ //
+ if (EfiAtRuntime ()) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (mDataHubProtocol == NULL) {
+ Status = DataHubStatusCodeInitializeWorker ();
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ Record = AcquireRecordBuffer ();
+ if (Record == NULL) {
+ //
+ // There are no empty record buffer in private buffers
+ //
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Construct Data Hub Extended Data
+ //
+ Record->CodeType = CodeType;
+ Record->Value = Value;
+ Record->Instance = Instance;
+
+ if (CallerId != NULL) {
+ CopyMem (&Record->CallerId, CallerId, sizeof (EFI_GUID));
+ }
+
+ if (Data != NULL) {
+ if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
+ CharCount = UnicodeBSPrintAsciiFormat (
+ (CHAR16 *) (Record + 1),
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ Format,
+ Marker
+ );
+ //
+ // Change record data type to DebugType.
+ //
+ CopyGuid (&Record->Data.Type, &gEfiStatusCodeDataTypeDebugGuid);
+ Record->Data.HeaderSize = Data->HeaderSize;
+ Record->Data.Size = (UINT16) ((CharCount + 1) * sizeof (CHAR16));
+ } else {
+ //
+ // Copy status code data header
+ //
+ CopyMem (&Record->Data, Data, sizeof (EFI_STATUS_CODE_DATA));
+
+ if (Data->Size > EFI_STATUS_CODE_DATA_MAX_SIZE) {
+ Record->Data.Size = EFI_STATUS_CODE_DATA_MAX_SIZE;
+ }
+ CopyMem ((VOID *) (Record + 1), Data + 1, Record->Data.Size);
+ }
+ }
+
+ gBS->SignalEvent (mLogDataHubEvent);
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ The Event handler which will be notified to log data in Data Hub.
+
+ @param Event Instance of the EFI_EVENT to signal whenever data is
+ available to be logged in the system.
+ @param Context Context of the event.
+
+**/
+VOID
+EFIAPI
+LogDataHubEventCallBack (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
+ UINT32 Size;
+ UINT64 DataRecordClass;
+
+ //
+ // Use atom operation to avoid the reentant of report.
+ // If current status is not zero, then the function is reentrancy.
+ //
+ if (InterlockedCompareExchange32 (&mLogDataHubStatus, 0, 1) == 1) {
+ return;
+ }
+
+ //
+ // Log DataRecord in Data Hub.
+ // Journal records fifo to find all record entry.
+ //
+ while (TRUE) {
+ //
+ // Retrieve record from record FIFO until no more record can be retrieved.
+ //
+ Record = RetrieveRecord ();
+ if (Record == NULL) {
+ break;
+ }
+ //
+ // Add in the size of the header we added.
+ //
+ Size = sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD) + (UINT32) Record->Data.Size;
+
+ if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+ } else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_ERROR;
+ } else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
+ DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG;
+ } else {
+ //
+ // Should never get here.
+ //
+ DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG |
+ EFI_DATA_RECORD_CLASS_ERROR |
+ EFI_DATA_RECORD_CLASS_DATA |
+ EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
+ }
+
+ //
+ // Log DataRecord in Data Hub
+ //
+ mDataHubProtocol->LogData (
+ mDataHubProtocol,
+ &gEfiDataHubStatusCodeRecordGuid,
+ &gEfiStatusCodeRuntimeProtocolGuid,
+ DataRecordClass,
+ Record,
+ Size
+ );
+
+ ReleaseRecord (Record);
+ }
+
+ //
+ // Restore the nest status of report
+ //
+ InterlockedCompareExchange32 (&mLogDataHubStatus, 1, 0);
+}
+
+
+/**
+ Locate Data Hub Protocol and create event for logging data
+ as initialization for data hub status code worker.
+
+ @retval EFI_SUCCESS Initialization is successful.
+
+**/
+EFI_STATUS
+DataHubStatusCodeInitializeWorker (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol (
+ &gEfiDataHubProtocolGuid,
+ NULL,
+ (VOID **) &mDataHubProtocol
+ );
+ if (EFI_ERROR (Status)) {
+ mDataHubProtocol = NULL;
+ return Status;
+ }
+
+ //
+ // Create a Notify Event to log data in Data Hub
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ LogDataHubEventCallBack,
+ NULL,
+ &mLogDataHubEvent
+ );
+
+ ASSERT_EFI_ERROR (Status);
+
+ return EFI_SUCCESS;
+}
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/RtMemoryStatusCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/RtMemoryStatusCodeWorker.c
new file mode 100644
index 0000000000..2a26e19e65
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/RtMemoryStatusCodeWorker.c
@@ -0,0 +1,104 @@
+/** @file
+ Runtime memory status code worker.
+
+ Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodeRuntimeDxe.h"
+
+RUNTIME_MEMORY_STATUSCODE_HEADER *mRtMemoryStatusCodeTable;
+
+/**
+ Initialize runtime memory status code table as initialization for runtime memory status code worker
+
+ @retval EFI_SUCCESS Runtime memory status code table successfully initialized.
+
+**/
+EFI_STATUS
+RtMemoryStatusCodeInitializeWorker (
+ VOID
+ )
+{
+ //
+ // Allocate runtime memory status code pool.
+ //
+ mRtMemoryStatusCodeTable = AllocateRuntimePool (
+ sizeof (RUNTIME_MEMORY_STATUSCODE_HEADER) +
+ PcdGet16 (PcdStatusCodeMemorySize) * 1024
+ );
+ ASSERT (mRtMemoryStatusCodeTable != NULL);
+
+ mRtMemoryStatusCodeTable->RecordIndex = 0;
+ mRtMemoryStatusCodeTable->NumberOfRecords = 0;
+ mRtMemoryStatusCodeTable->MaxRecordsNumber =
+ (PcdGet16 (PcdStatusCodeMemorySize) * 1024) / sizeof (MEMORY_STATUSCODE_RECORD);
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Report status code into runtime memory. If the runtime pool is full, roll back to the
+ first record and overwrite it.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+
+ @retval EFI_SUCCESS Status code successfully recorded in runtime memory status code table.
+
+**/
+EFI_STATUS
+RtMemoryStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance
+ )
+{
+ MEMORY_STATUSCODE_RECORD *Record;
+
+ //
+ // Locate current record buffer.
+ //
+ Record = (MEMORY_STATUSCODE_RECORD *) (mRtMemoryStatusCodeTable + 1);
+ Record = &Record[mRtMemoryStatusCodeTable->RecordIndex++];
+
+ //
+ // Save status code.
+ //
+ Record->CodeType = CodeType;
+ Record->Value = Value;
+ Record->Instance = Instance;
+
+ //
+ // If record index equals to max record number, then wrap around record index to zero.
+ //
+ // The reader of status code should compare the number of records with max records number,
+ // If it is equal to or larger than the max number, then the wrap-around had happened,
+ // so the first record is pointed by record index.
+ // If it is less then max number, index of the first record is zero.
+ //
+ mRtMemoryStatusCodeTable->NumberOfRecords++;
+ if (mRtMemoryStatusCodeTable->RecordIndex == mRtMemoryStatusCodeTable->MaxRecordsNumber) {
+ //
+ // Wrap around record index.
+ //
+ mRtMemoryStatusCodeTable->RecordIndex = 0;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/SerialStatusCodeWorker.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/SerialStatusCodeWorker.c
new file mode 100644
index 0000000000..e1d02630e7
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/SerialStatusCodeWorker.c
@@ -0,0 +1,160 @@
+/** @file
+ Serial I/O status code reporting worker.
+
+ Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodeRuntimeDxe.h"
+
+/**
+ Convert status code value and extended data to readable ASCII string, send string to serial I/O device.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS Status code reported to serial I/O successfully.
+ @retval EFI_DEVICE_ERROR EFI serial device cannot work after ExitBootService() is called.
+ @retval EFI_DEVICE_ERROR EFI serial device cannot work with TPL higher than TPL_CALLBACK.
+
+**/
+EFI_STATUS
+SerialStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ CHAR8 *Filename;
+ CHAR8 *Description;
+ CHAR8 *Format;
+ CHAR8 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];
+ UINT32 ErrorLevel;
+ UINT32 LineNumber;
+ UINTN CharCount;
+ BASE_LIST Marker;
+
+ Buffer[0] = '\0';
+
+ if (Data != NULL &&
+ ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
+ //
+ // Print ASSERT() information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "\n\rDXE_ASSERT!: %a (%d): %a\n\r",
+ Filename,
+ LineNumber,
+ Description
+ );
+ } else if (Data != NULL &&
+ ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
+ //
+ // Print DEBUG() information into output buffer.
+ //
+ CharCount = AsciiBSPrint (
+ Buffer,
+ sizeof (Buffer),
+ Format,
+ Marker
+ );
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
+ //
+ // Print ERROR information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "ERROR: C%08x:V%08x I%x",
+ CodeType,
+ Value,
+ Instance
+ );
+
+ if (CallerId != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ " %g",
+ CallerId
+ );
+ }
+
+ if (Data != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ " %x",
+ Data
+ );
+ }
+
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount],
+ (sizeof (Buffer) - (sizeof (Buffer[0]) * CharCount)),
+ "\n\r"
+ );
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
+ //
+ // Print PROGRESS information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "PROGRESS CODE: V%08x I%x\n\r",
+ Value,
+ Instance
+ );
+ } else if (Data != NULL &&
+ CompareGuid (&Data->Type, &gEfiStatusCodeDataTypeStringGuid) &&
+ ((EFI_STATUS_CODE_STRING_DATA *) Data)->StringType == EfiStringAscii) {
+ //
+ // EFI_STATUS_CODE_STRING_DATA
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "%a\n\r",
+ ((EFI_STATUS_CODE_STRING_DATA *) Data)->String.Ascii
+ );
+ } else {
+ //
+ // Code type is not defined.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ sizeof (Buffer),
+ "Undefined: C%08x:V%08x I%x\n\r",
+ CodeType,
+ Value,
+ Instance
+ );
+ }
+
+ //
+ // Call SerialPort Lib function to do print.
+ //
+ SerialPortWrite ((UINT8 *) Buffer, CharCount);
+
+ return EFI_SUCCESS;
+}
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.c b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.c
new file mode 100644
index 0000000000..6435e1f727
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.c
@@ -0,0 +1,301 @@
+/** @file
+ Status code driver for IA32/X64/EBC architecture.
+
+ Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "StatusCodeRuntimeDxe.h"
+
+EFI_EVENT mVirtualAddressChangeEvent = NULL;
+EFI_HANDLE mHandle = NULL;
+
+//
+// Declaration of status code protocol.
+//
+EFI_STATUS_CODE_PROTOCOL mEfiStatusCodeProtocol = {
+ ReportDispatcher
+};
+
+//
+// Report operation nest status.
+// If it is set, then the report operation has nested.
+//
+UINT32 mStatusCodeNestStatus = 0;
+
+/**
+ Entry point of DXE Status Code Driver.
+
+ This function is the entry point of this DXE Status Code Driver.
+ It installs Status Code Runtime Protocol, and registers event for EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
+
+ @param ImageHandle The firmware allocated handle for the EFI image.
+ @param SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+StatusCodeRuntimeDxeEntry (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Dispatch initialization request to supported devices
+ //
+ InitializationDispatcherWorker ();
+
+ //
+ // Install Status Code Runtime Protocol implementation as defined in PI Specification.
+ //
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &mHandle,
+ &gEfiStatusCodeRuntimeProtocolGuid,
+ &mEfiStatusCodeProtocol,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_NOTIFY,
+ VirtualAddressChangeCallBack,
+ NULL,
+ &gEfiEventVirtualAddressChangeGuid,
+ &mVirtualAddressChangeEvent
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Report status code to all supported device.
+
+ This function implements EFI_STATUS_CODE_PROTOCOL.ReportStatusCode().
+ It calls into the workers which dispatches the platform specific listeners.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully
+ @retval EFI_DEVICE_ERROR The function should not be completed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+ReportDispatcher (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId OPTIONAL,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ //
+ // Use atom operation to avoid the reentant of report.
+ // If current status is not zero, then the function is reentrancy.
+ //
+ if (InterlockedCompareExchange32 (&mStatusCodeNestStatus, 0, 1) == 1) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (FeaturePcdGet (PcdStatusCodeUseSerial)) {
+ SerialStatusCodeReportWorker (
+ CodeType,
+ Value,
+ Instance,
+ CallerId,
+ Data
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseMemory)) {
+ RtMemoryStatusCodeReportWorker (
+ CodeType,
+ Value,
+ Instance
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseDataHub)) {
+ DataHubStatusCodeReportWorker (
+ CodeType,
+ Value,
+ Instance,
+ CallerId,
+ Data
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseOEM)) {
+ //
+ // Call OEM hook status code library API to report status code to OEM device
+ //
+ OemHookStatusCodeReport (
+ CodeType,
+ Value,
+ Instance,
+ CallerId,
+ Data
+ );
+ }
+
+ //
+ // Restore the nest status of report
+ //
+ InterlockedCompareExchange32 (&mStatusCodeNestStatus, 1, 0);
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Virtual address change notification call back. It converts global pointer
+ to virtual address.
+
+ @param Event Event whose notification function is being invoked.
+ @param Context Pointer to the notification function's context, which is
+ always zero in current implementation.
+
+**/
+VOID
+EFIAPI
+VirtualAddressChangeCallBack (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ //
+ // Convert memory status code table to virtual address;
+ //
+ EfiConvertPointer (
+ 0,
+ (VOID **) &mRtMemoryStatusCodeTable
+ );
+}
+
+/**
+ Dispatch initialization request to sub status code devices based on
+ customized feature flags.
+
+**/
+VOID
+InitializationDispatcherWorker (
+ VOID
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+ EFI_STATUS Status;
+ MEMORY_STATUSCODE_PACKET_HEADER *PacketHeader;
+ MEMORY_STATUSCODE_RECORD *Record;
+ UINTN Index;
+ UINTN MaxRecordNumber;
+
+ //
+ // If enable UseSerial, then initialize serial port.
+ // if enable UseRuntimeMemory, then initialize runtime memory status code worker.
+ // if enable UseDataHub, then initialize data hub status code worker.
+ //
+ if (FeaturePcdGet (PcdStatusCodeUseSerial)) {
+ //
+ // Call Serial Port Lib API to initialize serial port.
+ //
+ Status = SerialPortInitialize ();
+ ASSERT_EFI_ERROR (Status);
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseMemory)) {
+ Status = RtMemoryStatusCodeInitializeWorker ();
+ ASSERT_EFI_ERROR (Status);
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseDataHub)) {
+ DataHubStatusCodeInitializeWorker ();
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseOEM)) {
+ //
+ // Call OEM hook status code library API to initialize OEM device for status code.
+ //
+ Status = OemHookStatusCodeInitialize ();
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ //
+ // Replay Status code which saved in GUID'ed HOB to all supported devices.
+ //
+ if (FeaturePcdGet (PcdStatusCodeReplayIn)) {
+ //
+ // Journal GUID'ed HOBs to find all record entry, if found,
+ // then output record to support replay device.
+ //
+ Hob.Raw = GetFirstGuidHob (&gMemoryStatusCodeRecordGuid);
+ if (Hob.Raw != NULL) {
+ PacketHeader = (MEMORY_STATUSCODE_PACKET_HEADER *) GET_GUID_HOB_DATA (Hob.Guid);
+ Record = (MEMORY_STATUSCODE_RECORD *) (PacketHeader + 1);
+ MaxRecordNumber = (UINTN) PacketHeader->RecordIndex;
+ if (PacketHeader->PacketIndex > 0) {
+ //
+ // Record has been wrapped around. So, record number has arrived at max number.
+ //
+ MaxRecordNumber = (UINTN) PacketHeader->MaxRecordsNumber;
+ }
+ for (Index = 0; Index < MaxRecordNumber; Index++) {
+ //
+ // Dispatch records to devices based on feature flag.
+ //
+ if (FeaturePcdGet (PcdStatusCodeUseSerial)) {
+ SerialStatusCodeReportWorker (
+ Record[Index].CodeType,
+ Record[Index].Value,
+ Record[Index].Instance,
+ NULL,
+ NULL
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseMemory)) {
+ RtMemoryStatusCodeReportWorker (
+ Record[Index].CodeType,
+ Record[Index].Value,
+ Record[Index].Instance
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseDataHub)) {
+ DataHubStatusCodeReportWorker (
+ Record[Index].CodeType,
+ Record[Index].Value,
+ Record[Index].Instance,
+ NULL,
+ NULL
+ );
+ }
+ if (FeaturePcdGet (PcdStatusCodeUseOEM)) {
+ //
+ // Call OEM hook status code library API to report status code to OEM device
+ //
+ OemHookStatusCodeReport (
+ Record[Index].CodeType,
+ Record[Index].Value,
+ Record[Index].Instance,
+ NULL,
+ NULL
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.h b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.h
new file mode 100644
index 0000000000..ae20f5b226
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.h
@@ -0,0 +1,231 @@
+/** @file
+ Internal include file of Status Code Runtime DXE Driver.
+
+ Copyright (c) 2006 - 2009, 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 __STATUS_CODE_RUNTIME_DXE_H__
+#define __STATUS_CODE_RUNTIME_DXE_H__
+
+
+#include <FrameworkDxe.h>
+#include <Guid/DataHubStatusCodeRecord.h>
+#include <Protocol/DataHub.h>
+#include <Guid/MemoryStatusCodeRecord.h>
+#include <Protocol/StatusCode.h>
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/StatusCodeDataTypeDebug.h>
+#include <Guid/EventGroup.h>
+
+#include <Library/BaseLib.h>
+#include <Library/SynchronizationLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/PrintLib.h>
+#include <Library/PcdLib.h>
+#include <Library/HobLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiRuntimeLib.h>
+#include <Library/SerialPortLib.h>
+#include <Library/OemHookStatusCodeLib.h>
+
+//
+// Data hub worker definition
+//
+#define DATAHUB_STATUS_CODE_SIGNATURE SIGNATURE_32 ('B', 'D', 'H', 'S')
+
+typedef struct {
+ UINTN Signature;
+ LIST_ENTRY Node;
+ UINT8 Data[sizeof(DATA_HUB_STATUS_CODE_DATA_RECORD) + EFI_STATUS_CODE_DATA_MAX_SIZE];
+} DATAHUB_STATUSCODE_RECORD;
+
+
+extern RUNTIME_MEMORY_STATUSCODE_HEADER *mRtMemoryStatusCodeTable;
+
+/**
+ Report status code to all supported device.
+
+ This function implements EFI_STATUS_CODE_PROTOCOL.ReportStatusCode().
+ It calls into the workers which dispatches the platform specific listeners.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully
+ @retval EFI_DEVICE_ERROR The function should not be completed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+ReportDispatcher (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId OPTIONAL,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+/**
+ Dispatch initialization request to sub status code devices based on
+ customized feature flags.
+
+**/
+VOID
+InitializationDispatcherWorker (
+ VOID
+ );
+
+
+/**
+ Locates Serial I/O Protocol as initialization for serial status code worker.
+
+ @retval EFI_SUCCESS Serial I/O Protocol is successfully located.
+
+**/
+EFI_STATUS
+EfiSerialStatusCodeInitializeWorker (
+ VOID
+ );
+
+
+/**
+ Convert status code value and extended data to readable ASCII string, send string to serial I/O device.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS Status code reported to serial I/O successfully.
+ @retval EFI_DEVICE_ERROR EFI serial device cannot work after ExitBootService() is called.
+ @retval EFI_DEVICE_ERROR EFI serial device cannot work with TPL higher than TPL_CALLBACK.
+
+**/
+EFI_STATUS
+SerialStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+/**
+ Initialize runtime memory status code table as initialization for runtime memory status code worker
+
+ @retval EFI_SUCCESS Runtime memory status code table successfully initialized.
+
+**/
+EFI_STATUS
+RtMemoryStatusCodeInitializeWorker (
+ VOID
+ );
+
+/**
+ Report status code into runtime memory. If the runtime pool is full, roll back to the
+ first record and overwrite it.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+
+ @retval EFI_SUCCESS Status code successfully recorded in runtime memory status code table.
+
+**/
+EFI_STATUS
+RtMemoryStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance
+ );
+
+/**
+ Locate Data Hub Protocol and create event for logging data
+ as initialization for data hub status code worker.
+
+ @retval EFI_SUCCESS Initialization is successful.
+
+**/
+EFI_STATUS
+DataHubStatusCodeInitializeWorker (
+ VOID
+ );
+
+
+/**
+ Report status code into DataHub.
+
+ @param CodeType Indicates the type of status code being reported.
+ @param Value Describes the current status of a hardware or software entity.
+ This included information about the class and subclass that is used to
+ classify the entity as well as an operation.
+ @param Instance The enumeration of a hardware or software entity within
+ the system. Valid instance numbers start with 1.
+ @param CallerId This optional parameter may be used to identify the caller.
+ This parameter allows the status code driver to apply different rules to
+ different callers.
+ @param Data This optional parameter may be used to pass additional data.
+
+ @retval EFI_SUCCESS The function completed successfully.
+ @retval EFI_DEVICE_ERROR Function is reentered.
+ @retval EFI_DEVICE_ERROR Function is called at runtime.
+ @retval EFI_OUT_OF_RESOURCES Fail to allocate memory for free record buffer.
+
+**/
+EFI_STATUS
+DataHubStatusCodeReportWorker (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN EFI_GUID *CallerId,
+ IN EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+
+/**
+ Virtual address change notification call back. It converts global pointer
+ to virtual address.
+
+ @param Event Event whose notification function is being invoked.
+ @param Context Pointer to the notification function's context, which is
+ always zero in current implementation.
+
+**/
+VOID
+EFIAPI
+VirtualAddressChangeCallBack (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ );
+
+#endif
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.inf b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.inf
new file mode 100644
index 0000000000..d7c35021a2
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.inf
@@ -0,0 +1,88 @@
+## @file
+# Status Code Runtime Dxe driver produces Status Code Runtime Protocol.
+#
+# Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = StatusCodeRuntimeDxe
+ MODULE_UNI_FILE = StatusCodeRuntimeDxe.uni
+ FILE_GUID = FEDE0A1B-BCA2-4A9F-BB2B-D9FD7DEC2E9F
+ MODULE_TYPE = DXE_RUNTIME_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = StatusCodeRuntimeDxeEntry
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 EBC
+#
+# VIRTUAL_ADDRESS_MAP_CALLBACK = VirtualAddressChangeCallBack
+#
+
+[Sources]
+ SerialStatusCodeWorker.c
+ RtMemoryStatusCodeWorker.c
+ DataHubStatusCodeWorker.c
+ StatusCodeRuntimeDxe.h
+ StatusCodeRuntimeDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelFrameworkPkg/IntelFrameworkPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ OemHookStatusCodeLib
+ SerialPortLib
+ UefiRuntimeLib
+ MemoryAllocationLib
+ UefiLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ HobLib
+ PcdLib
+ PrintLib
+ ReportStatusCodeLib
+ DebugLib
+ BaseMemoryLib
+ BaseLib
+ SynchronizationLib
+
+
+[Guids]
+ gEfiDataHubStatusCodeRecordGuid ## SOMETIMES_PRODUCES ## UNDEFINED # DataRecord Guid
+ gEfiStatusCodeDataTypeDebugGuid ## SOMETIMES_PRODUCES ## UNDEFINED # Record data type
+ gMemoryStatusCodeRecordGuid ## SOMETIMES_CONSUMES ## HOB
+ gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event
+ gEfiStatusCodeDataTypeStringGuid ## SOMETIMES_CONSUMES ## UNDEFINED
+
+[Protocols]
+ gEfiStatusCodeRuntimeProtocolGuid ## PRODUCES
+ gEfiDataHubProtocolGuid ## SOMETIMES_CONSUMES # Needed if Data Hub is supported for status code
+
+[FeaturePcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeReplayIn ## CONSUMES
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdStatusCodeUseOEM ## CONSUMES
+ gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdStatusCodeUseDataHub ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial ## CONSUMES
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize |128| gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory ## SOMETIMES_CONSUMES
+
+[Depex]
+ TRUE
+[UserExtensions.TianoCore."ExtraFiles"]
+ StatusCodeRuntimeDxeExtra.uni
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.uni
new file mode 100644
index 0000000000..2f1d7cc162
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxe.uni
@@ -0,0 +1,21 @@
+// /** @file
+// Status Code Runtime Dxe driver produces Status Code Runtime Protocol.
+//
+// The Status Code Runtime DXE driver produces the Status Code Runtime Protocol.
+//
+// Copyright (c) 2006 - 2014, 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.
+//
+// **/
+
+
+#string STR_MODULE_ABSTRACT #language en-US "Produces the Status Code Runtime Protocol"
+
+#string STR_MODULE_DESCRIPTION #language en-US "The Status Code Runtime DXE driver produces the Status Code Runtime Protocol."
+
diff --git a/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxeExtra.uni b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxeExtra.uni
new file mode 100644
index 0000000000..2cc9aa33ef
--- /dev/null
+++ b/Core/IntelFrameworkModulePkg/Universal/StatusCode/RuntimeDxe/StatusCodeRuntimeDxeExtra.uni
@@ -0,0 +1,19 @@
+// /** @file
+// StatusCodeRuntimeDxe Localized Strings and Content
+//
+// Copyright (c) 2013 - 2014, 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.
+//
+// **/
+
+#string STR_PROPERTIES_MODULE_NAME
+#language en-US
+"Status Code Runtime DXE Driver"
+
+