]> git.proxmox.com Git - mirror_edk2.git/commitdiff
Check in DxeCore for Nt32 platform. Currently, it does not follow PI/UEFI2.1.
authoryshang1 <yshang1@6f19259b-4bc3-4df7-8a09-765794883524>
Wed, 4 Jul 2007 10:51:54 +0000 (10:51 +0000)
committeryshang1 <yshang1@6f19259b-4bc3-4df7-8a09-765794883524>
Wed, 4 Jul 2007 10:51:54 +0000 (10:51 +0000)
git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@3045 6f19259b-4bc3-4df7-8a09-765794883524

42 files changed:
MdeModulePkg/Core/Dxe/DebugImageInfo.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Dispatcher/dependency.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/DxeMain.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/DxeMain.inf [new file with mode: 0644]
MdeModulePkg/Core/Dxe/DxeMain.msa [new file with mode: 0644]
MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Event/event.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Event/execdata.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Event/timer.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Event/tpl.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Exec.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVol/Ffs.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVol/FwVol.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVolBlock.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/FwVolDriver.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Gcd/gcd.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Hand/DriverSupport.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Hand/Notify.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Hand/handle.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Hand/locate.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Image.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Image/Image.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Image/ImageFile.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Library.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Library/Library.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Mem/Page.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Mem/memdata.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Mem/pool.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/Misc/Stall.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c [new file with mode: 0644]
MdeModulePkg/Core/Dxe/gcd.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/hand.h [new file with mode: 0644]
MdeModulePkg/Core/Dxe/imem.h [new file with mode: 0644]

diff --git a/MdeModulePkg/Core/Dxe/DebugImageInfo.h b/MdeModulePkg/Core/Dxe/DebugImageInfo.h
new file mode 100644 (file)
index 0000000..006f629
--- /dev/null
@@ -0,0 +1,126 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  DebugImageInfo.h\r
+    \r
+Abstract:\r
+\r
+  Support functions for managing debug image info table when loading and unloading\r
+  images.\r
+\r
+--*/\r
+\r
+#ifndef __DEBUG_IMAGE_INFO_H__\r
+#define __DEBUG_IMAGE_INFO_H__\r
+\r
+#define FOUR_MEG_PAGES  0x400  \r
+#define FOUR_MEG_MASK   ((FOUR_MEG_PAGES * EFI_PAGE_SIZE) - 1)\r
+\r
+#define EFI_DEBUG_TABLE_ENTRY_SIZE       (sizeof (VOID *))\r
+\r
+VOID\r
+CoreInitializeDebugImageInfoTable (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Creates and initializes the DebugImageInfo Table.  Also creates the configuration\r
+  table and registers it into the system table.\r
+\r
+Arguments:\r
+  None\r
+\r
+Returns:\r
+  NA\r
+\r
+Notes:\r
+  This function allocates memory, frees it, and then allocates memory at an\r
+  address within the initial allocation. Since this function is called early\r
+  in DXE core initialization (before drivers are dispatched), this should not\r
+  be a problem.\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreUpdateDebugTableCrc32 (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Update the CRC32 in the Debug Table.\r
+  Since the CRC32 service is made available by the Runtime driver, we have to\r
+  wait for the Runtime Driver to be installed before the CRC32 can be computed.\r
+  This function is called elsewhere by the core when the runtime architectural\r
+  protocol is produced.\r
+\r
+Arguments:\r
+  None\r
+\r
+Returns:\r
+  NA\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreNewDebugImageInfoEntry (\r
+  UINT32                    ImageInfoType,\r
+  EFI_LOADED_IMAGE_PROTOCOL *LoadedImage,\r
+  EFI_HANDLE                ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Adds a new DebugImageInfo structure to the DebugImageInfo Table.  Re-Allocates\r
+  the table if it's not large enough to accomidate another entry.\r
+\r
+Arguments:\r
+\r
+  ImageInfoType     - type of debug image information\r
+  LoadedImage       - pointer to the loaded image protocol for the image being loaded\r
+  ImageHandle       - image handle for the image being loaded\r
+\r
+Returns:\r
+  NA\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreRemoveDebugImageInfoEntry (\r
+  EFI_HANDLE ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes and frees an entry from the DebugImageInfo Table.\r
+\r
+Arguments:\r
+\r
+  ImageHandle       - image handle for the image being unloaded\r
+\r
+Returns:\r
+\r
+  NA\r
+\r
+--*/\r
+;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c
new file mode 100644 (file)
index 0000000..9792a16
--- /dev/null
@@ -0,0 +1,1170 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  Dispatcher.c\r
+\r
+Abstract:\r
+\r
+  Tiano DXE Dispatcher.\r
+\r
+  Step #1 - When a FV protocol is added to the system every driver in the FV\r
+            is added to the mDiscoveredList. The SOR, Before, and After Depex are \r
+            pre-processed as drivers are added to the mDiscoveredList. If an Apriori \r
+            file exists in the FV those drivers are addeded to the \r
+            mScheduledQueue. The mFvHandleList is used to make sure a \r
+            FV is only processed once.\r
+\r
+  Step #2 - Dispatch. Remove driver from the mScheduledQueue and load and\r
+            start it. After mScheduledQueue is drained check the \r
+            mDiscoveredList to see if any item has a Depex that is ready to \r
+            be placed on the mScheduledQueue.\r
+\r
+  Step #3 - Adding to the mScheduledQueue requires that you process Before \r
+            and After dependencies. This is done recursively as the call to add\r
+            to the mScheduledQueue checks for Before and recursively adds \r
+            all Befores. It then addes the item that was passed in and then \r
+            processess the After dependecies by recursively calling the routine.\r
+\r
+  Dispatcher Rules:\r
+  The rules for the dispatcher are in chapter 10 of the DXE CIS. Figure 10-3 \r
+  is the state diagram for the DXE dispatcher\r
+\r
+  Depex - Dependency Expresion.\r
+  SOR   - Schedule On Request - Don't schedule if this bit is set.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// The Driver List contains one copy of every driver that has been discovered.\r
+// Items are never removed from the driver list. List of EFI_CORE_DRIVER_ENTRY\r
+//\r
+LIST_ENTRY  mDiscoveredList = INITIALIZE_LIST_HEAD_VARIABLE (mDiscoveredList);  \r
+\r
+//\r
+// Queue of drivers that are ready to dispatch. This queue is a subset of the\r
+// mDiscoveredList.list of EFI_CORE_DRIVER_ENTRY.\r
+//\r
+LIST_ENTRY  mScheduledQueue = INITIALIZE_LIST_HEAD_VARIABLE (mScheduledQueue);\r
+\r
+//\r
+// List of handles who's Fv's have been parsed and added to the mFwDriverList.\r
+//\r
+LIST_ENTRY  mFvHandleList = INITIALIZE_LIST_HEAD_VARIABLE (mFvHandleList);           // list of KNOWN_HANDLE\r
+\r
+//\r
+// Lock for mDiscoveredList, mScheduledQueue, gDispatcherRunning.\r
+//\r
+EFI_LOCK  mDispatcherLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL);\r
+\r
+\r
+//\r
+// Flag for the DXE Dispacher.  TRUE if dispatcher is execuing.\r
+//\r
+BOOLEAN  gDispatcherRunning = FALSE;\r
+\r
+//\r
+// Module globals to manage the FwVol registration notification event\r
+//\r
+EFI_EVENT       mFwVolEvent;\r
+VOID            *mFwVolEventRegistration;\r
+\r
+//\r
+// List of file types supported by dispatcher\r
+//\r
+static EFI_FV_FILETYPE mDxeFileTypes[] = { \r
+  EFI_FV_FILETYPE_DRIVER, \r
+  EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER, \r
+  EFI_FV_FILETYPE_DXE_CORE,\r
+  EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE\r
+};\r
+\r
+typedef struct {\r
+  MEDIA_FW_VOL_FILEPATH_DEVICE_PATH   File;\r
+  EFI_DEVICE_PATH_PROTOCOL            End;\r
+} FV_FILEPATH_DEVICE_PATH;\r
+\r
+FV_FILEPATH_DEVICE_PATH mFvDevicePath;\r
+\r
+\r
+//\r
+// Function Prototypes\r
+//\r
+STATIC\r
+VOID\r
+CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *InsertedDriverEntry\r
+  );\r
\r
+STATIC\r
+VOID\r
+EFIAPI\r
+CoreFwVolEventProtocolNotify (\r
+  IN  EFI_EVENT       Event,\r
+  IN  VOID            *Context\r
+  );\r
+\r
+STATIC\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreFvToDevicePath (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv,\r
+  IN  EFI_HANDLE                      FvHandle,\r
+  IN  EFI_GUID                        *DriverName\r
+  );\r
+\r
+STATIC \r
+EFI_STATUS\r
+CoreAddToDriverList (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL  *Fv,\r
+  IN  EFI_HANDLE                    FvHandle,\r
+  IN  EFI_GUID                      *DriverName\r
+  );\r
+\r
+STATIC\r
+EFI_STATUS \r
+CoreProcessFvImageFile (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv,\r
+  IN  EFI_HANDLE                      FvHandle,\r
+  IN  EFI_GUID                        *DriverName\r
+  );\r
+\r
+STATIC\r
+VOID\r
+CoreAcquireDispatcherLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Enter critical section by gaining lock on mDispatcherLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+\r
+{\r
+  CoreAcquireLock (&mDispatcherLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreReleaseDispatcherLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Exit critical section by releasing lock on mDispatcherLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&mDispatcherLock);\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreGetDepexSectionAndPreProccess (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *DriverEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Read Depex and pre-process the Depex for Before and After. If Section Extraction\r
+  protocol returns an error via ReadSection defer the reading of the Depex.\r
+\r
+Arguments:\r
+\r
+  DriverEntry - Driver to work on.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS - Depex read and preprossesed \r
+\r
+  EFI_PROTOCOL_ERROR - The section extraction protocol returned an error and \r
+                        Depex reading needs to be retried.\r
+\r
+  Other Error - DEPEX not found.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                    Status;\r
+  EFI_SECTION_TYPE              SectionType;\r
+  UINT32                        AuthenticationStatus;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL  *Fv;\r
+\r
+  \r
+  Fv = DriverEntry->Fv;\r
+\r
+  //\r
+  // Grab Depex info, it will never be free'ed.\r
+  //\r
+  SectionType         = EFI_SECTION_DXE_DEPEX;\r
+  Status = Fv->ReadSection (\r
+                DriverEntry->Fv, \r
+                &DriverEntry->FileName,\r
+                SectionType, \r
+                0, \r
+                &DriverEntry->Depex, \r
+                (UINTN *)&DriverEntry->DepexSize,\r
+                &AuthenticationStatus\r
+                );\r
+  if (EFI_ERROR (Status)) {\r
+    if (Status == EFI_PROTOCOL_ERROR) {\r
+      //\r
+      // The section extraction protocol failed so set protocol error flag\r
+      //\r
+      DriverEntry->DepexProtocolError = TRUE;\r
+    } else {\r
+      //\r
+      // If no Depex assume EFI 1.1 driver model\r
+      //\r
+      DriverEntry->Depex = NULL;\r
+      DriverEntry->Dependent = TRUE;\r
+      DriverEntry->DepexProtocolError = FALSE;\r
+    }\r
+  } else {\r
+    //\r
+    // Set Before, After, and Unrequested state information based on Depex\r
+    // Driver will be put in Dependent or Unrequested state\r
+    //\r
+    CorePreProcessDepex (DriverEntry);\r
+    DriverEntry->DepexProtocolError = FALSE;\r
+  }  \r
+\r
+  return Status;\r
+}\r
+\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSchedule (\r
+  IN  EFI_HANDLE  FirmwareVolumeHandle,\r
+  IN  EFI_GUID    *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check every driver and locate a matching one. If the driver is found, the Unrequested\r
+  state flag is cleared.\r
+\r
+Arguments:\r
+\r
+  FirmwareVolumeHandle - The handle of the Firmware Volume that contains the firmware \r
+                         file specified by DriverName.\r
+\r
+  DriverName           - The Driver name to put in the Dependent state.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The DriverName was found and it's SOR bit was cleared\r
+\r
+  EFI_NOT_FOUND - The DriverName does not exist or it's SOR bit was not set.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY            *Link;\r
+  EFI_CORE_DRIVER_ENTRY *DriverEntry;\r
+\r
+  //\r
+  // Check every driver\r
+  //\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->FvHandle == FirmwareVolumeHandle &&\r
+        DriverEntry->Unrequested && \r
+        CompareGuid (DriverName, &DriverEntry->FileName)) {\r
+      //\r
+      // Move the driver from the Unrequested to the Dependent state\r
+      //\r
+      CoreAcquireDispatcherLock ();\r
+      DriverEntry->Unrequested  = FALSE;\r
+      DriverEntry->Dependent    = TRUE;\r
+      CoreReleaseDispatcherLock ();\r
+    \r
+      return EFI_SUCCESS;\r
+    }\r
+  }\r
+  return EFI_NOT_FOUND;  \r
+}\r
+\r
+\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreTrust (\r
+  IN  EFI_HANDLE  FirmwareVolumeHandle,\r
+  IN  EFI_GUID    *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Convert a driver from the Untrused back to the Scheduled state\r
+\r
+Arguments:\r
+\r
+  FirmwareVolumeHandle - The handle of the Firmware Volume that contains the firmware \r
+                         file specified by DriverName.\r
+\r
+  DriverName           - The Driver name to put in the Scheduled state\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The file was found in the untrusted state, and it was promoted \r
+                  to the trusted state.\r
+\r
+  EFI_NOT_FOUND - The file was not found in the untrusted state.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY            *Link;\r
+  EFI_CORE_DRIVER_ENTRY *DriverEntry;\r
+\r
+  //\r
+  // Check every driver\r
+  //\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->FvHandle == FirmwareVolumeHandle &&\r
+        DriverEntry->Untrusted && \r
+        CompareGuid (DriverName, &DriverEntry->FileName)) {\r
+      //\r
+      // Transition driver from Untrusted to Scheduled state.\r
+      //\r
+      CoreAcquireDispatcherLock ();\r
+      DriverEntry->Untrusted = FALSE;\r
+      DriverEntry->Scheduled = TRUE;\r
+      InsertTailList (&mScheduledQueue, &DriverEntry->ScheduledLink);\r
+      CoreReleaseDispatcherLock ();\r
+    \r
+      return EFI_SUCCESS;\r
+    }\r
+  }\r
+  return EFI_NOT_FOUND;  \r
+}\r
+\r
+\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreDispatcher (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  This is the main Dispatcher for DXE and it exits when there are no more \r
+  drivers to run. Drain the mScheduledQueue and load and start a PE\r
+  image for each driver. Search the mDiscoveredList to see if any driver can \r
+  be placed on the mScheduledQueue. If no drivers are placed on the\r
+  mScheduledQueue exit the function. On exit it is assumed the Bds()\r
+  will be called, and when the Bds() exits the Dispatcher will be called \r
+  again.\r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  EFI_ALREADY_STARTED - The DXE Dispatcher is already running\r
+\r
+  EFI_NOT_FOUND       - No DXE Drivers were dispatched\r
+\r
+  EFI_SUCCESS         - One or more DXE Drivers were dispatched\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                      Status;\r
+  EFI_STATUS                      ReturnStatus;\r
+  LIST_ENTRY                      *Link;\r
+  EFI_CORE_DRIVER_ENTRY           *DriverEntry;\r
+  BOOLEAN                         ReadyToRun;\r
+\r
+  if (gDispatcherRunning) {\r
+    //\r
+    // If the dispatcher is running don't let it be restarted.\r
+    //\r
+    return EFI_ALREADY_STARTED;\r
+  }\r
+\r
+  gDispatcherRunning = TRUE;\r
+\r
+\r
+  ReturnStatus = EFI_NOT_FOUND;\r
+  do {\r
+    //\r
+    // Drain the Scheduled Queue\r
+    //\r
+    while (!IsListEmpty (&mScheduledQueue)) {\r
+      DriverEntry = CR (\r
+                      mScheduledQueue.ForwardLink,\r
+                      EFI_CORE_DRIVER_ENTRY,\r
+                      ScheduledLink,\r
+                      EFI_CORE_DRIVER_ENTRY_SIGNATURE\r
+                      );\r
+\r
+      //\r
+      // Load the DXE Driver image into memory. If the Driver was transitioned from\r
+      // Untrused to Scheduled it would have already been loaded so we may need to\r
+      // skip the LoadImage\r
+      //\r
+      if (DriverEntry->ImageHandle == NULL) {\r
+        Status = CoreLoadImage (\r
+                        FALSE, \r
+                        gDxeCoreImageHandle, \r
+                        DriverEntry->FvFileDevicePath,\r
+                        NULL, \r
+                        0, \r
+                        &DriverEntry->ImageHandle\r
+                        );\r
+\r
+        //\r
+        // Update the driver state to reflect that it's been loaded\r
+        //\r
+        if (EFI_ERROR (Status)) {\r
+          CoreAcquireDispatcherLock ();\r
+\r
+          if (Status == EFI_SECURITY_VIOLATION) {\r
+            //\r
+            // Take driver from Scheduled to Untrused state\r
+            //\r
+            DriverEntry->Untrusted = TRUE;\r
+          } else {\r
+            //\r
+            // The DXE Driver could not be loaded, and do not attempt to load or start it again.\r
+            // Take driver from Scheduled to Initialized. \r
+            //\r
+            // This case include the Never Trusted state if EFI_ACCESS_DENIED is returned\r
+            //\r
+            DriverEntry->Initialized  = TRUE;\r
+          }\r
+\r
+          DriverEntry->Scheduled = FALSE;\r
+          RemoveEntryList (&DriverEntry->ScheduledLink);\r
+          \r
+          CoreReleaseDispatcherLock ();\r
+        \r
+          //\r
+          // If it's an error don't try the StartImage\r
+          //\r
+          continue;\r
+        }\r
+      }\r
+\r
+      CoreAcquireDispatcherLock ();\r
+\r
+      DriverEntry->Scheduled    = FALSE;\r
+      DriverEntry->Initialized  = TRUE;\r
+      RemoveEntryList (&DriverEntry->ScheduledLink);\r
+      \r
+      CoreReleaseDispatcherLock ();\r
+\r
+\r
+      CoreReportProgressCodeSpecific (EFI_SOFTWARE_DXE_CORE | EFI_SW_PC_INIT_BEGIN, DriverEntry->ImageHandle);\r
+      Status = CoreStartImage (DriverEntry->ImageHandle, NULL, NULL);\r
+      CoreReportProgressCodeSpecific (EFI_SOFTWARE_DXE_CORE | EFI_SW_PC_INIT_END, DriverEntry->ImageHandle);\r
+\r
+      ReturnStatus = EFI_SUCCESS;\r
+    }\r
+\r
+    //\r
+    // Search DriverList for items to place on Scheduled Queue\r
+    //\r
+    ReadyToRun = FALSE;\r
+    for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+      DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+\r
+      if (DriverEntry->DepexProtocolError){\r
+        //\r
+        // If Section Extraction Protocol did not let the Depex be read before retry the read\r
+        //\r
+        Status = CoreGetDepexSectionAndPreProccess (DriverEntry);\r
+      } \r
+\r
+      if (DriverEntry->Dependent) {\r
+        if (CoreIsSchedulable (DriverEntry)) {\r
+          CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry); \r
+          ReadyToRun = TRUE;\r
+        } \r
+      }\r
+    }\r
+  } while (ReadyToRun);\r
+\r
+  gDispatcherRunning = FALSE;\r
+\r
+  return ReturnStatus;\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *InsertedDriverEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Insert InsertedDriverEntry onto the mScheduledQueue. To do this you \r
+  must add any driver with a before dependency on InsertedDriverEntry first.\r
+  You do this by recursively calling this routine. After all the Befores are\r
+  processed you can add InsertedDriverEntry to the mScheduledQueue. \r
+  Then you can add any driver with an After dependency on InsertedDriverEntry \r
+  by recursively calling this routine.\r
+\r
+Arguments:\r
+\r
+  InsertedDriverEntry - The driver to insert on the ScheduledLink Queue\r
+\r
+Returns:\r
+\r
+  NONE \r
+\r
+--*/\r
+{\r
+  LIST_ENTRY            *Link;\r
+  EFI_CORE_DRIVER_ENTRY *DriverEntry;\r
+\r
+  //\r
+  // Process Before Dependency\r
+  //\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->Before && DriverEntry->Dependent) {\r
+      if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {\r
+        //\r
+        // Recursively process BEFORE\r
+        //\r
+        CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Convert driver from Dependent to Scheduled state\r
+  //\r
+  CoreAcquireDispatcherLock ();\r
+\r
+  InsertedDriverEntry->Dependent = FALSE;\r
+  InsertedDriverEntry->Scheduled = TRUE;\r
+  InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink);\r
+  \r
+  CoreReleaseDispatcherLock ();\r
+\r
+  //\r
+  // Process After Dependency\r
+  //\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->After && DriverEntry->Dependent) {\r
+      if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {\r
+        //\r
+        // Recursively process AFTER\r
+        //\r
+        CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+STATIC\r
+BOOLEAN\r
+FvHasBeenProcessed (\r
+  IN  EFI_HANDLE      FvHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return TRUE if the Fv has been processed, FALSE if not.\r
+\r
+Arguments:\r
+\r
+  FvHandle - The handle of a FV that's being tested\r
+\r
+Returns:\r
+\r
+  TRUE  - Fv protocol on FvHandle has been processed\r
+\r
+  FALSE - Fv protocol on FvHandle has not yet been processed\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY      *Link;\r
+  KNOWN_HANDLE    *KnownHandle;\r
+\r
+  for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) {\r
+    KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE);\r
+    if (KnownHandle->Handle == FvHandle) {\r
+      return TRUE;\r
+    }\r
+  }\r
+  return FALSE;\r
+}\r
+\r
+STATIC\r
+VOID\r
+FvIsBeingProcesssed (\r
+  IN  EFI_HANDLE    FvHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Remember that Fv protocol on FvHandle has had it's drivers placed on the\r
+  mDiscoveredList. This fucntion adds entries on the mFvHandleList. Items are\r
+  never removed/freed from the mFvHandleList.\r
+\r
+Arguments:\r
+\r
+  FvHandle - The handle of a FV that has been processed\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  KNOWN_HANDLE  *KnownHandle;\r
+\r
+  KnownHandle = CoreAllocateBootServicesPool (sizeof (KNOWN_HANDLE));\r
+  ASSERT (KnownHandle != NULL);\r
+\r
+  KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE;\r
+  KnownHandle->Handle = FvHandle;\r
+  InsertTailList (&mFvHandleList, &KnownHandle->Link);\r
+}\r
+\r
+\r
+\r
+STATIC\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreFvToDevicePath (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv,\r
+  IN  EFI_HANDLE                      FvHandle,\r
+  IN  EFI_GUID                        *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Convert FvHandle and DriverName into an EFI device path\r
+\r
+Arguments:\r
+\r
+  Fv         - Fv protocol, needed to read Depex info out of FLASH.\r
+  \r
+  FvHandle   - Handle for Fv, needed in the EFI_CORE_DRIVER_ENTRY so that the\r
+               PE image can be read out of the FV at a later time.\r
+\r
+  DriverName - Name of driver to add to mDiscoveredList.\r
+\r
+Returns:\r
+\r
+  Pointer to device path constructed from FvHandle and DriverName\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  EFI_DEVICE_PATH_PROTOCOL            *FvDevicePath;\r
+  EFI_DEVICE_PATH_PROTOCOL            *FileNameDevicePath;\r
+\r
+  //\r
+  // Remember the device path of the FV\r
+  //\r
+  Status = CoreHandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);\r
+  if (EFI_ERROR (Status)) {\r
+    FileNameDevicePath = NULL;\r
+  } else {\r
+    //\r
+    // Build a device path to the file in the FV to pass into gBS->LoadImage\r
+    //\r
+    EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, DriverName);\r
+    mFvDevicePath.End.Type = EFI_END_ENTIRE_DEVICE_PATH;\r
+    mFvDevicePath.End.SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;\r
+    SetDevicePathNodeLength (&mFvDevicePath.End, sizeof (EFI_DEVICE_PATH_PROTOCOL));\r
+\r
+    FileNameDevicePath = CoreAppendDevicePath (\r
+                            FvDevicePath, \r
+                            (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath\r
+                            );\r
+  }\r
+\r
+  return FileNameDevicePath;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+CoreAddToDriverList (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv,\r
+  IN  EFI_HANDLE                      FvHandle,\r
+  IN  EFI_GUID                        *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add an entry to the mDiscoveredList. Allocate memory to store the DriverEntry, \r
+  and initilize any state variables. Read the Depex from the FV and store it\r
+  in DriverEntry. Pre-process the Depex to set the SOR, Before and After state.\r
+  The Discovered list is never free'ed and contains booleans that represent the\r
+  other possible DXE driver states.\r
+\r
+Arguments:\r
+\r
+  Fv         - Fv protocol, needed to read Depex info out of FLASH.\r
+  \r
+  FvHandle   - Handle for Fv, needed in the EFI_CORE_DRIVER_ENTRY so that the\r
+               PE image can be read out of the FV at a later time.\r
+\r
+  DriverName - Name of driver to add to mDiscoveredList.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - If driver was added to the mDiscoveredList.\r
+\r
+  EFI_ALREADY_STARTED - The driver has already been started. Only one DriverName\r
+                        may be active in the system at any one time.\r
+\r
+--*/\r
+{\r
+  EFI_CORE_DRIVER_ENTRY               *DriverEntry;\r
+\r
\r
+  //\r
+  // Create the Driver Entry for the list. ZeroPool initializes lots of variables to \r
+  // NULL or FALSE.\r
+  //\r
+  DriverEntry = CoreAllocateZeroBootServicesPool (sizeof (EFI_CORE_DRIVER_ENTRY));\r
+  ASSERT (DriverEntry != NULL);\r
+\r
+  DriverEntry->Signature        = EFI_CORE_DRIVER_ENTRY_SIGNATURE;\r
+  CopyMem (&DriverEntry->FileName, DriverName, sizeof (EFI_GUID));\r
+  DriverEntry->FvHandle         = FvHandle;\r
+  DriverEntry->Fv               = Fv;\r
+  DriverEntry->FvFileDevicePath = CoreFvToDevicePath (Fv, FvHandle, DriverName);\r
+\r
+  CoreGetDepexSectionAndPreProccess (DriverEntry);\r
+  \r
+  CoreAcquireDispatcherLock ();\r
+  \r
+  InsertTailList (&mDiscoveredList, &DriverEntry->Link);\r
+\r
+  CoreReleaseDispatcherLock ();\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS \r
+CoreProcessFvImageFile (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv,\r
+  IN  EFI_HANDLE                      FvHandle,\r
+  IN  EFI_GUID                        *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Get the driver from the FV through driver name, and produce a FVB protocol on FvHandle.\r
+\r
+Arguments:\r
+\r
+  Fv          - The FIRMWARE_VOLUME protocol installed on the FV.\r
+  FvHandle    - The handle which FVB protocol installed on.\r
+  DriverName  - The driver guid specified.\r
+\r
+Returns:\r
+\r
+  EFI_OUT_OF_RESOURCES    - No enough memory or other resource.\r
+  \r
+  EFI_VOLUME_CORRUPTED    - Corrupted volume.\r
+  \r
+  EFI_SUCCESS             - Function successfully returned.\r
+  \r
+\r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  EFI_SECTION_TYPE                    SectionType;\r
+  UINT32                              AuthenticationStatus;\r
+  VOID                                *Buffer;\r
+  UINTN                               BufferSize;\r
+\r
+  //\r
+  // Read the first (and only the first) firmware volume section\r
+  //\r
+  SectionType = EFI_SECTION_FIRMWARE_VOLUME_IMAGE;\r
+  Buffer      = NULL;\r
+  BufferSize  = 0;\r
+  Status = Fv->ReadSection (\r
+                Fv, \r
+                DriverName, \r
+                SectionType, \r
+                0, \r
+                &Buffer, \r
+                &BufferSize,\r
+                &AuthenticationStatus\r
+                );\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Produce a FVB protocol for the file\r
+    //\r
+    Status = ProduceFVBProtocolOnBuffer (\r
+              (EFI_PHYSICAL_ADDRESS) (UINTN) Buffer,\r
+              (UINT64)BufferSize,\r
+              FvHandle,\r
+              NULL\r
+              );\r
+  }\r
+\r
+  if (EFI_ERROR (Status) && (Buffer != NULL)) {    \r
+  //\r
+  // ReadSection or Produce FVB failed, Free data buffer\r
+  //\r
+  CoreFreePool (Buffer); \r
+\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+CoreFwVolEventProtocolNotify (\r
+  IN  EFI_EVENT       Event,\r
+  IN  VOID            *Context\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Event notification that is fired every time a FV dispatch protocol is added. \r
+  More than one protocol may have been added when this event is fired, so you\r
+  must loop on CoreLocateHandle () to see how many protocols were added and\r
+  do the following to each FV:\r
+\r
+  If the Fv has already been processed, skip it. If the Fv has not been \r
+  processed then mark it as being processed, as we are about to process it.\r
+\r
+  Read the Fv and add any driver in the Fv to the mDiscoveredList.The \r
+  mDiscoveredList is never free'ed and contains variables that define\r
+  the other states the DXE driver transitions to.. \r
+  \r
+  While you are at it read the A Priori file into memory.\r
+  Place drivers in the A Priori list onto the mScheduledQueue.\r
+\r
+Arguments:\r
+\r
+  Event   - The Event that is being processed, not used.\r
+  \r
+  Context - Event Context, not used.\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                    Status;\r
+  EFI_STATUS                    GetNextFileStatus;\r
+  EFI_STATUS                    SecurityStatus;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL  *Fv;\r
+  EFI_DEVICE_PATH_PROTOCOL      *FvDevicePath;\r
+  EFI_HANDLE                    FvHandle;\r
+  UINTN                         BufferSize;\r
+  EFI_GUID                      NameGuid;\r
+  UINTN                         Key;\r
+  EFI_FV_FILETYPE               Type;\r
+  EFI_FV_FILE_ATTRIBUTES        Attributes;\r
+  UINTN                         Size;\r
+  EFI_CORE_DRIVER_ENTRY         *DriverEntry;\r
+  EFI_GUID                      *AprioriFile;\r
+  UINTN                         AprioriEntryCount;\r
+  UINTN                         Index;\r
+  LIST_ENTRY                    *Link;\r
+  UINT32                        AuthenticationStatus;\r
+  UINTN                         SizeOfBuffer;\r
+\r
+\r
+  while (TRUE) {\r
+    BufferSize = sizeof (EFI_HANDLE);\r
+    Status = CoreLocateHandle (\r
+                    ByRegisterNotify,\r
+                    NULL,\r
+                    mFwVolEventRegistration,\r
+                    &BufferSize,\r
+                    &FvHandle\r
+                    );\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // If no more notification events exit\r
+      //\r
+      return;\r
+    }\r
+\r
+    if (FvHasBeenProcessed (FvHandle)) {\r
+      //\r
+      // This Fv has already been processed so lets skip it!\r
+      //\r
+      continue;\r
+    }\r
+\r
+    Status = CoreHandleProtocol (FvHandle, &gEfiFirmwareVolumeDispatchProtocolGuid, (VOID **)&Fv);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // If no dispatch protocol then skip, but do not marked as being processed as it\r
+      // may show up later.\r
+      //\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // Since we are about to process this Fv mark it as processed.\r
+    //\r
+    FvIsBeingProcesssed (FvHandle);\r
+\r
+\r
+    Status = CoreHandleProtocol (FvHandle, &gEfiFirmwareVolumeProtocolGuid, (VOID **)&Fv);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // The Handle has a FirmwareVolumeDispatch protocol and should also contiain\r
+      // a FirmwareVolume protocol thus we should never get here.\r
+      //\r
+      ASSERT (FALSE);\r
+      continue;\r
+    }\r
+    \r
+    Status = CoreHandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // The Firmware volume doesn't have device path, can't be dispatched.\r
+      //\r
+      continue;\r
+    }\r
+    \r
+    //\r
+    // Evaluate the authentication status of the Firmware Volume through \r
+    // Security Architectural Protocol\r
+    //\r
+    if (gSecurity != NULL) {\r
+      SecurityStatus = gSecurity->FileAuthenticationState (\r
+                                    gSecurity, \r
+                                    0, \r
+                                    FvDevicePath\r
+                                    );\r
+      if (SecurityStatus != EFI_SUCCESS) {\r
+        //\r
+        // Security check failed. The firmware volume should not be used for any purpose.\r
+        //\r
+        continue;\r
+      }\r
+    }   \r
+    \r
+    //\r
+    // Discover Drivers in FV and add them to the Discovered Driver List. \r
+    // Process EFI_FV_FILETYPE_DRIVER type and then EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER \r
+    //  EFI_FV_FILETYPE_DXE_CORE is processed to produce a Loaded Image protocol for the core\r
+    //  EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE is processed to create a Fvb\r
+    //\r
+    for (Index = 0; Index < sizeof (mDxeFileTypes)/sizeof (EFI_FV_FILETYPE); Index++) {\r
+      //\r
+      // Initialize the search key\r
+      //\r
+      Key = 0;\r
+      do {\r
+        Type = mDxeFileTypes[Index];\r
+        GetNextFileStatus = Fv->GetNextFile (\r
+                                  Fv, \r
+                                  &Key,\r
+                                  &Type,  \r
+                                  &NameGuid, \r
+                                  &Attributes, \r
+                                  &Size\r
+                                  );\r
+        if (!EFI_ERROR (GetNextFileStatus)) {\r
+          if (Type == EFI_FV_FILETYPE_DXE_CORE) {\r
+            //\r
+            // If this is the DXE core fill in it's DevicePath & DeviceHandle\r
+            //\r
+            if (gDxeCoreLoadedImage->FilePath == NULL) {\r
+              if (CompareGuid (&NameGuid, gDxeCoreFileName)) {\r
+                //\r
+                // Maybe One specail Fv cantains only one DXE_CORE module, so its device path must\r
+                // be initialized completely.\r
+                //\r
+                EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, &NameGuid);\r
+                mFvDevicePath.End.Type = EFI_END_ENTIRE_DEVICE_PATH;\r
+                mFvDevicePath.End.SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;\r
+                SetDevicePathNodeLength (&mFvDevicePath.End, sizeof (EFI_DEVICE_PATH_PROTOCOL));\r
+\r
+                gDxeCoreLoadedImage->FilePath = CoreDuplicateDevicePath (\r
+                                                  (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath\r
+                                                  );\r
+                gDxeCoreLoadedImage->DeviceHandle = FvHandle;\r
+              }\r
+            }\r
+          } else if (Type == EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {\r
+            //\r
+            // Found a firmware volume image. Produce a firmware volume block\r
+            // protocol for it so it gets dispatched from. This is usually a \r
+            // capsule.\r
+            //\r
+            CoreProcessFvImageFile (Fv, FvHandle, &NameGuid);\r
+          } else {\r
+            //\r
+            // Transition driver from Undiscovered to Discovered state\r
+            //\r
+            CoreAddToDriverList (Fv, FvHandle, &NameGuid);\r
+          }\r
+        }\r
+      } while (!EFI_ERROR (GetNextFileStatus));\r
+    }\r
+    \r
+    //\r
+    // Read the array of GUIDs from the Apriori file if it is present in the firmware volume\r
+    //\r
+    AprioriFile = NULL;\r
+    Status = Fv->ReadSection (\r
+                  Fv,\r
+                  &gAprioriGuid,\r
+                  EFI_SECTION_RAW,\r
+                  0,\r
+                  (VOID **)&AprioriFile,\r
+                  &SizeOfBuffer,\r
+                  &AuthenticationStatus\r
+                  );\r
+    if (!EFI_ERROR (Status)) {\r
+      AprioriEntryCount = SizeOfBuffer / sizeof (EFI_GUID);\r
+    } else {\r
+      AprioriEntryCount = 0;\r
+    }\r
+\r
+    //\r
+    // Put drivers on Apriori List on the Scheduled queue. The Discovered List includes\r
+    // drivers not in the current FV and these must be skipped since the a priori list\r
+    // is only valid for the FV that it resided in.\r
+    //\r
+    CoreAcquireDispatcherLock ();\r
+    \r
+    for (Index = 0; Index < AprioriEntryCount; Index++) {\r
+      for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+        DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+        if (CompareGuid (&DriverEntry->FileName, &AprioriFile[Index]) &&\r
+            (FvHandle == DriverEntry->FvHandle)) {\r
+          DriverEntry->Dependent = FALSE;\r
+          DriverEntry->Scheduled = TRUE;\r
+          InsertTailList (&mScheduledQueue, &DriverEntry->ScheduledLink);\r
+          break;\r
+        }\r
+      }\r
+    }\r
+\r
+    CoreReleaseDispatcherLock ();\r
+\r
+    //\r
+    // Free data allocated by Fv->ReadSection () \r
+    //\r
+    CoreFreePool (AprioriFile);  \r
+  }\r
+}\r
+\r
+\r
+VOID\r
+CoreInitializeDispatcher (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initialize the dispatcher. Initialize the notification function that runs when\r
+  a FV protocol is added to the system.\r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  NONE \r
+\r
+--*/\r
+{\r
+  mFwVolEvent = CoreCreateProtocolNotifyEvent (\r
+                  &gEfiFirmwareVolumeProtocolGuid, \r
+                  TPL_CALLBACK,\r
+                  CoreFwVolEventProtocolNotify,\r
+                  NULL,\r
+                  &mFwVolEventRegistration,\r
+                  TRUE\r
+                  );\r
+}\r
+\r
+//\r
+// Function only used in debug builds\r
+//\r
+VOID\r
+CoreDisplayDiscoveredNotDispatched (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Traverse the discovered list for any drivers that were discovered but not loaded \r
+  because the dependency experessions evaluated to false\r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  NONE \r
+\r
+--*/\r
+{\r
+  LIST_ENTRY                    *Link;\r
+  EFI_CORE_DRIVER_ENTRY         *DriverEntry;\r
+\r
+  for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->Dependent) {\r
+      DEBUG ((EFI_D_LOAD, "Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName));\r
+    }\r
+  }\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Dispatcher/dependency.c b/MdeModulePkg/Core/Dxe/Dispatcher/dependency.c
new file mode 100644 (file)
index 0000000..7c2093b
--- /dev/null
@@ -0,0 +1,452 @@
+/*++ \r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  dependency.c\r
+\r
+Abstract:\r
+\r
+  DXE Dispatcher Dependency Evaluator\r
+\r
+  This routine evaluates a dependency expression (DEPENDENCY_EXPRESSION) to determine\r
+  if a driver can be scheduled for execution.  The criteria for\r
+  schedulability is that the dependency expression is satisfied.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// Global stack used to evaluate dependency expressions\r
+//\r
+BOOLEAN *mDepexEvaluationStack        = NULL;\r
+BOOLEAN *mDepexEvaluationStackEnd     = NULL;\r
+BOOLEAN *mDepexEvaluationStackPointer = NULL;\r
+\r
+//\r
+// Worker functions\r
+//\r
+\r
+STATIC\r
+EFI_STATUS\r
+GrowDepexStack (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Grow size of the Depex stack\r
+\r
+Arguments:\r
+\r
+  Stack     - Old stack on the way in and new stack on the way out\r
+\r
+  StackSize - New size of the stack\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS          - Stack successfully growed.\r
+  \r
+  EFI_OUT_OF_RESOURCES - There is not enough system memory to grow the stack.\r
+  \r
+  \r
+\r
+--*/\r
+{\r
+  BOOLEAN     *NewStack;\r
+  UINTN       Size;\r
+\r
+  Size = DEPEX_STACK_SIZE_INCREMENT;\r
+  if (mDepexEvaluationStack != NULL) {\r
+    Size = Size + (mDepexEvaluationStackEnd - mDepexEvaluationStack);\r
+  }\r
+\r
+  NewStack = CoreAllocateBootServicesPool (Size * sizeof (BOOLEAN));\r
+  if (NewStack == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  if (mDepexEvaluationStack != NULL) {\r
+    //\r
+    // Copy to Old Stack to the New Stack\r
+    //\r
+    CopyMem (\r
+      NewStack, \r
+      mDepexEvaluationStack, \r
+      (mDepexEvaluationStackEnd - mDepexEvaluationStack) * sizeof (BOOLEAN)\r
+      );\r
+\r
+    //\r
+    // Free The Old Stack\r
+    //\r
+    CoreFreePool (mDepexEvaluationStack);\r
+  }\r
+\r
+  //\r
+  // Make the Stack pointer point to the old data in the new stack\r
+  //\r
+  mDepexEvaluationStackPointer = NewStack + (mDepexEvaluationStackPointer - mDepexEvaluationStack);\r
+  mDepexEvaluationStack        = NewStack;\r
+  mDepexEvaluationStackEnd     = NewStack + Size;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+PushBool (\r
+  IN BOOLEAN  Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Push an element onto the Boolean Stack\r
+\r
+Arguments:\r
+\r
+  Value - BOOLEAN to push.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS          - The value was pushed onto the stack.\r
+\r
+  EFI_OUT_OF_RESOURCES - There is not enough system memory to grow the stack.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  //\r
+  // Check for a stack overflow condition\r
+  //\r
+  if (mDepexEvaluationStackPointer == mDepexEvaluationStackEnd) {\r
+    //\r
+    // Grow the stack\r
+    //\r
+    Status = GrowDepexStack ();\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Push the item onto the stack\r
+  //\r
+  *mDepexEvaluationStackPointer = Value;\r
+  mDepexEvaluationStackPointer++;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS \r
+PopBool (\r
+  OUT BOOLEAN  *Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Pop an element from the Boolean stack.\r
+\r
+Arguments:\r
+\r
+  Value - BOOLEAN to pop.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - The value was popped onto the stack.\r
+\r
+  EFI_ACCESS_DENIED - The pop operation underflowed the stack\r
+\r
+--*/\r
+{\r
+  //\r
+  // Check for a stack underflow condition\r
+  //\r
+  if (mDepexEvaluationStackPointer == mDepexEvaluationStack) {\r
+    return EFI_ACCESS_DENIED;\r
+  }\r
+\r
+  //\r
+  // Pop the item off the stack\r
+  //\r
+  mDepexEvaluationStackPointer--;\r
+  *Value = *mDepexEvaluationStackPointer;\r
+  return EFI_SUCCESS;  \r
+}\r
+\r
+\r
+EFI_STATUS\r
+CorePreProcessDepex (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *DriverEntry  \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Preprocess dependency expression and update DriverEntry to reflect the\r
+  state of  Before, After, and SOR dependencies. If DriverEntry->Before\r
+  or DriverEntry->After is set it will never be cleared. If SOR is set\r
+  it will be cleared by CoreSchedule(), and then the driver can be \r
+  dispatched.\r
+\r
+Arguments:\r
+\r
+  DriverEntry - DriverEntry element to update\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - It always works.\r
+\r
+--*/\r
+{\r
+  UINT8  *Iterator;\r
+    \r
+  Iterator = DriverEntry->Depex;\r
+  if (*Iterator == EFI_DEP_SOR) {\r
+    DriverEntry->Unrequested = TRUE;\r
+  } else {\r
+    DriverEntry->Dependent = TRUE;\r
+  }\r
+    \r
+  if (*Iterator == EFI_DEP_BEFORE) {\r
+    DriverEntry->Before = TRUE;\r
+  } else if (*Iterator == EFI_DEP_AFTER) {\r
+    DriverEntry->After = TRUE;\r
+  } \r
+\r
+  if (DriverEntry->Before || DriverEntry->After) {\r
+    CopyMem (&DriverEntry->BeforeAfterGuid, Iterator + 1, sizeof (EFI_GUID));\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+BOOLEAN\r
+CoreIsSchedulable (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *DriverEntry  \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  This is the POSTFIX version of the dependency evaluator.  This code does \r
+  not need to handle Before or After, as it is not valid to call this \r
+  routine in this case. The SOR is just ignored and is a nop in the grammer.\r
+\r
+  POSTFIX means all the math is done on top of the stack.\r
+\r
+Arguments:\r
+\r
+  DriverEntry - DriverEntry element to update\r
+  \r
+Returns:\r
+\r
+  TRUE - If driver is ready to run.\r
+\r
+  FALSE - If driver is not ready to run or some fatal error was found.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS  Status;\r
+  UINT8       *Iterator;\r
+  BOOLEAN     Operator;\r
+  BOOLEAN     Operator2;\r
+  EFI_GUID    DriverGuid;\r
+  VOID        *Interface;\r
+\r
+  if (DriverEntry->After || DriverEntry->Before) {\r
+    //\r
+    // If Before or After Depex skip as CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ()\r
+    // processes them.\r
+    //\r
+    return FALSE;\r
+  }\r
+\r
+  if (DriverEntry->Depex == NULL) {\r
+    //\r
+    // A NULL Depex means treat the driver like an EFI 1.0 thing.\r
+    //\r
+    Status = CoreAllEfiServicesAvailable ();\r
+    if (EFI_ERROR (Status)) {\r
+      return FALSE;\r
+    }\r
+    return TRUE;\r
+  }\r
+\r
+  //\r
+  // Clean out memory leaks in Depex Boolean stack. Leaks are only caused by\r
+  //  incorrectly formed DEPEX expressions\r
+  //\r
+  mDepexEvaluationStackPointer = mDepexEvaluationStack;\r
+\r
+\r
+  Iterator = DriverEntry->Depex;\r
+  \r
+  while (TRUE) {\r
+    //\r
+    // Check to see if we are attempting to fetch dependency expression instructions\r
+    // past the end of the dependency expression.\r
+    //\r
+    if (((UINTN)Iterator - (UINTN)DriverEntry->Depex) >= DriverEntry->DepexSize) {\r
+      return FALSE;\r
+    }\r
+\r
+    //\r
+    // Look at the opcode of the dependency expression instruction.\r
+    //\r
+    switch (*Iterator) {\r
+    case EFI_DEP_BEFORE:\r
+    case EFI_DEP_AFTER:\r
+      //\r
+      // For a well-formed Dependency Expression, the code should never get here.\r
+      // The BEFORE and AFTER are processed prior to this routine's invocation.\r
+      // If the code flow arrives at this point, there was a BEFORE or AFTER\r
+      // that were not the first opcodes.\r
+      //\r
+      ASSERT (FALSE);\r
+    case EFI_DEP_SOR:\r
+      //\r
+      // These opcodes can only appear once as the first opcode.  If it is found \r
+      // at any other location, then the dependency expression evaluates to FALSE\r
+      //\r
+      if (Iterator != DriverEntry->Depex) {\r
+        return FALSE;\r
+      }\r
+      //\r
+      // Otherwise, it is the first opcode and should be treated as a NOP.\r
+      //\r
+      break;\r
+\r
+    case EFI_DEP_PUSH:  \r
+      //\r
+      // Push operator is followed by a GUID. Test to see if the GUID protocol\r
+      // is installed and push the boolean result on the stack.\r
+      //\r
+      CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID));\r
+\r
+      Status = CoreLocateProtocol (&DriverGuid, NULL, &Interface);\r
+\r
+      if (EFI_ERROR (Status)) {\r
+        Status = PushBool (FALSE);\r
+      } else {\r
+        *Iterator = EFI_DEP_REPLACE_TRUE;\r
+        Status = PushBool (TRUE);\r
+      }\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Iterator += sizeof (EFI_GUID);\r
+      break;\r
+\r
+    case EFI_DEP_AND:    \r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PopBool (&Operator2);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(Operator && Operator2));\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_OR:     \r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PopBool (&Operator2);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(Operator || Operator2));\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_NOT:    \r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(!Operator));\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_TRUE:   \r
+      Status = PushBool (TRUE);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_FALSE: \r
+      Status = PushBool (FALSE);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_END:    \r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+      return Operator;\r
+\r
+    case EFI_DEP_REPLACE_TRUE:\r
+      Status = PushBool (TRUE);\r
+      if (EFI_ERROR (Status)) {\r
+        return FALSE;\r
+      }\r
+\r
+      Iterator += sizeof (EFI_GUID);\r
+      break;\r
+\r
+    default:      \r
+      goto Done;\r
+    }\r
+    \r
+    //\r
+    // Skip over the Dependency Op Code we just processed in the switch.\r
+    // The math is done out of order, but it should not matter. That is\r
+    // we may add in the sizeof (EFI_GUID) before we account for the OP Code.\r
+    // This is not an issue, since we just need the correct end result. You\r
+    // need to be careful using Iterator in the loop as it's intermediate value\r
+    // may be strange.\r
+    //\r
+    Iterator++;\r
+  }\r
+\r
+Done:\r
+  return FALSE;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.h b/MdeModulePkg/Core/Dxe/DxeMain.h
new file mode 100644 (file)
index 0000000..fb7c82f
--- /dev/null
@@ -0,0 +1,2847 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  DxeMain.h\r
+\r
+Abstract:\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#ifndef _DXE_MAIN_H_\r
+#define _DXE_MAIN_H_\r
+\r
+\r
+//\r
+// The package level header files this module uses\r
+//\r
+#include <PiDxe.h>\r
+#include <FrameworkPei.h>\r
+//\r
+// The protocols, PPI and GUID defintions for this module\r
+//\r
+#include <Protocol/LoadedImage.h>\r
+#include <Protocol/GuidedSectionExtraction.h>\r
+#include <Protocol/SectionExtraction.h>\r
+#include <Guid/DebugImageInfoTable.h>\r
+#include <Protocol/DevicePath.h>\r
+#include <Protocol/Runtime.h>\r
+#include <Protocol/LoadFile.h>\r
+#include <Protocol/DriverBinding.h>\r
+#include <Protocol/VariableWrite.h>\r
+#include <Protocol/PlatformDriverOverride.h>\r
+#include <Protocol/Variable.h>\r
+#include <Guid/MemoryTypeInformation.h>\r
+#include <Guid/FirmwareFileSystem2.h>\r
+#include <Guid/HobList.h>\r
+#include <Protocol/Timer.h>\r
+#include <Protocol/SimpleFileSystem.h>\r
+#include <Protocol/Bds.h>\r
+#include <Guid/FileInfo.h>\r
+#include <Protocol/RealTimeClock.h>\r
+#include <Guid/Apriori.h>\r
+#include <Protocol/WatchdogTimer.h>\r
+#include <Protocol/FirmwareVolume.h>\r
+#include <Protocol/MonotonicCounter.h>\r
+#include <Guid/DxeServices.h>\r
+#include <Guid/MemoryAllocationHob.h>\r
+#include <Protocol/StatusCode.h>\r
+#include <Protocol/CustomizedDecompress.h>\r
+#include <Protocol/Decompress.h>\r
+#include <Protocol/LoadPe32Image.h>\r
+#include <Protocol/FirmwareVolumeDispatch.h>\r
+#include <Protocol/Security.h>\r
+#include <Protocol/Ebc.h>\r
+#include <Guid/EventLegacyBios.h>\r
+#include <Protocol/Reset.h>\r
+#include <Protocol/EdkDecompress.h>\r
+#include <Protocol/Cpu.h>\r
+#include <Guid/EventGroup.h>\r
+#include <Protocol/Metronome.h>\r
+#include <Protocol/FirmwareVolumeBlock.h>\r
+#include <Protocol/Capsule.h>\r
+#include <Protocol/BusSpecificDriverOverride.h>\r
+#include <Protocol/Performance.h>\r
+#include <Guid/StatusCodeDataTypeId.h>\r
+//\r
+// The Library classes this module consumes\r
+//\r
+#include <Library/DxeCoreEntryPoint.h>\r
+#include <Library/DebugLib.h>\r
+#include <Library/UefiLib.h>\r
+#include <Library/BaseLib.h>\r
+#include <Library/HobLib.h>\r
+#include <Library/PerformanceLib.h>\r
+#include <Library/UefiDecompressLib.h>\r
+#include <Library/CustomDecompressLib.h>\r
+#include <Library/PeCoffLoaderLib.h>\r
+#include <Library/CacheMaintenanceLib.h>\r
+#include <Library/BaseMemoryLib.h>\r
+\r
+#include "DebugImageInfo.h"\r
+#include "Library.h"\r
+#include "FwVolBlock.h"\r
+#include "FwVolDriver.h"\r
+#include "gcd.h"\r
+#include "imem.h"\r
+#include "Image.h"\r
+#include "Exec.h"\r
+#include "hand.h"\r
+\r
+\r
+//\r
+// Modifier for EFI DXE Services\r
+//\r
+#define EFI_DXESERVICE\r
+\r
+//\r
+// attributes for reserved memory before it is promoted to system memory\r
+//\r
+#define EFI_MEMORY_PRESENT      0x0100000000000000ULL\r
+#define EFI_MEMORY_INITIALIZED  0x0200000000000000ULL\r
+#define EFI_MEMORY_TESTED       0x0400000000000000ULL\r
+\r
+//\r
+// range for memory mapped port I/O on IPF\r
+//\r
+#define EFI_MEMORY_PORT_IO  0x4000000000000000ULL\r
+\r
+\r
+///\r
+/// EFI_DEP_REPLACE_TRUE - Used to dynamically patch the dependecy expression\r
+///                        to save time.  A EFI_DEP_PUSH is evauated one an\r
+///                        replaced with EFI_DEP_REPLACE_TRUE\r
+///\r
+#define EFI_DEP_REPLACE_TRUE  0xff\r
+\r
+///\r
+/// Define the initial size of the dependency expression evaluation stack\r
+///\r
+#define DEPEX_STACK_SIZE_INCREMENT  0x1000\r
+\r
+typedef struct {\r
+  EFI_GUID                    *ProtocolGuid;\r
+  VOID                        **Protocol;\r
+  EFI_EVENT                   Event;\r
+  VOID                        *Registration;\r
+  BOOLEAN                     Present;\r
+} ARCHITECTURAL_PROTOCOL_ENTRY;\r
+\r
+\r
+//\r
+// DXE Dispatcher Data structures\r
+//\r
+\r
+#define KNOWN_HANDLE_SIGNATURE  EFI_SIGNATURE_32('k','n','o','w')\r
+typedef struct {\r
+  UINTN           Signature;\r
+  LIST_ENTRY      Link;         // mFvHandleList           \r
+  EFI_HANDLE      Handle;\r
+} KNOWN_HANDLE;\r
+\r
+\r
+#define EFI_CORE_DRIVER_ENTRY_SIGNATURE EFI_SIGNATURE_32('d','r','v','r')\r
+typedef struct {\r
+  UINTN                           Signature;\r
+  LIST_ENTRY                      Link;             // mDriverList\r
+\r
+  LIST_ENTRY                      ScheduledLink;    // mScheduledQueue\r
+\r
+  EFI_HANDLE                      FvHandle;\r
+  EFI_GUID                        FileName;\r
+  EFI_DEVICE_PATH_PROTOCOL        *FvFileDevicePath;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL    *Fv;\r
+\r
+  VOID                            *Depex;\r
+  UINTN                           DepexSize;\r
+\r
+  BOOLEAN                         Before;\r
+  BOOLEAN                         After;\r
+  EFI_GUID                        BeforeAfterGuid;\r
+\r
+  BOOLEAN                         Dependent;\r
+  BOOLEAN                         Unrequested;\r
+  BOOLEAN                         Scheduled;\r
+  BOOLEAN                         Untrusted;\r
+  BOOLEAN                         Initialized;\r
+  BOOLEAN                         DepexProtocolError;\r
+\r
+  EFI_HANDLE                      ImageHandle;\r
+\r
+} EFI_CORE_DRIVER_ENTRY;\r
+\r
+//\r
+//The data structure of GCD memory map entry\r
+//\r
+#define EFI_GCD_MAP_SIGNATURE  EFI_SIGNATURE_32('g','c','d','m')\r
+typedef struct {\r
+  UINTN                 Signature;\r
+  LIST_ENTRY            Link;\r
+  EFI_PHYSICAL_ADDRESS  BaseAddress;\r
+  UINT64                EndAddress;\r
+  UINT64                Capabilities;\r
+  UINT64                Attributes;\r
+  EFI_GCD_MEMORY_TYPE   GcdMemoryType;\r
+  EFI_GCD_IO_TYPE       GcdIoType;\r
+  EFI_HANDLE            ImageHandle;\r
+  EFI_HANDLE            DeviceHandle;\r
+} EFI_GCD_MAP_ENTRY;\r
+\r
+//\r
+// DXE Core Global Variables\r
+//\r
+extern EFI_SYSTEM_TABLE                         *gDxeCoreST;\r
+extern EFI_BOOT_SERVICES                        *gDxeCoreBS;\r
+extern EFI_RUNTIME_SERVICES                     *gDxeCoreRT;\r
+extern EFI_DXE_SERVICES                         *gDxeCoreDS;\r
+extern EFI_HANDLE                               gDxeCoreImageHandle;\r
+\r
+extern EFI_DECOMPRESS_PROTOCOL                  gEfiDecompress;\r
+extern EFI_PEI_PE_COFF_LOADER_PROTOCOL          *gEfiPeiPeCoffLoader;\r
+\r
+extern EFI_RUNTIME_ARCH_PROTOCOL                *gRuntime;\r
+extern EFI_CPU_ARCH_PROTOCOL                    *gCpu;\r
+extern EFI_WATCHDOG_TIMER_ARCH_PROTOCOL         *gWatchdogTimer;\r
+extern EFI_METRONOME_ARCH_PROTOCOL              *gMetronome;\r
+extern EFI_TIMER_ARCH_PROTOCOL                  *gTimer;\r
+extern EFI_SECURITY_ARCH_PROTOCOL               *gSecurity;\r
+extern EFI_BDS_ARCH_PROTOCOL                    *gBds;\r
+extern EFI_STATUS_CODE_PROTOCOL                 *gStatusCode;\r
+\r
+extern EFI_TPL                                  gEfiCurrentTpl;\r
+\r
+extern EFI_GUID                                 *gDxeCoreFileName;\r
+extern EFI_LOADED_IMAGE_PROTOCOL                *gDxeCoreLoadedImage;\r
+\r
+extern EFI_MEMORY_TYPE_INFORMATION              gMemoryTypeInformation[EfiMaxMemoryType + 1];\r
+\r
+extern BOOLEAN                                  gDispatcherRunning;\r
+extern EFI_RUNTIME_ARCH_PROTOCOL                gRuntimeTemplate;\r
+\r
+//\r
+// Service Initialization Functions\r
+//\r
+\r
+\r
+VOID\r
+CoreInitializePool (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called to initialize the pool.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreAddMemoryDescriptor (\r
+  IN EFI_MEMORY_TYPE       Type,\r
+  IN EFI_PHYSICAL_ADDRESS  Start,\r
+  IN UINT64                NumberOfPages,\r
+  IN UINT64                Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called to initialize the memory map and add descriptors to\r
+  the current descriptor list.\r
+\r
+       The first descriptor that is added must be general usable\r
+  memory as the addition allocates heap.\r
+\r
+Arguments:\r
+\r
+  Type          - The type of memory to add\r
+\r
+  Start         - The starting address in the memory range\r
+                  Must be page aligned\r
+\r
+  NumberOfPages - The number of pages in the range\r
+\r
+  Attribute     - Attributes of the memory to add\r
+\r
+Returns:\r
+\r
+  None.  The range is added to the memory map\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreReleaseGcdMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Release memory lock on mGcdMemorySpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreAcquireGcdMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Acquire memory lock on mGcdMemorySpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreInitializeMemoryServices (\r
+  IN VOID                  **HobStart,\r
+  IN EFI_PHYSICAL_ADDRESS  *MemoryBaseAddress,\r
+  IN UINT64                *MemoryLength\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  External function. Initializes the GCD and memory services based on the memory \r
+  descriptor HOBs.  This function is responsible for priming the GCD map and the\r
+  memory map, so memory allocations and resource allocations can be made.  The first\r
+  part of this function can not depend on any memory services until at least one\r
+  memory descriptor is provided to the memory services.  Then the memory services\r
+  can be used to intialize the GCD map.\r
+\r
+Arguments:\r
+\r
+  HobStart - The start address of the HOB.\r
+  \r
+  MemoryBaseAddress   - Start address of memory region found to init DXE core.\r
+  \r
+  MemoryLength        - Length of memory region found to init DXE core.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS         - Memory services successfully initialized.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+CoreInitializeGcdServices (\r
+  IN VOID                  **HobStart,\r
+  IN EFI_PHYSICAL_ADDRESS  MemoryBaseAddress,\r
+  IN UINT64                MemoryLength\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  External function. Initializes the GCD and memory services based on the memory \r
+  descriptor HOBs.  This function is responsible for priming the GCD map and the\r
+  memory map, so memory allocations and resource allocations can be made.  The first\r
+  part of this function can not depend on any memory services until at least one\r
+  memory descriptor is provided to the memory services.  Then the memory services\r
+  can be used to intialize the GCD map.\r
+\r
+Arguments:\r
+\r
+  HobStart - The start address of the HOB\r
+  \r
+  MemoryBaseAddress   - Start address of memory region found to init DXE core.\r
+  \r
+  MemoryLength        - Length of memory region found to init DXE core.\r
+\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS         - GCD services successfully initialized.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreInitializeEventServices (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initializes "event" support and populates parts of the System and Runtime Table.\r
+\r
+Arguments:\r
+\r
+  None\r
+    \r
+Returns:\r
+\r
+  EFI_SUCCESS - Always return success\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreInitializeImageServices (\r
+  IN  VOID *HobStart\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add the Image Services to EFI Boot Services Table and install the protocol\r
+  interfaces for this image.\r
+\r
+Arguments:\r
+\r
+  HobStart        - The HOB to initialize\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreNotifyOnArchProtocolInstallation (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Creates an event that is fired everytime a Protocol of a specific type is installed\r
+\r
+Arguments:\r
+  NONE\r
+\r
+Returns:\r
+  NONE\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAllEfiServicesAvailable (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Return TRUE if all AP services are availible.\r
+\r
+Arguments:\r
+  NONE\r
+\r
+Returns:\r
+  EFI_SUCCESS   - All AP services are available\r
+  EFI_NOT_FOUND - At least one AP service is not available \r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CalculateEfiHdrCrc (\r
+  IN  OUT EFI_TABLE_HEADER    *Hdr\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Calcualte the 32-bit CRC in a EFI table using the service provided by the\r
+  gRuntime service.\r
+\r
+Arguments:\r
+\r
+  Hdr  - Pointer to an EFI standard header\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+EFIAPI\r
+CoreTimerTick (\r
+  IN UINT64     Duration\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called by the platform code to process a tick.\r
+\r
+Arguments:\r
+\r
+  Duration    - The number of 100ns elasped since the last call to TimerTick\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreInitializeDispatcher (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initialize the dispatcher. Initialize the notification function that runs when\r
+  a FV protocol is added to the system.\r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  NONE \r
+\r
+--*/\r
+;\r
+\r
+BOOLEAN\r
+CoreIsSchedulable (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *DriverEntry  \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  This is the POSTFIX version of the dependency evaluator.  This code does \r
+  not need to handle Before or After, as it is not valid to call this \r
+  routine in this case. The SOR is just ignored and is a nop in the grammer.\r
+\r
+  POSTFIX means all the math is done on top of the stack.\r
+\r
+Arguments:\r
+\r
+  DriverEntry - DriverEntry element to update\r
+  \r
+Returns:\r
+\r
+  TRUE - If driver is ready to run.\r
+\r
+  FALSE - If driver is not ready to run or some fatal error was found.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CorePreProcessDepex (\r
+  IN  EFI_CORE_DRIVER_ENTRY   *DriverEntry  \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Preprocess dependency expression and update DriverEntry to reflect the\r
+  state of  Before, After, and SOR dependencies. If DriverEntry->Before\r
+  or DriverEntry->After is set it will never be cleared. If SOR is set\r
+  it will be cleared by CoreSchedule(), and then the driver can be \r
+  dispatched.\r
+\r
+Arguments:\r
+\r
+  DriverEntry - DriverEntry element to update\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - It always works.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreExitBootServices (\r
+  IN EFI_HANDLE   ImageHandle,\r
+  IN UINTN        MapKey\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  EFI 1.0 API to terminate Boot Services\r
+\r
+Arguments:\r
+\r
+  ImageHandle - Handle that represents the identity of the calling image\r
+\r
+  MapKey      -Key to the latest memory map.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - Boot Services terminated\r
+  EFI_INVALID_PARAMETER - MapKey is incorrect.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreTerminateMemoryMap (\r
+  IN UINTN        MapKey\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Make sure the memory map is following all the construction rules, \r
+  it is the last time to check memory map error before exit boot services.\r
+\r
+Arguments:\r
+\r
+  MapKey        - Memory map key\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Memory map not consistent with construction rules.\r
+  \r
+  EFI_SUCCESS                 - Valid memory map.\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreNotifySignalList (\r
+  IN EFI_GUID     *EventGroup\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Signals all events on the requested list\r
+\r
+Arguments:\r
+\r
+  SignalType      - The list to signal\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallConfigurationTable (\r
+  IN EFI_GUID         *Guid,\r
+  IN VOID             *Table\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Boot Service called to add, modify, or remove a system configuration table from \r
+  the EFI System Table.\r
+\r
+Arguments:\r
+\r
+  Guid:   Pointer to the GUID for the entry to add, update, or remove\r
+  Table:  Pointer to the configuration table for the entry to add, update, or\r
+          remove, may be NULL.\r
+\r
+Returns:\r
+  \r
+  EFI_SUCCESS               Guid, Table pair added, updated, or removed.\r
+  EFI_INVALID_PARAMETER     Input GUID not valid.\r
+  EFI_NOT_FOUND             Attempted to delete non-existant entry\r
+  EFI_OUT_OF_RESOURCES      Not enough memory available\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_TPL\r
+EFIAPI\r
+CoreRaiseTpl (\r
+  IN EFI_TPL  NewTpl\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Raise the task priority level to the new level.\r
+  High level is implemented by disabling processor interrupts.\r
+\r
+Arguments:\r
+\r
+  NewTpl  - New task priority level\r
+    \r
+Returns:\r
+\r
+  The previous task priority level\r
+\r
+--*/\r
+;\r
+\r
+\r
+VOID\r
+EFIAPI\r
+CoreRestoreTpl (\r
+  IN EFI_TPL  NewTpl\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Lowers the task priority to the previous value.   If the new \r
+  priority unmasks events at a higher priority, they are dispatched.\r
+\r
+Arguments:\r
+\r
+  NewTpl  - New, lower, task priority\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreStall (\r
+  IN UINTN            Microseconds\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Introduces a fine-grained stall.\r
+\r
+Arguments:\r
+\r
+  Microseconds      The number of microseconds to stall execution\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - Execution was stalled for at least the requested amount\r
+                           of microseconds.\r
+\r
+  EFI_NOT_AVAILABLE_YET  - gMetronome is not available yet\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSetWatchdogTimer (\r
+  IN UINTN            Timeout,\r
+  IN UINT64           WatchdogCode,\r
+  IN UINTN            DataSize,\r
+  IN CHAR16           *WatchdogData   OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Sets the system's watchdog timer.\r
+\r
+Arguments:\r
+\r
+  Timeout         The number of seconds.  Zero disables the timer.\r
+\r
+  ///////following  three parameters are left for platform specific using  \r
+  \r
+  WatchdogCode    The numberic code to log.  0x0 to 0xffff are firmware\r
+  DataSize        Size of the optional data\r
+  WatchdogData    Optional Null terminated unicode string followed by binary \r
+                  data.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS               Timeout has been set\r
+  EFI_NOT_AVAILABLE_YET     WatchdogTimer is not available yet \r
+  EFI_UNSUPPORTED           System does not have a timer (currently not used)\r
+  EFI_DEVICE_ERROR          Could not complete due to hardware error\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallProtocolInterface (\r
+  IN OUT EFI_HANDLE     *UserHandle,\r
+  IN EFI_GUID           *Protocol,\r
+  IN EFI_INTERFACE_TYPE InterfaceType,\r
+  IN VOID               *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Wrapper function to CoreInstallProtocolInterfaceNotify.  This is the public API which\r
+  Calls the private one which contains a BOOLEAN parameter for notifications\r
+\r
+Arguments:\r
+\r
+  UserHandle     - The handle to install the protocol handler on,\r
+                    or NULL if a new handle is to be allocated\r
+\r
+  Protocol       - The protocol to add to the handle\r
+\r
+  InterfaceType  - Indicates whether Interface is supplied in native form.\r
+\r
+  Interface      - The interface for the protocol being added\r
+\r
+Returns:\r
+\r
+  Status code    \r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreInstallProtocolInterfaceNotify (\r
+  IN OUT EFI_HANDLE     *UserHandle,\r
+  IN EFI_GUID           *Protocol,\r
+  IN EFI_INTERFACE_TYPE InterfaceType,\r
+  IN VOID               *Interface,\r
+  IN BOOLEAN            Notify\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Installs a protocol interface into the boot services environment.\r
+\r
+Arguments:\r
+\r
+  UserHandle     - The handle to install the protocol handler on,\r
+                   or NULL if a new handle is to be allocated\r
+\r
+  Protocol       - The protocol to add to the handle\r
+\r
+  InterfaceType  - Indicates whether Interface is supplied in native form.\r
+\r
+  Interface      - The interface for the protocol being added\r
+  \r
+  Notify         - Whether to notify the notification list for this protocol \r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES       - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Protocol interface successfully installed\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallMultipleProtocolInterfaces (\r
+  IN OUT EFI_HANDLE           *Handle,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Installs a list of protocol interface into the boot services environment.\r
+  This function calls InstallProtocolInterface() in a loop. If any error\r
+  occures all the protocols added by this function are removed. This is \r
+  basically a lib function to save space.\r
+\r
+Arguments:\r
+\r
+  Handle      - The handle to install the protocol handlers on,\r
+                or NULL if a new handle is to be allocated\r
+  ...         - EFI_GUID followed by protocol instance. A NULL terminates the \r
+                list. The pairs are the arguments to InstallProtocolInterface().\r
+                All the protocols are added to Handle.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Handle is NULL.\r
+  \r
+  EFI_SUCCESS                 - Protocol interfaces successfully installed.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUninstallMultipleProtocolInterfaces (\r
+  IN EFI_HANDLE           Handle,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Uninstalls a list of protocol interface in the boot services environment. \r
+  This function calls UnisatllProtocolInterface() in a loop. This is \r
+  basically a lib function to save space.\r
+\r
+Arguments:\r
+\r
+  Handle      - The handle to uninstall the protocol\r
+\r
+  ...         - EFI_GUID followed by protocol instance. A NULL terminates the \r
+                list. The pairs are the arguments to UninstallProtocolInterface().\r
+                All the protocols are added to Handle.\r
+\r
+Returns:\r
+\r
+  Status code    \r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreReinstallProtocolInterface (\r
+  IN EFI_HANDLE     UserHandle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *OldInterface,\r
+  IN VOID           *NewInterface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Reinstall a protocol interface on a device handle.  The OldInterface for Protocol is replaced by the NewInterface.\r
+\r
+Arguments:\r
+\r
+  UserHandle    - Handle on which the interface is to be reinstalled\r
+  Protocol      - The numeric ID of the interface\r
+  OldInterface  - A pointer to the old interface\r
+  NewInterface  - A pointer to the new interface \r
+\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+  On EFI_SUCCESS            The protocol interface was installed\r
+  On EFI_NOT_FOUND          The OldInterface on the handle was not found\r
+  On EFI_INVALID_PARAMETER  One of the parameters has an invalid value\r
+  \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUninstallProtocolInterface (\r
+  IN EFI_HANDLE       UserHandle,\r
+  IN EFI_GUID         *Protocol,\r
+  IN VOID             *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Uninstalls all instances of a protocol:interfacer from a handle. \r
+  If the last protocol interface is remove from the handle, the \r
+  handle is freed.\r
+\r
+Arguments:\r
+\r
+  UserHandle      - The handle to remove the protocol handler from\r
+\r
+  Protocol        - The protocol, of protocol:interface, to remove\r
+\r
+  Interface       - The interface, of protocol:interface, to remove\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Protocol is NULL.\r
+  \r
+  EFI_SUCCESS                 - Protocol interface successfully uninstalled.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreHandleProtocol (\r
+  IN  EFI_HANDLE       UserHandle,\r
+  IN  EFI_GUID         *Protocol,\r
+  OUT VOID             **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Queries a handle to determine if it supports a specified protocol.\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle being queried.\r
+\r
+  Protocol    - The published unique identifier of the protocol.\r
+\r
+  Interface   - Supplies the address where a pointer to the corresponding Protocol\r
+               Interface is returned.\r
+\r
+Returns:\r
+\r
+  The requested protocol interface for the handle\r
+  \r
+--*/  \r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreOpenProtocol (\r
+  IN  EFI_HANDLE                UserHandle,\r
+  IN  EFI_GUID                  *Protocol,\r
+  OUT VOID                      **Interface OPTIONAL,\r
+  IN  EFI_HANDLE                ImageHandle,\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  UINT32                    Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the installed protocol handler for the handle, and\r
+  invokes it to obtain the protocol interface. Usage information\r
+  is registered in the protocol data base.\r
+\r
+Arguments:\r
+\r
+  UserHandle        - The handle to obtain the protocol interface on\r
+\r
+  Protocol          - The ID of the protocol \r
+\r
+  Interface         - The location to return the protocol interface\r
+\r
+  ImageHandle       - The handle of the Image that is opening the protocol interface\r
+                    specified by Protocol and Interface.\r
+  \r
+  ControllerHandle  - The controller handle that is requiring this interface.\r
+\r
+  Attributes     - The open mode of the protocol interface specified by Handle\r
+                    and Protocol.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Protocol is NULL.\r
+  \r
+  EFI_SUCCESS                 - Get the protocol interface.\r
+  \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreOpenProtocolInformation (\r
+  IN  EFI_HANDLE                          UserHandle,\r
+  IN  EFI_GUID                            *Protocol,\r
+  OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer,\r
+  OUT UINTN                               *EntryCount\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return information about Opened protocols in the system\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle to close the protocol interface on\r
+\r
+  Protocol    - The ID of the protocol \r
+\r
+  EntryBuffer - A pointer to a buffer of open protocol information in the form of\r
+                EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures.\r
+\r
+  EntryCount  - Number of EntryBuffer entries\r
+\r
+Returns:\r
+\r
+  \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCloseProtocol (\r
+  IN  EFI_HANDLE                UserHandle,\r
+  IN  EFI_GUID                  *Protocol,\r
+  IN  EFI_HANDLE                ImageHandle,\r
+  IN  EFI_HANDLE                ControllerHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Close Protocol\r
+\r
+Arguments:\r
+\r
+  UserHandle       - The handle to close the protocol interface on\r
+\r
+  Protocol         - The ID of the protocol \r
+\r
+  ImageHandle      - The user of the protocol to close\r
+\r
+  ControllerHandle - The user of the protocol to close\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Protocol is NULL.\r
+    \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreProtocolsPerHandle (\r
+  IN  EFI_HANDLE       UserHandle,\r
+  OUT EFI_GUID         ***ProtocolBuffer,\r
+  OUT UINTN            *ProtocolBufferCount\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated\r
+ from pool.\r
+\r
+Arguments:\r
+\r
+  UserHandle           - The handle from which to retrieve the list of protocol interface\r
+                          GUIDs.\r
+\r
+  ProtocolBuffer       - A pointer to the list of protocol interface GUID pointers that are\r
+                          installed on Handle.\r
+\r
+  ProtocolBufferCount  - A pointer to the number of GUID pointers present in\r
+                          ProtocolBuffer.\r
+\r
+Returns:\r
+  EFI_SUCCESS   -  The list of protocol interface GUIDs installed on Handle was returned in\r
+                   ProtocolBuffer. The number of protocol interface GUIDs was\r
+                   returned in ProtocolBufferCount.\r
+  EFI_INVALID_PARAMETER   -  Handle is NULL.\r
+  EFI_INVALID_PARAMETER   -  Handle is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER   -  ProtocolBuffer is NULL.\r
+  EFI_INVALID_PARAMETER   -  ProtocolBufferCount is NULL.\r
+  EFI_OUT_OF_RESOURCES    -  There is not enough pool memory to store the results.\r
+  \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreRegisterProtocolNotify (\r
+  IN  EFI_GUID       *Protocol,\r
+  IN  EFI_EVENT      Event,\r
+  OUT VOID           **Registration\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add a new protocol notification record for the request protocol.\r
+\r
+Arguments:\r
+\r
+  Protocol      - The requested protocol to add the notify registration\r
+\r
+  Event         - The event to signal \r
+\r
+  Registration  - Returns the registration record\r
+\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+\r
+  EFI_SUCCESS                 - Successfully returned the registration record that has been added\r
+  \r
+--*/\r
+;\r
+  \r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateHandle (\r
+  IN     EFI_LOCATE_SEARCH_TYPE         SearchType,\r
+  IN     EFI_GUID                       *Protocol OPTIONAL,\r
+  IN     VOID                           *SearchKey OPTIONAL,\r
+  IN OUT UINTN                          *BufferSize,\r
+  OUT    EFI_HANDLE                     *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the requested handle(s) and returns them in Buffer.\r
+\r
+Arguments:\r
+\r
+  SearchType  - The type of search to perform to locate the handles\r
+\r
+  Protocol    - The protocol to search for\r
+  \r
+  SearchKey   - Dependant on SearchType\r
+\r
+  BufferSize  - On input the size of Buffer.  On output the \r
+                size of data returned.  \r
+\r
+  Buffer      - The buffer to return the results in\r
+\r
+\r
+Returns:\r
+\r
+  EFI_BUFFER_TOO_SMALL      - Buffer too small, required buffer size is returned in BufferSize.\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_SUCCESS               - Successfully found the requested handle(s) and returns them in Buffer.\r
+  \r
+--*/\r
+;\r
+  \r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateDevicePath (\r
+  IN     EFI_GUID                       *Protocol,\r
+  IN OUT EFI_DEVICE_PATH_PROTOCOL       **FilePath,\r
+  OUT    EFI_HANDLE                     *Device\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the handle to a device on the device path that supports the specified protocol.\r
+\r
+Arguments:\r
+\r
+  Protocol    - The protocol to search for.\r
+  FilePath    - On input, a pointer to a pointer to the device path. On output, the device\r
+                  path pointer is modified to point to the remaining part of the devicepath.\r
+  Device      - A pointer to the returned device handle.              \r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The resulting handle was returned.\r
+  EFI_NOT_FOUND         - No handles matched the search.\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value.\r
+\r
+--*/\r
+;\r
+\r
\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateHandleBuffer (\r
+  IN     EFI_LOCATE_SEARCH_TYPE         SearchType,\r
+  IN     EFI_GUID                       *Protocol OPTIONAL,\r
+  IN     VOID                           *SearchKey OPTIONAL,\r
+  IN OUT UINTN                          *NumberHandles,\r
+  OUT    EFI_HANDLE                     **Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Function returns an array of handles that support the requested protocol \r
+  in a buffer allocated from pool. This is a version of CoreLocateHandle()\r
+  that allocates a buffer for the caller.\r
+\r
+Arguments:\r
+\r
+  SearchType           - Specifies which handle(s) are to be returned.\r
+  Protocol             - Provides the protocol to search by.   \r
+                         This parameter is only valid for SearchType ByProtocol.\r
+  SearchKey            - Supplies the search key depending on the SearchType.\r
+  NumberHandles      - The number of handles returned in Buffer.\r
+  Buffer               - A pointer to the buffer to return the requested array of \r
+                         handles that support Protocol.\r
+\r
+Returns:\r
+  \r
+  EFI_SUCCESS             - The result array of handles was returned.\r
+  EFI_NOT_FOUND           - No handles match the search. \r
+  EFI_OUT_OF_RESOURCES    - There is not enough pool memory to store the matching results.\r
+  EFI_INVALID_PARAMETER   - Invalid parameter\r
+\r
+--*/\r
+;\r
+\r
\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateProtocol (\r
+  IN    EFI_GUID  *Protocol,\r
+  IN    VOID      *Registration OPTIONAL,\r
+  OUT   VOID      **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return the first Protocol Interface that matches the Protocol GUID. If\r
+  Registration is pasased in return a Protocol Instance that was just add\r
+  to the system. If Retistration is NULL return the first Protocol Interface\r
+  you find.\r
+\r
+Arguments:\r
+\r
+  Protocol     - The protocol to search for\r
+  \r
+  Registration - Optional Registration Key returned from RegisterProtocolNotify() \r
+\r
+  Interface    - Return the Protocol interface (instance).\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS                 - If a valid Interface is returned\r
+  \r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+  \r
+  EFI_NOT_FOUND               - Protocol interface not found\r
+\r
+--*/\r
+;\r
+\r
+UINT64\r
+CoreGetHandleDatabaseKey (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  return handle database key.\r
+\r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+  \r
+  Handle database key.\r
+  \r
+--*/\r
+;\r
+\r
+VOID\r
+CoreConnectHandlesByKey (\r
+  UINT64  Key\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Go connect any handles that were created or modified while a image executed.\r
+\r
+Arguments:\r
+\r
+  Key  -  The Key to show that the handle has been created/modified\r
+\r
+Returns:\r
+  \r
+  None\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreConnectController (\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  EFI_HANDLE                *DriverImageHandle    OPTIONAL,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL  *RemainingDevicePath  OPTIONAL,\r
+  IN  BOOLEAN                   Recursive\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Connects one or more drivers to a controller.\r
+\r
+Arguments:\r
+\r
+  ControllerHandle            - Handle of the controller to be connected.\r
+\r
+  DriverImageHandle           - DriverImageHandle A pointer to an ordered list of driver image handles.\r
+\r
+  RemainingDevicePath         - RemainingDevicePath A pointer to the device path that specifies a child of the\r
+                                controller specified by ControllerHandle.\r
+    \r
+  Recursive -                 - Whether the function would be called recursively or not.\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreDisconnectController (\r
+  IN EFI_HANDLE  ControllerHandle,\r
+  IN EFI_HANDLE  DriverImageHandle  OPTIONAL,\r
+  IN EFI_HANDLE  ChildHandle        OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Disonnects a controller from a driver\r
+\r
+Arguments:\r
+\r
+  ControllerHandle  - ControllerHandle The handle of the controller from which driver(s) \r
+                        are to be disconnected.\r
+  DriverImageHandle - DriverImageHandle The driver to disconnect from ControllerHandle.\r
+  ChildHandle       - ChildHandle The handle of the child to destroy.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           -  One or more drivers were disconnected from the controller.\r
+  EFI_SUCCESS           -  On entry, no drivers are managing ControllerHandle.\r
+  EFI_SUCCESS           -  DriverImageHandle is not NULL, and on entry DriverImageHandle is not managing ControllerHandle.\r
+  EFI_INVALID_PARAMETER -  ControllerHandle is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER -  DriverImageHandle is not NULL, and it is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER -  ChildHandle is not NULL, and it is not a valid EFI_HANDLE.\r
+  EFI_OUT_OF_RESOURCES  -  There are not enough resources available to disconnect any drivers from ControllerHandle.\r
+  EFI_DEVICE_ERROR      -  The controller could not be disconnected because of a device error.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreAllocatePages (\r
+  IN      EFI_ALLOCATE_TYPE       Type,\r
+  IN      EFI_MEMORY_TYPE         MemoryType,\r
+  IN      UINTN                   NumberOfPages,\r
+  IN OUT  EFI_PHYSICAL_ADDRESS    *Memory\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocates pages from the memory map.\r
+\r
+Arguments:\r
+\r
+  Type          - The type of allocation to perform\r
+\r
+  MemoryType    - The type of memory to turn the allocated pages into\r
+\r
+  NumberOfPages - The number of pages to allocate\r
+\r
+  Memory        - A pointer to receive the base allocated memory address\r
+\r
+Returns:\r
+\r
+  Status. On success, Memory is filled in with the base address allocated\r
+  \r
+  EFI_INVALID_PARAMETER     - Parameters violate checking rules defined in spec.\r
+  \r
+  EFI_NOT_FOUND             - Could not allocate pages match the requirement.\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough pages to allocate.\r
+  \r
+  EFI_SUCCESS               - Pages successfully allocated.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreFreePages (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees previous allocated pages.\r
+\r
+Arguments:\r
+\r
+  Memory        - Base address of memory being freed\r
+\r
+  NumberOfPages - The number of pages to free\r
+\r
+Returns:\r
+\r
+  EFI_NOT_FOUND       - Could not find the entry that covers the range\r
+  \r
+  EFI_INVALID_PARAMETER   - Address not aligned\r
+  \r
+  EFI_SUCCESS         -Pages successfully freed.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreGetMemoryMap (\r
+  IN OUT UINTN                       *MemoryMapSize,\r
+  IN OUT EFI_MEMORY_DESCRIPTOR       *Desc,\r
+  OUT    UINTN                       *MapKey,\r
+  OUT    UINTN                       *DescriptorSize,\r
+  OUT    UINT32                      *DescriptorVersion\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Returns the current memory map.\r
+\r
+Arguments:\r
+\r
+  MemoryMapSize     - On input the buffer size of MemoryMap allocated by caller\r
+                      On output the required buffer size to contain the memory map \r
+                      \r
+  Desc              - The buffer to return the current memory map\r
+\r
+  MapKey            - The address to return the current map key\r
+\r
+  DescriptorSize    - The size in bytes for an individual EFI_MEMORY_DESCRIPTOR\r
+\r
+  DescriptorVersion - The version number associated with the EFI_MEMORY_DESCRIPTOR\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           The current memory map was returned successfully\r
+\r
+  EFI_BUFFER_TOO_SMALL  The MemoryMap buffer was too small\r
+\r
+  EFI_INVALID_PARAMETER One of the parameters has an invalid value\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreAllocatePool (\r
+  IN   EFI_MEMORY_TYPE  PoolType,\r
+  IN   UINTN            Size,\r
+  OUT  VOID             **Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of a particular type.\r
+\r
+Arguments:\r
+\r
+  PoolType    - Type of pool to allocate\r
+\r
+  Size        - The amount of pool to allocate\r
+\r
+  Buffer      - The address to return a pointer to the allocated pool\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - PoolType not valid\r
+  \r
+  EFI_OUT_OF_RESOURCES      - Size exceeds max pool size or allocation failed.  \r
+  \r
+  EFI_SUCCESS               - Pool successfully allocated.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreFreePool (\r
+  IN VOID      *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees pool.\r
+\r
+Arguments:\r
+\r
+  Buffer      - The allocated pool entry to free\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER   - Buffer is not a valid value.\r
+  \r
+  EFI_SUCCESS             - Pool successfully freed.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLoadImage (\r
+  IN  BOOLEAN                    BootPolicy,\r
+  IN  EFI_HANDLE                 ParentImageHandle,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL   *FilePath,\r
+  IN  VOID                       *SourceBuffer   OPTIONAL,\r
+  IN  UINTN                      SourceSize,\r
+  OUT EFI_HANDLE                 *ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads an EFI image into memory and returns a handle to the image.\r
+\r
+Arguments:\r
+\r
+  BootPolicy          - If TRUE, indicates that the request originates from the boot manager,\r
+                        and that the boot manager is attempting to load FilePath as a boot selection.\r
+  ParentImageHandle   - The caller's image handle.\r
+  FilePath            - The specific file path from which the image is loaded.\r
+  SourceBuffer        - If not NULL, a pointer to the memory location containing a copy of \r
+                        the image to be loaded.\r
+  SourceSize          - The size in bytes of SourceBuffer.\r
+  ImageHandle         - Pointer to the returned image handle that is created when the image \r
+                        is successfully loaded.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - The image was loaded into memory.\r
+  EFI_NOT_FOUND          - The FilePath was not found.\r
+  EFI_INVALID_PARAMETER  - One of the parameters has an invalid value.\r
+  EFI_UNSUPPORTED        - The image type is not supported, or the device path cannot be \r
+                           parsed to locate the proper protocol for loading the file.\r
+  EFI_OUT_OF_RESOURCES   - Image was not loaded due to insufficient resources.\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUnloadImage (\r
+  IN EFI_HANDLE  ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unload the specified image.\r
+\r
+Arguments:\r
+\r
+  ImageHandle       - The specified image handle.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Image handle is NULL.\r
+  \r
+  EFI_UNSUPPORTED             - Attempt to unload an unsupported image.\r
+  \r
+  EFI_SUCCESS                 - Image successfully unloaded.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreStartImage (\r
+  IN  EFI_HANDLE  ImageHandle,\r
+  OUT UINTN       *ExitDataSize,\r
+  OUT CHAR16      **ExitData  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Transfer control to a loaded image's entry point.\r
+\r
+Arguments:\r
+\r
+  ImageHandle     - Handle of image to be started.\r
+  \r
+  ExitDataSize    - Pointer of the size to ExitData\r
+  \r
+  ExitData        - Pointer to a pointer to a data buffer that includes a Null-terminated\r
+                    Unicode string, optionally followed by additional binary data. The string\r
+                    is a description that the caller may use to further indicate the reason for\r
+                    the image's exit.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES       - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Successfully transfer control to the image's entry point.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreExit (\r
+  IN EFI_HANDLE  ImageHandle,\r
+  IN EFI_STATUS  Status,\r
+  IN UINTN       ExitDataSize,\r
+  IN CHAR16      *ExitData  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Terminates the currently loaded EFI image and returns control to boot services.\r
+\r
+Arguments:\r
+\r
+  ImageHandle       - Handle that identifies the image. This parameter is passed to the image \r
+                      on entry.\r
+  Status            - The image's exit code.\r
+  ExitDataSize      - The size, in bytes, of ExitData. Ignored if ExitStatus is\r
+                      EFI_SUCCESS.\r
+  ExitData          - Pointer to a data buffer that includes a Null-terminated Unicode string,\r
+                      optionally followed by additional binary data. The string is a \r
+                      description that the caller may use to further indicate the reason for\r
+                      the image's exit.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Image handle is NULL or it is not current image.\r
+  \r
+  EFI_SUCCESS               - Successfully terminates the currently loaded EFI image.\r
+  \r
+  EFI_ACCESS_DENIED         - Should never reach there.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCreateEvent (\r
+  IN  UINT32               Type,\r
+  IN  EFI_TPL              NotifyTpl,\r
+  IN  EFI_EVENT_NOTIFY     NotifyFunction,\r
+  IN  VOID                 *NotifyContext,\r
+  OUT EFI_EVENT            *pEvent\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Creates a general-purpose event structure\r
+\r
+Arguments:\r
+\r
+  Type                - The type of event to create and its mode and attributes\r
+  NotifyTpl           - The task priority level of event notifications\r
+  NotifyFunction      - Pointer to the event's notification function\r
+  NotifyContext       - Pointer to the notification function's context; corresponds to\r
+                        parameter "Context" in the notification function\r
+  pEvent              - Pointer to the newly created event if the call succeeds; undefined otherwise\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event structure was created\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value\r
+  EFI_OUT_OF_RESOURCES  - The event could not be allocated\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCreateEventEx (\r
+  IN UINT32                   Type,\r
+  IN EFI_TPL                  NotifyTpl,\r
+  IN EFI_EVENT_NOTIFY         NotifyFunction, OPTIONAL\r
+  IN CONST VOID               *NotifyContext, OPTIONAL\r
+  IN CONST EFI_GUID           *EventGroup,    OPTIONAL\r
+  OUT EFI_EVENT               *Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Creates a general-purpose event structure\r
+\r
+Arguments:\r
+  Type                - The type of event to create and its mode and attributes\r
+  NotifyTpl           - The task priority level of event notifications\r
+  NotifyFunction      - Pointer to the events notification function\r
+  NotifyContext       - Pointer to the notification functions context; corresponds to\r
+                        parameter "Context" in the notification function\r
+  EventGrout          - GUID for EventGroup if NULL act the same as gBS->CreateEvent().\r
+  Event               - Pointer to the newly created event if the call succeeds; undefined otherwise\r
+\r
+Returns:\r
+  EFI_SUCCESS           - The event structure was created\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value\r
+  EFI_OUT_OF_RESOURCES  - The event could not be allocated\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSetTimer (\r
+  IN EFI_EVENT            Event,\r
+  IN EFI_TIMER_DELAY      Type,\r
+  IN UINT64               TriggerTime\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Sets the type of timer and the trigger time for a timer event.\r
+\r
+Arguments:\r
+\r
+  UserEvent   - The timer event that is to be signaled at the specified time\r
+  Type        - The type of time that is specified in TriggerTime\r
+  TriggerTime - The number of 100ns units until the timer expires\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event has been set to be signaled at the requested time\r
+  EFI_INVALID_PARAMETER - Event or Type is not valid\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSignalEvent (\r
+  IN EFI_EVENT            Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Signals the event.  Queues the event to be notified if needed\r
+    \r
+Arguments:\r
+\r
+  Event - The event to signal\r
+    \r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER - Parameters are not valid.\r
+  \r
+  EFI_SUCCESS - The event was signaled.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreWaitForEvent (\r
+  IN  UINTN        NumberOfEvents,\r
+  IN  EFI_EVENT    *UserEvents,\r
+  OUT UINTN        *UserIndex\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Stops execution until an event is signaled.\r
+    \r
+Arguments:\r
+\r
+  NumberOfEvents  - The number of events in the UserEvents array\r
+  UserEvents      - An array of EFI_EVENT\r
+  UserIndex       - Pointer to the index of the event which satisfied the wait condition\r
+    \r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event indicated by Index was signaled.\r
+  EFI_INVALID_PARAMETER - The event indicated by Index has a notification function or \r
+                          Event was not a valid type\r
+  EFI_UNSUPPORTED       - The current TPL is not TPL_APPLICATION\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCloseEvent (\r
+  IN EFI_EVENT            Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Closes an event and frees the event structure.\r
+    \r
+Arguments:\r
+\r
+  UserEvent - Event to close\r
+    \r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER - Parameters are not valid.\r
+  \r
+  EFI_SUCCESS - The event has been closed\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCheckEvent (\r
+  IN EFI_EVENT            Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check the status of an event\r
+    \r
+Arguments:\r
+\r
+  UserEvent - The event to check\r
+    \r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event is in the signaled state\r
+  EFI_NOT_READY         - The event is not in the signaled state\r
+  EFI_INVALID_PARAMETER - Event is of type EVT_NOTIFY_SIGNAL\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAddMemorySpace (\r
+  IN EFI_GCD_MEMORY_TYPE   GcdMemoryType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Capabilities\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add a segment of memory space to GCD map and add all available pages in this segment \r
+  as memory descriptors.\r
+\r
+Arguments:\r
+    \r
+  GcdMemoryType     - Memory type of the segment.\r
+  \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+  Capabilities      - alterable attributes of the segment.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Merged this segment into GCD map.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAllocateMemorySpace (\r
+  IN     EFI_GCD_ALLOCATE_TYPE  GcdAllocateType,\r
+  IN     EFI_GCD_MEMORY_TYPE    GcdMemoryType,\r
+  IN     UINTN                  Alignment,\r
+  IN     UINT64                 Length,\r
+  IN OUT EFI_PHYSICAL_ADDRESS   *BaseAddress,\r
+  IN     EFI_HANDLE             ImageHandle,\r
+  IN     EFI_HANDLE             DeviceHandle OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate memory space on GCD map.\r
+\r
+Arguments:\r
+  \r
+  GcdAllocateType   - The type of allocate operation\r
+  \r
+  GcdMemoryType     - The desired memory type\r
+  \r
+  Alignment         - Align with 2^Alignment\r
+  \r
+  Length            - Length to allocate\r
+  \r
+  BaseAddress       - Base address to allocate\r
+  \r
+  ImageHandle       - The image handle consume the allocated space.\r
+  \r
+  DeviceHandle      - The device handle consume the allocated space.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter.\r
+  \r
+  EFI_NOT_FOUND               - No descriptor contains the desired space.\r
+  \r
+  EFI_SUCCESS                 - Memory space successfully allocated.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreFreeMemorySpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:Routine Description:\r
+\r
+  Free a segment of memory space in GCD map.\r
+\r
+Arguments:\r
+    \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Space successfully freed.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreRemoveMemorySpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:Routine Description:\r
+\r
+  Remove a segment of memory space in GCD map.\r
+\r
+Arguments:\r
+    \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully a segment of memory space.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetMemorySpaceDescriptor (\r
+  IN  EFI_PHYSICAL_ADDRESS             BaseAddress,\r
+  OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *Descriptor\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Search all entries in GCD map which contains specified segment and build it to a descriptor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Descriptor        - Specified length\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+  \r
+  EFI_SUCCESS                 - Successfully get memory space descriptor.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreSetMemorySpaceAttributes (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Set memory space with specified attributes.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Length            - Specified length\r
+  \r
+  Attributes        - Specified attributes\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully set attribute of a segment of memory space.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetMemorySpaceMap (\r
+  OUT UINTN                            *NumberOfDescriptors,\r
+  OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR  **MemorySpaceMap\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Transer all entries of GCD memory map into memory descriptors and pass to caller.\r
+\r
+Arguments:\r
+\r
+  NumberOfDescriptors       - Number of descriptors.\r
+  \r
+  MemorySpaceMap            - Descriptor array\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Successfully get memory space map.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAddIoSpace (\r
+  IN EFI_GCD_IO_TYPE       GcdIoType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add a segment of IO space to GCD map.\r
+\r
+Arguments:\r
+    \r
+  GcdIoType         - IO type of the segment.\r
+  \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Merged this segment into GCD map.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAllocateIoSpace (\r
+  IN     EFI_GCD_ALLOCATE_TYPE  GcdAllocateType,\r
+  IN     EFI_GCD_IO_TYPE        GcdIoType,\r
+  IN     UINTN                  Alignment,\r
+  IN     UINT64                 Length,\r
+  IN OUT EFI_PHYSICAL_ADDRESS   *BaseAddress,\r
+  IN     EFI_HANDLE             ImageHandle,\r
+  IN     EFI_HANDLE             DeviceHandle OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate IO space on GCD map.\r
+\r
+Arguments:\r
+  \r
+  GcdAllocateType   - The type of allocate operation\r
+  \r
+  GcdIoType         - The desired IO type\r
+  \r
+  Alignment         - Align with 2^Alignment\r
+  \r
+  Length            - Length to allocate\r
+  \r
+  BaseAddress       - Base address to allocate\r
+  \r
+  ImageHandle       - The image handle consume the allocated space.\r
+  \r
+  DeviceHandle      - The device handle consume the allocated space.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter.\r
+  \r
+  EFI_NOT_FOUND               - No descriptor contains the desired space.\r
+  \r
+  EFI_SUCCESS                 - IO space successfully allocated.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreFreeIoSpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:Routine Description:\r
+\r
+  Free a segment of IO space in GCD map.\r
+\r
+Arguments:\r
+    \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Space successfully freed.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreRemoveIoSpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:Routine Description:\r
+\r
+  Remove a segment of IO space in GCD map.\r
+\r
+Arguments:\r
+    \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully removed a segment of IO space.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetIoSpaceDescriptor (\r
+  IN  EFI_PHYSICAL_ADDRESS         BaseAddress,\r
+  OUT EFI_GCD_IO_SPACE_DESCRIPTOR  *Descriptor\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Search all entries in GCD map which contains specified segment and build it to a descriptor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Descriptor        - Specified length\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Descriptor is NULL.\r
+  \r
+  EFI_SUCCESS                 - Successfully get the IO space descriptor.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetIoSpaceMap (\r
+  OUT UINTN                        *NumberOfDescriptors,\r
+  OUT EFI_GCD_IO_SPACE_DESCRIPTOR  **IoSpaceMap\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Transer all entries of GCD IO map into IO descriptors and pass to caller.\r
+\r
+Arguments:\r
+\r
+  NumberOfDescriptors       - Number of descriptors.\r
+  \r
+  IoSpaceMap                - Descriptor array\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Successfully get IO space map.\r
+\r
+--*/\r
+;\r
+\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreDispatcher (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  This is the main Dispatcher for DXE and it exits when there are no more \r
+  drivers to run. Drain the mScheduledQueue and load and start a PE\r
+  image for each driver. Search the mDiscoveredList to see if any driver can \r
+  be placed on the mScheduledQueue. If no drivers are placed on the\r
+  mScheduledQueue exit the function. On exit it is assumed the Bds()\r
+  will be called, and when the Bds() exits the Dispatcher will be called \r
+  again.\r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  EFI_ALREADY_STARTED - The DXE Dispatcher is already running\r
+\r
+  EFI_NOT_FOUND       - No DXE Drivers were dispatched\r
+\r
+  EFI_SUCCESS         - One or more DXE Drivers were dispatched\r
+\r
+--*/\r
+;\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSchedule (\r
+  IN  EFI_HANDLE  FirmwareVolumeHandle,\r
+  IN  EFI_GUID    *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check every driver and locate a matching one. If the driver is found, the Unrequested\r
+  state flag is cleared.\r
+\r
+Arguments:\r
+\r
+  FirmwareVolumeHandle - The handle of the Firmware Volume that contains the firmware \r
+                         file specified by DriverName.\r
+\r
+  DriverName           - The Driver name to put in the Dependent state.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The DriverName was found and it's SOR bit was cleared\r
+\r
+  EFI_NOT_FOUND - The DriverName does not exist or it's SOR bit was not set.\r
+\r
+--*/\r
+;\r
+\r
+EFI_DXESERVICE\r
+EFI_STATUS\r
+EFIAPI\r
+CoreTrust (\r
+  IN  EFI_HANDLE  FirmwareVolumeHandle,\r
+  IN  EFI_GUID    *DriverName\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Convert a driver from the Untrused back to the Scheduled state\r
+\r
+Arguments:\r
+\r
+  FirmwareVolumeHandle - The handle of the Firmware Volume that contains the firmware \r
+                         file specified by DriverName.\r
+\r
+  DriverName           - The Driver name to put in the Scheduled state\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The file was found in the untrusted state, and it was promoted \r
+                  to the trusted state.\r
+\r
+  EFI_NOT_FOUND - The file was not found in the untrusted state.\r
+\r
+--*/\r
+;\r
+\r
+BOOLEAN\r
+CoreGrowBuffer (\r
+  IN OUT EFI_STATUS       *Status,\r
+  IN OUT VOID             **Buffer,\r
+  IN     UINTN            BufferSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Helper function called as part of the code needed\r
+    to allocate the proper sized buffer for various \r
+    EFI interfaces.\r
+\r
+Arguments:\r
+\r
+    Status      - Current status\r
+\r
+    Buffer      - Current allocated buffer, or NULL\r
+\r
+    BufferSize  - Current buffer size needed\r
+    \r
+Returns:\r
+    \r
+    TRUE - if the buffer was reallocated and the caller \r
+    should try the API again.\r
+\r
+    FALSE - buffer could not be allocated and the caller\r
+    should not try the API again.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolDriverInit (\r
+  IN EFI_HANDLE                   ImageHandle,\r
+  IN EFI_SYSTEM_TABLE             *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine is the driver initialization entry point.  It initializes the\r
+    libraries, and registers two notification functions.  These notification\r
+    functions are responsible for building the FV stack dynamically.\r
+    \r
+Arguments:\r
+    ImageHandle   - The image handle.\r
+    SystemTable   - The system table.\r
+    \r
+Returns:\r
+    EFI_SUCCESS   - Function successfully returned.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+InitializeSectionExtraction (\r
+  IN EFI_HANDLE                   ImageHandle,\r
+  IN EFI_SYSTEM_TABLE             *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description: \r
+  Entry point of the section extraction code. Initializes an instance of the \r
+  section extraction interface and installs it on a new handle.\r
+\r
+Arguments:  \r
+  ImageHandle   EFI_HANDLE: A handle for the image that is initializing this driver\r
+  SystemTable   EFI_SYSTEM_TABLE: A pointer to the EFI system table        \r
+\r
+Returns:  \r
+  EFI_SUCCESS:  Driver initialized successfully\r
+  EFI_OUT_OF_RESOURCES:   Could not allocate needed resources\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreProcessFirmwareVolume (\r
+  IN  VOID                         *FvHeader,\r
+  IN  UINTN                        Size, \r
+  OUT EFI_HANDLE                   *FVProtocolHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This DXE service routine is used to process a firmware volume. In\r
+    particular, it can be called by BDS to process a single firmware\r
+    volume found in a capsule. \r
+\r
+Arguments:\r
+    FvHeader              - pointer to a firmware volume header\r
+    Size                  - the size of the buffer pointed to by FvHeader\r
+    FVProtocolHandle      - the handle on which a firmware volume protocol\r
+                            was produced for the firmware volume passed in.\r
+\r
+Returns:\r
+    EFI_OUT_OF_RESOURCES  - if an FVB could not be produced due to lack of \r
+                            system resources\r
+    EFI_VOLUME_CORRUPTED  - if the volume was corrupted\r
+    EFI_SUCCESS           - a firmware volume protocol was produced for the\r
+                            firmware volume\r
+\r
+--*/\r
+;\r
+\r
+//\r
+//Functions used during debug buils\r
+//\r
+VOID\r
+CoreDisplayMissingArchProtocols (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+  Displays Architectural protocols that were not loaded and are required for DXE core to function\r
+  Only used in Debug Builds\r
+\r
+  Arguments:\r
+    NONE\r
+\r
+  Returns:\r
+    NONE\r
+\r
+--*/;\r
+  \r
+VOID\r
+CoreDisplayDiscoveredNotDispatched (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+\r
+    Traverse the discovered list for any drivers that were discovered but not loaded \r
+    because the dependency experessions evaluated to false\r
+\r
+  Arguments:\r
+\r
+    NONE\r
+\r
+  Returns:\r
+\r
+    NONE \r
+\r
+--*/;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg0 (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg1 (\r
+  UINTN Arg1\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg2 (\r
+  UINTN Arg1,\r
+  UINTN Arg2\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+  \r
+  Arg2        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg3 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+  \r
+  Arg2        - Undefined\r
+  \r
+  Arg3        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg4 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+  \r
+  Arg2        - Undefined\r
+  \r
+  Arg3        - Undefined\r
+  \r
+  Arg4        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg5 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4,\r
+  UINTN Arg5\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+  \r
+  Arg2        - Undefined\r
+  \r
+  Arg3        - Undefined\r
+  \r
+  Arg4        - Undefined\r
+  \r
+  Arg5        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetPeiProtocol (\r
+  IN EFI_GUID  *ProtocolGuid,\r
+  IN VOID      **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Searches for a Protocol Interface passed from PEI through a HOB\r
+\r
+Arguments:\r
+\r
+  ProtocolGuid - The Protocol GUID to search for in the HOB List\r
+\r
+  Interface    - A pointer to the interface for the Protocol GUID\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The Protocol GUID was found and its interface is returned in Interface\r
+\r
+  EFI_NOT_FOUND - The Protocol GUID was not found in the HOB List\r
+\r
+--*/\r
+;\r
+  \r
+EFI_STATUS\r
+DxeMainUefiDecompressGetInfo (\r
+  IN EFI_DECOMPRESS_PROTOCOL            *This,\r
+  IN   VOID                             *Source,\r
+  IN   UINT32                           SourceSize,\r
+  OUT  UINT32                           *DestinationSize,\r
+  OUT  UINT32                           *ScratchSize\r
+  );\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+DxeMainUefiDecompress (\r
+  IN EFI_DECOMPRESS_PROTOCOL              *This,\r
+  IN     VOID                             *Source,\r
+  IN     UINT32                           SourceSize,\r
+  IN OUT VOID                             *Destination,\r
+  IN     UINT32                           DestinationSize,\r
+  IN OUT VOID                             *Scratch,\r
+  IN     UINT32                           ScratchSize\r
+  );\r
+\r
+EFI_STATUS\r
+DxeMainTianoDecompressGetInfo (\r
+  IN EFI_TIANO_DECOMPRESS_PROTOCOL      *This,\r
+  IN   VOID                             *Source,\r
+  IN   UINT32                           SourceSize,\r
+  OUT  UINT32                           *DestinationSize,\r
+  OUT  UINT32                           *ScratchSize\r
+  );\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+DxeMainTianoDecompress (\r
+  IN EFI_TIANO_DECOMPRESS_PROTOCOL        *This,\r
+  IN     VOID                             *Source,\r
+  IN     UINT32                           SourceSize,\r
+  IN OUT VOID                             *Destination,\r
+  IN     UINT32                           DestinationSize,\r
+  IN OUT VOID                             *Scratch,\r
+  IN     UINT32                           ScratchSize\r
+  );\r
+\r
+EFI_STATUS\r
+DxeMainCustomDecompressGetInfo (\r
+  IN EFI_CUSTOMIZED_DECOMPRESS_PROTOCOL  *This,\r
+  IN   VOID                              *Source,\r
+  IN   UINT32                            SourceSize,\r
+  OUT  UINT32                            *DestinationSize,\r
+  OUT  UINT32                            *ScratchSize\r
+  );\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+DxeMainCustomDecompress (\r
+  IN EFI_CUSTOMIZED_DECOMPRESS_PROTOCOL  *This,\r
+  IN     VOID                            *Source,\r
+  IN     UINT32                          SourceSize,\r
+  IN OUT VOID                            *Destination,\r
+  IN     UINT32                          DestinationSize,\r
+  IN OUT VOID                            *Scratch,\r
+  IN     UINT32                          ScratchSize\r
+  );\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.inf b/MdeModulePkg/Core/Dxe/DxeMain.inf
new file mode 100644 (file)
index 0000000..79dccde
--- /dev/null
@@ -0,0 +1,175 @@
+#/** @file\r
+# Component description file for DxeMain module.\r
+#\r
+# This module provide an DXE CIS compliant implementation of DXE Core.\r
+# Copyright (c) 2006 - 2007, Intel Corporation\r
+#\r
+#  All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+#\r
+#\r
+#**/\r
+\r
+################################################################################\r
+#\r
+# Defines Section - statements that will be processed to create a Makefile.\r
+#\r
+################################################################################\r
+[Defines]\r
+  INF_VERSION                    = 0x00010005\r
+  BASE_NAME                      = DxeMain\r
+  FILE_GUID                      = D6A2CB7F-6A18-4e2f-B43B-9920A733700A\r
+  MODULE_TYPE                    = DXE_CORE\r
+  VERSION_STRING                 = 1.0\r
+  EDK_RELEASE_VERSION            = 0x00020000\r
+  EFI_SPECIFICATION_VERSION      = 0x00020000\r
+\r
+  ENTRY_POINT                    = DxeMain\r
+\r
+#\r
+# The following information is for reference only and not required by the build tools.\r
+#\r
+#  VALID_ARCHITECTURES           = IA32 X64 IPF EBC\r
+#\r
+\r
+################################################################################\r
+#\r
+# Sources Section - list of files that are required for the build to succeed.\r
+#\r
+################################################################################\r
+\r
+[Sources.common]\r
+  Library.h\r
+  imem.h\r
+  Image.h\r
+  hand.h\r
+  gcd.h\r
+  FwVolDriver.h\r
+  FwVolBlock.h\r
+  Exec.h\r
+  DxeMain.h\r
+  DebugImageInfo.h\r
+  SectionExtraction/CoreSectionExtraction.c\r
+  Image/ImageFile.c\r
+  Image/Image.c\r
+  Misc/DebugImageInfo.c\r
+  Misc/Stall.c\r
+  Misc/SetWatchdogTimer.c\r
+  Misc/InstallConfigurationTable.c\r
+  Library/Library.c\r
+  Hand/DriverSupport.c\r
+  Hand/Notify.c\r
+  Hand/locate.c\r
+  Hand/handle.c\r
+  Gcd/gcd.c\r
+  Mem/pool.c\r
+  Mem/Page.c\r
+  Mem/memdata.c\r
+  FwVolBlock/FwVolBlock.c\r
+  FwVol/FwVolWrite.c\r
+  FwVol/FwVolRead.c\r
+  FwVol/FwVolAttrib.c\r
+  FwVol/Ffs.c\r
+  FwVol/FwVol.c\r
+  Event/tpl.c\r
+  Event/timer.c\r
+  Event/event.c\r
+  Event/execdata.c\r
+  Dispatcher/dependency.c\r
+  Dispatcher/Dispatcher.c\r
+  DxeMain/DxeProtocolNotify.c\r
+  DxeMain/DxeMain.c\r
+  CommonHeader.h\r
+\r
+\r
+################################################################################\r
+#\r
+# Package Dependency Section - list of Package files that are required for\r
+#                              this module.\r
+#\r
+################################################################################\r
+\r
+[Packages]\r
+  MdePkg/MdePkg.dec\r
+  IntelFrameworkPkg/IntelFrameworkPkg.dec\r
+\r
+\r
+################################################################################\r
+#\r
+# Library Class Section - list of Library Classes that are required for\r
+#                         this module.\r
+#\r
+################################################################################\r
+\r
+[LibraryClasses]\r
+  BaseMemoryLib\r
+  CacheMaintenanceLib\r
+  PeCoffLoaderLib\r
+  UefiDecompressLib\r
+  PerformanceLib\r
+  HobLib\r
+  BaseLib\r
+  UefiLib\r
+  DebugLib\r
+  DxeCoreEntryPoint\r
+\r
+\r
+################################################################################\r
+#\r
+# Guid C Name Section - list of Guids that this module uses or produces.\r
+#\r
+################################################################################\r
+\r
+[Guids]\r
+  gEfiEventLegacyBootGuid                       # ALWAYS_CONSUMED\r
+  gEfiEventReadyToBootGuid                      # ALWAYS_CONSUMED\r
+  gEfiEventMemoryMapChangeGuid                  # ALWAYS_CONSUMED\r
+  gEfiEventVirtualAddressChangeGuid             # ALWAYS_CONSUMED\r
+  gEfiEventExitBootServicesGuid                 # ALWAYS_CONSUMED\r
+  gEfiHobMemoryAllocModuleGuid                  # ALWAYS_CONSUMED\r
+  gEfiFileInfoGuid                              # ALWAYS_CONSUMED\r
+  gEfiFirmwareFileSystemGuid                    # ALWAYS_CONSUMED\r
+  gAprioriGuid                                  # ALWAYS_CONSUMED\r
+  gEfiDebugImageInfoTableGuid                   # ALWAYS_CONSUMED\r
+  gEfiHobListGuid                               # ALWAYS_CONSUMED\r
+  gEfiDxeServicesTableGuid                      # ALWAYS_CONSUMED\r
+  gEfiMemoryTypeInformationGuid                 # ALWAYS_CONSUMED\r
+\r
+\r
+################################################################################\r
+#\r
+# Protocol C Name Section - list of Protocol and Protocol Notify C Names\r
+#                           that this module uses or produces.\r
+#\r
+################################################################################\r
+\r
+[Protocols]\r
+  gEfiStatusCodeRuntimeProtocolGuid             # PROTOCOL SOMETIMES_CONSUMED\r
+  gEfiCapsuleArchProtocolGuid                   # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiTianoDecompressProtocolGuid               # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiCustomizedDecompressProtocolGuid          # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiDecompressProtocolGuid                    # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiLoadPeImageProtocolGuid                   # PROTOCOL ALWAYS_PRODUCED\r
+  gEfiSimpleFileSystemProtocolGuid              # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiLoadFileProtocolGuid                      # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiResetArchProtocolGuid                     # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiRealTimeClockArchProtocolGuid             # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiRuntimeArchProtocolGuid                   # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiWatchdogTimerArchProtocolGuid             # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiSecurityArchProtocolGuid                  # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiVariableArchProtocolGuid                  # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiBdsArchProtocolGuid                       # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiVariableWriteArchProtocolGuid             # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiMonotonicCounterArchProtocolGuid          # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiMetronomeArchProtocolGuid                 # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiTimerArchProtocolGuid                     # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiBusSpecificDriverOverrideProtocolGuid     # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiPlatformDriverOverrideProtocolGuid        # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiDriverBindingProtocolGuid                 # PROTOCOL SOMETIMES_CONSUMED\r
+  gEfiFirmwareVolumeBlockProtocolGuid           # PROTOCOL ALWAYS_PRODUCED\r
+  gEfiFirmwareVolumeDispatchProtocolGuid        # PROTOCOL ALWAYS_PRODUCED\r
+  gEfiFirmwareVolumeProtocolGuid                # PROTOCOL ALWAYS_PRODUCED\r
+  gEfiCpuArchProtocolGuid                       # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiDevicePathProtocolGuid                    # PROTOCOL ALWAYS_CONSUMED\r
+  gEfiLoadedImageProtocolGuid                   # PROTOCOL ALWAYS_PRODUCED\r
+  gEfiEbcProtocolGuid                           # PROTOCOL SOMETIMES_CONSUMED\r
+  gEfiSectionExtractionProtocolGuid             # PROTOCOL ALWAYS_PRODUCED\r
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.msa b/MdeModulePkg/Core/Dxe/DxeMain.msa
new file mode 100644 (file)
index 0000000..1ed9c09
--- /dev/null
@@ -0,0 +1,243 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<ModuleSurfaceArea xmlns="http://www.TianoCore.org/2006/Edk2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\r
+  <MsaHeader>\r
+    <ModuleName>DxeMain</ModuleName>\r
+    <ModuleType>DXE_CORE</ModuleType>\r
+    <GuidValue>D6A2CB7F-6A18-4e2f-B43B-9920A733700A</GuidValue>\r
+    <Version>1.0</Version>\r
+    <Abstract>Component description file for DxeMain module.</Abstract>\r
+    <Description>This module provide an DXE CIS compliant implementation of DXE Core.</Description>\r
+    <Copyright>Copyright (c) 2006 - 2007, Intel Corporation</Copyright>\r
+    <License>All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.</License>\r
+    <Specification>FRAMEWORK_BUILD_PACKAGING_SPECIFICATION   0x00000052</Specification>\r
+  </MsaHeader>\r
+  <ModuleDefinitions>\r
+    <SupportedArchitectures>IA32 X64 IPF EBC</SupportedArchitectures>\r
+    <BinaryModule>false</BinaryModule>\r
+    <OutputFileBasename>DxeMain</OutputFileBasename>\r
+  </ModuleDefinitions>\r
+  <LibraryClassDefinitions>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>DxeCoreEntryPoint</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>DebugLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>UefiLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>BaseLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>HobLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>PerformanceLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>UefiDecompressLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>TianoDecompressLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>CustomDecompressLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>EdkPeCoffLoaderLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>CacheMaintenanceLib</Keyword>\r
+    </LibraryClass>\r
+    <LibraryClass Usage="ALWAYS_CONSUMED">\r
+      <Keyword>BaseMemoryLib</Keyword>\r
+    </LibraryClass>\r
+  </LibraryClassDefinitions>\r
+  <SourceFiles>\r
+    <Filename>DxeMain/DxeMain.c</Filename>\r
+    <Filename>DxeMain/DxeProtocolNotify.c</Filename>\r
+    <Filename>Dispatcher/Dispatcher.c</Filename>\r
+    <Filename>Dispatcher/dependency.c</Filename>\r
+    <Filename>Event/execdata.c</Filename>\r
+    <Filename>Event/event.c</Filename>\r
+    <Filename>Event/timer.c</Filename>\r
+    <Filename>Event/tpl.c</Filename>\r
+    <Filename>FwVol/FwVol.c</Filename>\r
+    <Filename>FwVol/Ffs.c</Filename>\r
+    <Filename>FwVol/FwVolAttrib.c</Filename>\r
+    <Filename>FwVol/FwVolRead.c</Filename>\r
+    <Filename>FwVol/FwVolWrite.c</Filename>\r
+    <Filename>FwVolBlock/FwVolBlock.c</Filename>\r
+    <Filename>Mem/memdata.c</Filename>\r
+    <Filename>Mem/Page.c</Filename>\r
+    <Filename>Mem/pool.c</Filename>\r
+    <Filename>Gcd/gcd.c</Filename>\r
+    <Filename>Hand/handle.c</Filename>\r
+    <Filename>Hand/locate.c</Filename>\r
+    <Filename>Hand/Notify.c</Filename>\r
+    <Filename>Hand/DriverSupport.c</Filename>\r
+    <Filename>Library/Library.c</Filename>\r
+    <Filename>Misc/InstallConfigurationTable.c</Filename>\r
+    <Filename>Misc/SetWatchdogTimer.c</Filename>\r
+    <Filename>Misc/Stall.c</Filename>\r
+    <Filename>Misc/DebugImageInfo.c</Filename>\r
+    <Filename>Image/Image.c</Filename>\r
+    <Filename>Image/ImageFile.c</Filename>\r
+    <Filename>SectionExtraction/CoreSectionExtraction.c</Filename>\r
+    <Filename>DebugImageInfo.h</Filename>\r
+    <Filename>DxeMain.h</Filename>\r
+    <Filename>Exec.h</Filename>\r
+    <Filename>FwVolBlock.h</Filename>\r
+    <Filename>FwVolDriver.h</Filename>\r
+    <Filename>gcd.h</Filename>\r
+    <Filename>hand.h</Filename>\r
+    <Filename>Image.h</Filename>\r
+    <Filename>imem.h</Filename>\r
+    <Filename>Library.h</Filename>\r
+  </SourceFiles>\r
+  <PackageDependencies>\r
+    <Package PackageGuid="5e0e9358-46b6-4ae2-8218-4ab8b9bbdcec"/>\r
+    <Package PackageGuid="68169ab0-d41b-4009-9060-292c253ac43d"/>\r
+  </PackageDependencies>\r
+  <Protocols>\r
+    <Protocol Usage="SOMETIMES_CONSUMED">\r
+      <ProtocolCName>gEfiEbcProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiLoadedImageProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiDevicePathProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiCpuArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiFirmwareVolumeProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiFirmwareVolumeDispatchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiFirmwareVolumeBlockProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiSectionExtractionProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="SOMETIMES_CONSUMED">\r
+      <ProtocolCName>gEfiDriverBindingProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiPlatformDriverOverrideProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiBusSpecificDriverOverrideProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiTimerArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiMetronomeArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiMonotonicCounterArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiVariableWriteArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiBdsArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiVariableArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiSecurityArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiWatchdogTimerArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiRuntimeArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiRealTimeClockArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiResetArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiLoadFileProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiSimpleFileSystemProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_PRODUCED">\r
+      <ProtocolCName>gEfiLoadPeImageProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiDecompressProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiCustomizedDecompressProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiTianoDecompressProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="ALWAYS_CONSUMED">\r
+      <ProtocolCName>gEfiCapsuleArchProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+    <Protocol Usage="SOMETIMES_CONSUMED">\r
+      <ProtocolCName>gEfiStatusCodeRuntimeProtocolGuid</ProtocolCName>\r
+    </Protocol>\r
+  </Protocols>\r
+  <Guids>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiMemoryTypeInformationGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiDxeServicesTableGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiHobListGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiDebugImageInfoTableGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gAprioriGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiFirmwareFileSystemGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiFileInfoGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiHobMemoryAllocModuleGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiEventExitBootServicesGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiEventVirtualAddressChangeGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiEventMemoryMapChangeGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiEventReadyToBootGuid</GuidCName>\r
+    </GuidCNames>\r
+    <GuidCNames Usage="ALWAYS_CONSUMED">\r
+      <GuidCName>gEfiEventLegacyBootGuid</GuidCName>\r
+    </GuidCNames>\r
+  </Guids>\r
+  <Externs>\r
+    <Specification>EFI_SPECIFICATION_VERSION 0x00020000</Specification>\r
+    <Specification>EDK_RELEASE_VERSION 0x00020000</Specification>\r
+    <Extern>\r
+      <ModuleEntryPoint>DxeMain</ModuleEntryPoint>\r
+    </Extern>\r
+  </Externs>\r
+</ModuleSurfaceArea>\r
diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
new file mode 100644 (file)
index 0000000..0324901
--- /dev/null
@@ -0,0 +1,874 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  DxeMain.c\r
+\r
+Abstract:\r
+\r
+  DXE Core Main Entry Point\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// DXE Core Global Variables for Protocols from PEI\r
+//\r
+EFI_HANDLE                                mDecompressHandle = NULL;\r
+EFI_PEI_PE_COFF_LOADER_PROTOCOL           *gEfiPeiPeCoffLoader          = NULL;\r
+\r
+//\r
+// DXE Core globals for Architecture Protocols\r
+//\r
+EFI_SECURITY_ARCH_PROTOCOL        *gSecurity      = NULL;\r
+EFI_CPU_ARCH_PROTOCOL             *gCpu           = NULL;\r
+EFI_METRONOME_ARCH_PROTOCOL       *gMetronome     = NULL;\r
+EFI_TIMER_ARCH_PROTOCOL           *gTimer         = NULL;\r
+EFI_BDS_ARCH_PROTOCOL             *gBds           = NULL;\r
+EFI_WATCHDOG_TIMER_ARCH_PROTOCOL  *gWatchdogTimer = NULL;\r
+\r
+\r
+//\r
+// BugBug: I'n not runtime, but is the PPI?\r
+//\r
+EFI_STATUS_CODE_PROTOCOL     gStatusCodeInstance = {\r
+  NULL\r
+};\r
+\r
+EFI_STATUS_CODE_PROTOCOL     *gStatusCode    = &gStatusCodeInstance;\r
+\r
+\r
+//\r
+// DXE Core Global used to update core loaded image protocol handle\r
+//\r
+EFI_GUID                           *gDxeCoreFileName;\r
+EFI_LOADED_IMAGE_PROTOCOL          *gDxeCoreLoadedImage;\r
+\r
+\r
+\r
+//\r
+// DXE Core Module Variables\r
+//\r
+\r
+EFI_BOOT_SERVICES mBootServices = {\r
+  {\r
+    EFI_BOOT_SERVICES_SIGNATURE,                                                          // Signature\r
+    EFI_BOOT_SERVICES_REVISION,                                                           // Revision\r
+    sizeof (EFI_BOOT_SERVICES),                                                           // HeaderSize\r
+    0,                                                                                    // CRC32\r
+    0                                                                                     // Reserved\r
+  },\r
+  (EFI_RAISE_TPL)                               CoreRaiseTpl,                             // RaiseTPL\r
+  (EFI_RESTORE_TPL)                             CoreRestoreTpl,                           // RestoreTPL\r
+  (EFI_ALLOCATE_PAGES)                          CoreAllocatePages,                        // AllocatePages\r
+  (EFI_FREE_PAGES)                              CoreFreePages,                            // FreePages\r
+  (EFI_GET_MEMORY_MAP)                          CoreGetMemoryMap,                         // GetMemoryMap\r
+  (EFI_ALLOCATE_POOL)                           CoreAllocatePool,                         // AllocatePool\r
+  (EFI_FREE_POOL)                               CoreFreePool,                             // FreePool\r
+  (EFI_CREATE_EVENT)                            CoreCreateEvent,                          // CreateEvent\r
+  (EFI_SET_TIMER)                               CoreSetTimer,                             // SetTimer\r
+  (EFI_WAIT_FOR_EVENT)                          CoreWaitForEvent,                         // WaitForEvent\r
+  (EFI_SIGNAL_EVENT)                            CoreSignalEvent,                          // SignalEvent\r
+  (EFI_CLOSE_EVENT)                             CoreCloseEvent,                           // CloseEvent\r
+  (EFI_CHECK_EVENT)                             CoreCheckEvent,                           // CheckEvent\r
+  (EFI_INSTALL_PROTOCOL_INTERFACE)              CoreInstallProtocolInterface,             // InstallProtocolInterface\r
+  (EFI_REINSTALL_PROTOCOL_INTERFACE)            CoreReinstallProtocolInterface,           // ReinstallProtocolInterface\r
+  (EFI_UNINSTALL_PROTOCOL_INTERFACE)            CoreUninstallProtocolInterface,           // UninstallProtocolInterface\r
+  (EFI_HANDLE_PROTOCOL)                         CoreHandleProtocol,                       // HandleProtocol\r
+  (VOID *)                                      NULL,                                     // Reserved\r
+  (EFI_REGISTER_PROTOCOL_NOTIFY)                CoreRegisterProtocolNotify,               // RegisterProtocolNotify\r
+  (EFI_LOCATE_HANDLE)                           CoreLocateHandle,                         // LocateHandle\r
+  (EFI_LOCATE_DEVICE_PATH)                      CoreLocateDevicePath,                     // LocateDevicePath\r
+  (EFI_INSTALL_CONFIGURATION_TABLE)             CoreInstallConfigurationTable,            // InstallConfigurationTable\r
+  (EFI_IMAGE_LOAD)                              CoreLoadImage,                            // LoadImage\r
+  (EFI_IMAGE_START)                             CoreStartImage,                           // StartImage\r
+  (EFI_EXIT)                                    CoreExit,                                 // Exit\r
+  (EFI_IMAGE_UNLOAD)                            CoreUnloadImage,                          // UnloadImage\r
+  (EFI_EXIT_BOOT_SERVICES)                      CoreExitBootServices,                     // ExitBootServices\r
+  (EFI_GET_NEXT_MONOTONIC_COUNT)                CoreEfiNotAvailableYetArg1,               // GetNextMonotonicCount\r
+  (EFI_STALL)                                   CoreStall,                                // Stall\r
+  (EFI_SET_WATCHDOG_TIMER)                      CoreSetWatchdogTimer,                     // SetWatchdogTimer\r
+  (EFI_CONNECT_CONTROLLER)                      CoreConnectController,                    // ConnectController\r
+  (EFI_DISCONNECT_CONTROLLER)                   CoreDisconnectController,                 // DisconnectController\r
+  (EFI_OPEN_PROTOCOL)                           CoreOpenProtocol,                         // OpenProtocol\r
+  (EFI_CLOSE_PROTOCOL)                          CoreCloseProtocol,                        // CloseProtocol\r
+  (EFI_OPEN_PROTOCOL_INFORMATION)               CoreOpenProtocolInformation,              // OpenProtocolInformation\r
+  (EFI_PROTOCOLS_PER_HANDLE)                    CoreProtocolsPerHandle,                   // ProtocolsPerHandle\r
+  (EFI_LOCATE_HANDLE_BUFFER)                    CoreLocateHandleBuffer,                   // LocateHandleBuffer\r
+  (EFI_LOCATE_PROTOCOL)                         CoreLocateProtocol,                       // LocateProtocol\r
+  (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES)    CoreInstallMultipleProtocolInterfaces,    // InstallMultipleProtocolInterfaces\r
+  (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES)  CoreUninstallMultipleProtocolInterfaces,  // UninstallMultipleProtocolInterfaces\r
+  (EFI_CALCULATE_CRC32)                         CoreEfiNotAvailableYetArg3,               // CalculateCrc32\r
+  (EFI_COPY_MEM)                                CopyMem,                                  // CopyMem\r
+  (EFI_SET_MEM)                                 SetMem,                                   // SetMem\r
+  (EFI_CREATE_EVENT_EX)                         CoreCreateEventEx                         // CreateEventEx\r
+};\r
+\r
+EFI_DXE_SERVICES mDxeServices = {\r
+  {\r
+    DXE_SERVICES_SIGNATURE,                                           // Signature\r
+    DXE_SERVICES_REVISION,                                            // Revision\r
+    sizeof (DXE_SERVICES),                                            // HeaderSize\r
+    0,                                                                    // CRC32\r
+    0                                                                     // Reserved\r
+  },\r
+  (EFI_ADD_MEMORY_SPACE)             CoreAddMemorySpace,                  // AddMemorySpace\r
+  (EFI_ALLOCATE_MEMORY_SPACE)        CoreAllocateMemorySpace,             // AllocateMemorySpace\r
+  (EFI_FREE_MEMORY_SPACE)            CoreFreeMemorySpace,                 // FreeMemorySpace\r
+  (EFI_REMOVE_MEMORY_SPACE)          CoreRemoveMemorySpace,               // RemoveMemorySpace\r
+  (EFI_GET_MEMORY_SPACE_DESCRIPTOR)  CoreGetMemorySpaceDescriptor,        // GetMemorySpaceDescriptor\r
+  (EFI_SET_MEMORY_SPACE_ATTRIBUTES)  CoreSetMemorySpaceAttributes,        // SetMemorySpaceAttributes\r
+  (EFI_GET_MEMORY_SPACE_MAP)         CoreGetMemorySpaceMap,               // GetMemorySpaceMap\r
+  (EFI_ADD_IO_SPACE)                 CoreAddIoSpace,                      // AddIoSpace\r
+  (EFI_ALLOCATE_IO_SPACE)            CoreAllocateIoSpace,                 // AllocateIoSpace\r
+  (EFI_FREE_IO_SPACE)                CoreFreeIoSpace,                     // FreeIoSpace\r
+  (EFI_REMOVE_IO_SPACE)              CoreRemoveIoSpace,                   // RemoveIoSpace\r
+  (EFI_GET_IO_SPACE_DESCRIPTOR)      CoreGetIoSpaceDescriptor,            // GetIoSpaceDescriptor\r
+  (EFI_GET_IO_SPACE_MAP)             CoreGetIoSpaceMap,                   // GetIoSpaceMap\r
+  (EFI_DISPATCH)                     CoreDispatcher,                      // Dispatch\r
+  (EFI_SCHEDULE)                     CoreSchedule,                        // Schedule\r
+  (EFI_TRUST)                        CoreTrust,                           // Trust\r
+  (EFI_PROCESS_FIRMWARE_VOLUME)      CoreProcessFirmwareVolume,           // ProcessFirmwareVolume\r
+};\r
+\r
+EFI_SYSTEM_TABLE mEfiSystemTableTemplate = {\r
+  {\r
+    EFI_SYSTEM_TABLE_SIGNATURE,                                           // Signature\r
+    EFI_SYSTEM_TABLE_REVISION,                                            // Revision\r
+    sizeof (EFI_SYSTEM_TABLE),                                            // HeaderSize\r
+    0,                                                                    // CRC32\r
+    0                                                                     // Reserved\r
+  },\r
+  NULL,                                                                   // FirmwareVendor\r
+  0,                                                                      // FirmwareRevision\r
+  NULL,                                                                   // ConsoleInHandle\r
+  NULL,                                                                   // ConIn\r
+  NULL,                                                                   // ConsoleOutHandle\r
+  NULL,                                                                   // ConOut\r
+  NULL,                                                                   // StandardErrorHandle\r
+  NULL,                                                                   // StdErr\r
+  NULL,                                                                   // RuntimeServices\r
+  &mBootServices,                                                         // BootServices\r
+  0,                                                                      // NumberOfConfigurationTableEntries\r
+  NULL                                                                    // ConfigurationTable\r
+};\r
+\r
+EFI_RUNTIME_SERVICES mEfiRuntimeServicesTableTemplate = {\r
+  {\r
+    EFI_RUNTIME_SERVICES_SIGNATURE,                               // Signature\r
+    EFI_RUNTIME_SERVICES_REVISION,                                // Revision\r
+    sizeof (EFI_RUNTIME_SERVICES),                                // HeaderSize\r
+    0,                                                            // CRC32\r
+    0                                                             // Reserved\r
+  },\r
+  (EFI_GET_TIME)                    CoreEfiNotAvailableYetArg2,   // GetTime\r
+  (EFI_SET_TIME)                    CoreEfiNotAvailableYetArg1,   // SetTime\r
+  (EFI_GET_WAKEUP_TIME)             CoreEfiNotAvailableYetArg3,   // GetWakeupTime\r
+  (EFI_SET_WAKEUP_TIME)             CoreEfiNotAvailableYetArg2,   // SetWakeupTime\r
+  (EFI_SET_VIRTUAL_ADDRESS_MAP)     CoreEfiNotAvailableYetArg4,   // SetVirtualAddressMap\r
+  (EFI_CONVERT_POINTER)             CoreEfiNotAvailableYetArg2,   // ConvertPointer\r
+  (EFI_GET_VARIABLE)                CoreEfiNotAvailableYetArg5,   // GetVariable\r
+  (EFI_GET_NEXT_VARIABLE_NAME)      CoreEfiNotAvailableYetArg3,   // GetNextVariableName\r
+  (EFI_SET_VARIABLE)                CoreEfiNotAvailableYetArg5,   // SetVariable\r
+  (EFI_GET_NEXT_HIGH_MONO_COUNT)    CoreEfiNotAvailableYetArg1,   // GetNextHighMonotonicCount\r
+  (EFI_RESET_SYSTEM)                CoreEfiNotAvailableYetArg4,   // ResetSystem\r
+  (EFI_UPDATE_CAPSULE)              CoreEfiNotAvailableYetArg3,   // UpdateCapsule\r
+  (EFI_QUERY_CAPSULE_CAPABILITIES)  CoreEfiNotAvailableYetArg4,   // QueryCapsuleCapabilities\r
+  (EFI_QUERY_VARIABLE_INFO)         CoreEfiNotAvailableYetArg4    // QueryVariableInfo\r
+};\r
+\r
+EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate = {\r
+  INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.ImageHead),\r
+  INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.EventHead),\r
+\r
+  //\r
+  // Make sure Size != sizeof (EFI_MEMORY_DESCRIPTOR). This will\r
+  // prevent people from having pointer math bugs in their code.\r
+  // now you have to use *DescriptorSize to make things work.\r
+  //\r
+  sizeof (EFI_MEMORY_DESCRIPTOR) + sizeof (UINT64) - (sizeof (EFI_MEMORY_DESCRIPTOR) % sizeof (UINT64)),\r
+  EFI_MEMORY_DESCRIPTOR_VERSION,\r
+  0,\r
+  NULL,\r
+  NULL,\r
+  FALSE,\r
+  FALSE\r
+};\r
+\r
+EFI_RUNTIME_ARCH_PROTOCOL *gRuntime = &gRuntimeTemplate;\r
+\r
+//\r
+// DXE Core Global Variables for the EFI System Table, Boot Services Table,\r
+// DXE Services Table, and Runtime Services Table\r
+//\r
+EFI_BOOT_SERVICES     *gDxeCoreBS = &mBootServices;\r
+EFI_DXE_SERVICES      *gDxeCoreDS = &mDxeServices;\r
+EFI_SYSTEM_TABLE      *gDxeCoreST = NULL;\r
+\r
+//\r
+// For debug initialize gDxeCoreRT to template. gDxeCoreRT must be allocated from RT memory\r
+//  but gDxeCoreRT is used for ASSERT () and DEBUG () type macros so lets give it\r
+//  a value that will not cause debug infrastructure to crash early on.\r
+//\r
+EFI_RUNTIME_SERVICES  *gDxeCoreRT = &mEfiRuntimeServicesTableTemplate;\r
+EFI_HANDLE            gDxeCoreImageHandle = NULL;\r
+\r
+VOID  *mHobStart;\r
+\r
+//\r
+// EFI Decompress Protocol\r
+//\r
+EFI_DECOMPRESS_PROTOCOL  gEfiDecompress = {\r
+  DxeMainUefiDecompressGetInfo,\r
+  DxeMainUefiDecompress\r
+};\r
+\r
+//\r
+// Main entry point to the DXE Core\r
+//\r
+VOID\r
+EFIAPI\r
+DxeMain (\r
+  IN  VOID *HobStart\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Main entry point to DXE Core.\r
+\r
+Arguments:\r
+\r
+  HobStart - Pointer to the beginning of the HOB List from PEI\r
+\r
+Returns:\r
+\r
+  This function should never return\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                         Status;\r
+  EFI_PHYSICAL_ADDRESS               MemoryBaseAddress;\r
+  UINT64                             MemoryLength;\r
+\r
+  mHobStart = HobStart;\r
+\r
+  //\r
+  // Initialize Memory Services\r
+  //\r
+  CoreInitializeMemoryServices (&HobStart, &MemoryBaseAddress, &MemoryLength);\r
+\r
+  //\r
+  // Allocate the EFI System Table and EFI Runtime Service Table from EfiRuntimeServicesData\r
+  // Use the templates to initialize the contents of the EFI System Table and EFI Runtime Services Table\r
+  //\r
+  gDxeCoreST = CoreAllocateRuntimeCopyPool (sizeof (EFI_SYSTEM_TABLE), &mEfiSystemTableTemplate);\r
+  ASSERT (gDxeCoreST != NULL);\r
+\r
+  gDxeCoreRT = CoreAllocateRuntimeCopyPool (sizeof (EFI_RUNTIME_SERVICES), &mEfiRuntimeServicesTableTemplate);\r
+  ASSERT (gDxeCoreRT != NULL);\r
+\r
+  gDxeCoreST->RuntimeServices = gDxeCoreRT;\r
+\r
+  //\r
+  // Start the Image Services.\r
+  //\r
+  Status = CoreInitializeImageServices (HobStart);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Call constructor for all libraries\r
+  //\r
+  ProcessLibraryConstructorList (gDxeCoreImageHandle, gDxeCoreST);\r
+  PERF_END   (0,PEI_TOK, NULL, 0) ;\r
+  PERF_START (0,DXE_TOK, NULL, 0) ;\r
+\r
+  //\r
+  // Initialize the Global Coherency Domain Services\r
+  //\r
+  Status = CoreInitializeGcdServices (&HobStart, MemoryBaseAddress, MemoryLength);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Install the DXE Services Table into the EFI System Tables's Configuration Table\r
+  //\r
+  Status = CoreInstallConfigurationTable (&gEfiDxeServicesTableGuid, gDxeCoreDS);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Install the HOB List into the EFI System Tables's Configuration Table\r
+  //\r
+  Status = CoreInstallConfigurationTable (&gEfiHobListGuid, HobStart);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Install Memory Type Information Table into the EFI System Tables's Configuration Table\r
+  //\r
+  Status = CoreInstallConfigurationTable (&gEfiMemoryTypeInformationGuid, &gMemoryTypeInformation);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Initialize the ReportStatusCode with PEI version, if available\r
+  //\r
+  CoreGetPeiProtocol (&gEfiStatusCodeRuntimeProtocolGuid, (VOID **)&gStatusCode->ReportStatusCode);\r
+\r
+  //\r
+  // Report Status Code here for DXE_ENTRY_POINT once it is available\r
+  //\r
+  CoreReportProgressCode ((EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_ENTRY_POINT));\r
+\r
+  //\r
+  // Create the aligned system table pointer structure that is used by external\r
+  // debuggers to locate the system table...  Also, install debug image info\r
+  // configuration table.\r
+  //\r
+  CoreInitializeDebugImageInfoTable ();\r
+  CoreNewDebugImageInfoEntry (\r
+    EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL,\r
+    gDxeCoreLoadedImage,\r
+    gDxeCoreImageHandle\r
+    );\r
+\r
+  DEBUG ((EFI_D_INFO | EFI_D_LOAD, "HOBLIST address in DXE = 0x%08x\n", HobStart));\r
+\r
+  //\r
+  // Initialize the Event Services\r
+  //\r
+  Status = CoreInitializeEventServices ();\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+\r
+  //\r
+  // Get the Protocols that were passed in from PEI to DXE through GUIDed HOBs\r
+  //\r
+  // These Protocols are not architectural. This implementation is sharing code between\r
+  // PEI and DXE in order to save FLASH space. These Protocols could also be implemented\r
+  // as part of the DXE Core. However, that would also require the DXE Core to be ported\r
+  // each time a different CPU is used, a different Decompression algorithm is used, or a\r
+  // different Image type is used. By placing these Protocols in PEI, the DXE Core remains\r
+  // generic, and only PEI and the Arch Protocols need to be ported from Platform to Platform,\r
+  // and from CPU to CPU.\r
+  //\r
+\r
+  //\r
+  // Publish the EFI, Tiano, and Custom Decompress protocols for use by other DXE components\r
+  //\r
+  Status = CoreInstallMultipleProtocolInterfaces (\r
+              &mDecompressHandle,\r
+              &gEfiDecompressProtocolGuid,           &gEfiDecompress,\r
+              NULL\r
+              );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  gEfiPeiPeCoffLoader = GetPeCoffLoaderProtocol ();\r
+  ASSERT (gEfiPeiPeCoffLoader != NULL);\r
+\r
+  //\r
+  // Register for the GUIDs of the Architectural Protocols, so the rest of the\r
+  // EFI Boot Services and EFI Runtime Services tables can be filled in.\r
+  //\r
+  CoreNotifyOnArchProtocolInstallation ();\r
+\r
+  //\r
+  // Produce Firmware Volume Protocols, one for each FV in the HOB list.\r
+  //\r
+  Status = FwVolBlockDriverInit (gDxeCoreImageHandle, gDxeCoreST);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  Status = FwVolDriverInit (gDxeCoreImageHandle, gDxeCoreST);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Produce the Section Extraction Protocol\r
+  //\r
+  Status = InitializeSectionExtraction (gDxeCoreImageHandle, gDxeCoreST);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Initialize the DXE Dispatcher\r
+  //\r
+  PERF_START (0,"CoreInitializeDispatcher", "DxeMain", 0) ;\r
+  CoreInitializeDispatcher ();\r
+  PERF_END (0,"CoreInitializeDispatcher", "DxeMain", 0) ;\r
+\r
+  //\r
+  // Invoke the DXE Dispatcher\r
+  //\r
+  PERF_START (0, "CoreDispatcher", "DxeMain", 0);\r
+  CoreDispatcher ();\r
+  PERF_END (0, "CoreDispatcher", "DxeMain", 0);\r
+\r
+  //\r
+  // Display Architectural protocols that were not loaded if this is DEBUG build\r
+  //\r
+  DEBUG_CODE_BEGIN ();\r
+    CoreDisplayMissingArchProtocols ();\r
+  DEBUG_CODE_END ();\r
+\r
+  //\r
+  // Assert if the Architectural Protocols are not present.\r
+  //\r
+  ASSERT_EFI_ERROR (CoreAllEfiServicesAvailable ());\r
+\r
+  //\r
+  // Report Status code before transfer control to BDS\r
+  //\r
+  CoreReportProgressCode ((EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_HANDOFF_TO_NEXT));\r
+  //\r
+  // Display any drivers that were not dispatched because dependency expression\r
+  // evaluated to false if this is a debug build\r
+  //\r
+  DEBUG_CODE_BEGIN ();\r
+    CoreDisplayDiscoveredNotDispatched ();\r
+  DEBUG_CODE_END ();\r
+\r
+  //\r
+  // Transfer control to the BDS Architectural Protocol\r
+  //\r
+  gBds->Entry (gBds);\r
+\r
+  //\r
+  // BDS should never return\r
+  //\r
+  ASSERT (FALSE);\r
+  CpuDeadLoop ();\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg0 (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg1 (\r
+  UINTN Arg1\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg2 (\r
+  UINTN Arg1,\r
+  UINTN Arg2\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+  Arg2        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg3 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+  Arg2        - Undefined\r
+\r
+  Arg3        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg4 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+  Arg2        - Undefined\r
+\r
+  Arg3        - Undefined\r
+\r
+  Arg4        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreEfiNotAvailableYetArg5 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4,\r
+  UINTN Arg5\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Place holder function until all the Boot Services and Runtime Services are available\r
+\r
+Arguments:\r
+\r
+  Arg1        - Undefined\r
+\r
+  Arg2        - Undefined\r
+\r
+  Arg3        - Undefined\r
+\r
+  Arg4        - Undefined\r
+\r
+  Arg5        - Undefined\r
+\r
+Returns:\r
+\r
+  EFI_NOT_AVAILABLE_YET\r
+\r
+--*/\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.  The CpuBreakpoint () is commented out for now until the\r
+  // DXE Core and all the Architectural Protocols are complete.\r
+  //\r
+\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreGetPeiProtocol (\r
+  IN EFI_GUID  *ProtocolGuid,\r
+  IN VOID      **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Searches for a Protocol Interface passed from PEI through a HOB\r
+\r
+Arguments:\r
+\r
+  ProtocolGuid - The Protocol GUID to search for in the HOB List\r
+\r
+  Interface    - A pointer to the interface for the Protocol GUID\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - The Protocol GUID was found and its interface is returned in Interface\r
+\r
+  EFI_NOT_FOUND - The Protocol GUID was not found in the HOB List\r
+\r
+--*/\r
+{\r
+  EFI_HOB_GUID_TYPE   *GuidHob;\r
+  VOID                *Buffer;\r
+\r
+  GuidHob = GetNextGuidHob (ProtocolGuid, mHobStart);\r
+  if (GuidHob == NULL) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  Buffer = GET_GUID_HOB_DATA (GuidHob);\r
+  ASSERT (Buffer != NULL);\r
+\r
+  *Interface = (VOID *)(*(UINTN *)(Buffer));\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+VOID\r
+CalculateEfiHdrCrc (\r
+  IN  OUT EFI_TABLE_HEADER    *Hdr\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Calcualte the 32-bit CRC in a EFI table using the service provided by the\r
+  gRuntime service.\r
+\r
+Arguments:\r
+\r
+  Hdr  - Pointer to an EFI standard header\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  UINT32 Crc;\r
+\r
+  Hdr->CRC32 = 0;\r
+\r
+  //\r
+  // If gDxeCoreBS->CalculateCrce32 () == CoreEfiNotAvailableYet () then\r
+  //  Crc will come back as zero if we set it to zero here\r
+  //\r
+  Crc = 0;\r
+  gDxeCoreBS->CalculateCrc32 ((UINT8 *)Hdr, Hdr->HeaderSize, &Crc);\r
+  Hdr->CRC32 = Crc;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreExitBootServices (\r
+  IN EFI_HANDLE   ImageHandle,\r
+  IN UINTN        MapKey\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Terminates all boot services.\r
+\r
+Arguments:\r
+\r
+  ImageHandle   - Handle that identifies the exiting image.\r
+\r
+  MapKey -Key to the latest memory map.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - Boot Services terminated\r
+  EFI_INVALID_PARAMETER - MapKey is incorrect.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS    Status;\r
+\r
+  //\r
+  // Terminate memory services if the MapKey matches\r
+  //\r
+  Status = CoreTerminateMemoryMap (MapKey);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Notify other drivers that we are exiting boot services.\r
+  //\r
+  CoreNotifySignalList (&gEfiEventExitBootServicesGuid);\r
+\r
+  //\r
+  // Disable Timer\r
+  //\r
+  gTimer->SetTimerPeriod (gTimer, 0);\r
+\r
+  //\r
+  // Disable CPU Interrupts\r
+  //\r
+  gCpu->DisableInterrupt (gCpu);\r
+\r
+  //\r
+  // Report that ExitBootServices() has been called\r
+  //\r
+  // We are using gEfiDxeServicesTableGuid as the caller ID for Dxe Core\r
+  //\r
+  CoreReportProgressCode ((EFI_SOFTWARE_EFI_BOOT_SERVICE | EFI_SW_BS_PC_EXIT_BOOT_SERVICES));\r
+\r
+  //\r
+  // Clear the non-runtime values of the EFI System Table\r
+  //\r
+  gDxeCoreST->BootServices        = NULL;\r
+  gDxeCoreST->ConIn               = NULL;\r
+  gDxeCoreST->ConsoleInHandle     = NULL;\r
+  gDxeCoreST->ConOut              = NULL;\r
+  gDxeCoreST->ConsoleOutHandle    = NULL;\r
+  gDxeCoreST->StdErr              = NULL;\r
+  gDxeCoreST->StandardErrorHandle = NULL;\r
+\r
+  //\r
+  // Recompute the 32-bit CRC of the EFI System Table\r
+  //\r
+  CalculateEfiHdrCrc (&gDxeCoreST->Hdr);\r
+\r
+  //\r
+  // Zero out the Boot Service Table\r
+  //\r
+  SetMem (gDxeCoreBS, sizeof (EFI_BOOT_SERVICES), 0);\r
+  gDxeCoreBS = NULL;\r
+\r
+  //\r
+  // Update the AtRuntime field in Runtiem AP.\r
+  //\r
+  gRuntime->AtRuntime = TRUE;\r
+\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+DxeMainUefiDecompressGetInfo (\r
+  IN EFI_DECOMPRESS_PROTOCOL            *This,\r
+  IN   VOID                             *Source,\r
+  IN   UINT32                           SourceSize,\r
+  OUT  UINT32                           *DestinationSize,\r
+  OUT  UINT32                           *ScratchSize\r
+  )\r
+{\r
+  if (Source == NULL \r
+        || DestinationSize == NULL \r
+        || ScratchSize == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  return UefiDecompressGetInfo (Source, SourceSize, DestinationSize, ScratchSize);\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+DxeMainUefiDecompress (\r
+  IN EFI_DECOMPRESS_PROTOCOL              *This,\r
+  IN     VOID                             *Source,\r
+  IN     UINT32                           SourceSize,\r
+  IN OUT VOID                             *Destination,\r
+  IN     UINT32                           DestinationSize,\r
+  IN OUT VOID                             *Scratch,\r
+  IN     UINT32                           ScratchSize\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+  UINT32      TestDestinationSize;\r
+  UINT32      TestScratchSize;\r
+  \r
+  if (Source == NULL \r
+        || Destination== NULL \r
+        || Scratch == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  Status = UefiDecompressGetInfo (Source, SourceSize, &TestDestinationSize, &TestScratchSize);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  if (ScratchSize < TestScratchSize || DestinationSize < TestDestinationSize) {\r
+    return RETURN_INVALID_PARAMETER;\r
+  }\r
+\r
+  return UefiDecompress (Source, Destination, Scratch);\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c
new file mode 100644 (file)
index 0000000..5c9a5b8
--- /dev/null
@@ -0,0 +1,297 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  DxeProtocolNotify.c\r
+\r
+Abstract:\r
+\r
+  This file deals with Architecture Protocol (AP) registration in\r
+  the Dxe Core. The mArchProtocols[] array represents a list of\r
+  events that represent the Architectural Protocols.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+//\r
+// DXE Core Global Variables for all of the Architectural Protocols.\r
+// If a protocol is installed mArchProtocols[].Present will be TRUE.\r
+//\r
+// CoreNotifyOnArchProtocolInstallation () fills in mArchProtocols[].Event\r
+// and mArchProtocols[].Registration as it creates events for every array\r
+// entry.\r
+//\r
+\r
+ARCHITECTURAL_PROTOCOL_ENTRY  mArchProtocols[] = {\r
+  { &gEfiSecurityArchProtocolGuid,         (VOID **)&gSecurity,      NULL, NULL, FALSE },\r
+  { &gEfiCpuArchProtocolGuid,              (VOID **)&gCpu,           NULL, NULL, FALSE },\r
+  { &gEfiMetronomeArchProtocolGuid,        (VOID **)&gMetronome,     NULL, NULL, FALSE },\r
+  { &gEfiTimerArchProtocolGuid,            (VOID **)&gTimer,         NULL, NULL, FALSE },\r
+  { &gEfiBdsArchProtocolGuid,              (VOID **)&gBds,           NULL, NULL, FALSE },\r
+  { &gEfiWatchdogTimerArchProtocolGuid,    (VOID **)&gWatchdogTimer, NULL, NULL, FALSE },\r
+  { &gEfiRuntimeArchProtocolGuid,          (VOID **)&gRuntime,       NULL, NULL, FALSE },\r
+  { &gEfiVariableArchProtocolGuid,         (VOID **)NULL,            NULL, NULL, FALSE },\r
+  { &gEfiVariableWriteArchProtocolGuid,    (VOID **)NULL,            NULL, NULL, FALSE },\r
+  { &gEfiCapsuleArchProtocolGuid,          (VOID **)NULL,            NULL, NULL, FALSE},\r
+  { &gEfiMonotonicCounterArchProtocolGuid, (VOID **)NULL,            NULL, NULL, FALSE },\r
+  { &gEfiResetArchProtocolGuid,            (VOID **)NULL,            NULL, NULL, FALSE },\r
+  { &gEfiRealTimeClockArchProtocolGuid,    (VOID **)NULL,            NULL, NULL, FALSE },\r
+  { NULL,                                  (VOID **)NULL,            NULL, NULL, FALSE }\r
+};\r
+\r
+\r
+EFI_STATUS\r
+CoreAllEfiServicesAvailable (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Return TRUE if all AP services are availible.\r
+\r
+Arguments:\r
+  NONE\r
+\r
+Returns:\r
+  EFI_SUCCESS   - All AP services are available\r
+  EFI_NOT_FOUND - At least one AP service is not available\r
+\r
+--*/\r
+{\r
+  ARCHITECTURAL_PROTOCOL_ENTRY  *Entry;\r
+\r
+  for (Entry = mArchProtocols; Entry->ProtocolGuid != NULL; Entry++) {\r
+    if (!Entry->Present) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+GenericArchProtocolNotify (\r
+  IN   EFI_EVENT       Event,\r
+  IN   VOID            *Context\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Notification event handler registered by CoreNotifyOnArchProtocolInstallation ().\r
+  This notify function is registered for every architectural protocol. This handler\r
+  updates mArchProtocol[] array entry with protocol instance data and sets it's\r
+  present flag to TRUE. If any constructor is required it is executed. The EFI\r
+  System Table headers are updated.\r
+\r
+Arguments:\r
+\r
+  Event   - The Event that is being processed, not used.\r
+\r
+  Context - Event Context, not used.\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                      Status;\r
+  ARCHITECTURAL_PROTOCOL_ENTRY    *Entry;\r
+  VOID                            *Protocol;\r
+  BOOLEAN                         Found;\r
+  LIST_ENTRY                      *Link;\r
+  LIST_ENTRY                      TempLinkNode;\r
+\r
+  Found = FALSE;\r
+  for (Entry = mArchProtocols; Entry->ProtocolGuid != NULL; Entry++) {\r
+\r
+    Status = CoreLocateProtocol (Entry->ProtocolGuid, Entry->Registration, &Protocol);\r
+    if (EFI_ERROR (Status)) {\r
+      continue;\r
+    }\r
+\r
+    Found = TRUE;\r
+    Entry->Present = TRUE;\r
+\r
+    //\r
+    // Update protocol global variable if one exists. Entry->Protocol points to a global variable\r
+    // if one exists in the DXE core for this Architectural Protocol\r
+    //\r
+    if (Entry->Protocol != NULL) {\r
+      *(Entry->Protocol) = Protocol;\r
+    }\r
+\r
+    if (CompareGuid (Entry->ProtocolGuid, &gEfiTimerArchProtocolGuid)) {\r
+      //\r
+      // Register the Core timer tick handler with the Timer AP\r
+      //\r
+      gTimer->RegisterHandler (gTimer, CoreTimerTick);\r
+    }\r
+\r
+    if (CompareGuid (Entry->ProtocolGuid, &gEfiRuntimeArchProtocolGuid)) {\r
+      //\r
+      // When runtime architectural protocol is available, updates CRC32 in the Debug Table\r
+      //\r
+      CoreUpdateDebugTableCrc32 ();\r
+\r
+      //\r
+      // Update the Runtime Architectural protocol with the template that the core was\r
+      // using so there would not need to be a dependency on the Runtime AP\r
+      //\r
+\r
+      //\r
+      // Copy all the registered Image to new gRuntime protocol\r
+      //\r
+      for (Link = gRuntimeTemplate.ImageHead.ForwardLink; Link != &gRuntimeTemplate.ImageHead; Link = TempLinkNode.ForwardLink) {\r
+        CopyMem (&TempLinkNode, Link, sizeof(LIST_ENTRY));\r
+        InsertTailList (&gRuntime->ImageHead, Link);\r
+      }\r
+      //\r
+      // Copy all the registered Event to new gRuntime protocol\r
+      //\r
+      for (Link = gRuntimeTemplate.EventHead.ForwardLink; Link != &gRuntimeTemplate.EventHead; Link = TempLinkNode.ForwardLink) {\r
+        CopyMem (&TempLinkNode, Link, sizeof(LIST_ENTRY));\r
+        InsertTailList (&gRuntime->EventHead, Link);\r
+      }\r
+\r
+      //\r
+      // Clean up gRuntimeTemplate\r
+      //\r
+      gRuntimeTemplate.ImageHead.ForwardLink = &gRuntimeTemplate.ImageHead;\r
+      gRuntimeTemplate.ImageHead.BackLink    = &gRuntimeTemplate.ImageHead;\r
+      gRuntimeTemplate.EventHead.ForwardLink = &gRuntimeTemplate.EventHead;\r
+      gRuntimeTemplate.EventHead.BackLink    = &gRuntimeTemplate.EventHead;\r
+    }\r
+  }\r
+\r
+  //\r
+  // It's over kill to do them all every time, but it saves a lot of code.\r
+  //\r
+  if (Found) {\r
+    CalculateEfiHdrCrc (&gDxeCoreRT->Hdr);\r
+    CalculateEfiHdrCrc (&gDxeCoreBS->Hdr);\r
+    CalculateEfiHdrCrc (&gDxeCoreST->Hdr);\r
+    CalculateEfiHdrCrc (&gDxeCoreDS->Hdr);\r
+  }\r
+}\r
+\r
+\r
+\r
+VOID\r
+CoreNotifyOnArchProtocolInstallation (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Creates an event that is fired everytime a Protocol of a specific type is installed\r
+\r
+Arguments:\r
+  NONE\r
+\r
+Returns:\r
+  NONE\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                      Status;\r
+  ARCHITECTURAL_PROTOCOL_ENTRY    *Entry;\r
+\r
+  for (Entry = mArchProtocols; Entry->ProtocolGuid != NULL; Entry++) {\r
+\r
+    //\r
+    // Create the event\r
+    //\r
+    Status = CoreCreateEvent (\r
+              EVT_NOTIFY_SIGNAL,\r
+              TPL_CALLBACK,\r
+              GenericArchProtocolNotify,\r
+              NULL,\r
+              &Entry->Event\r
+              );\r
+    ASSERT_EFI_ERROR(Status);\r
+\r
+    //\r
+    // Register for protocol notifactions on this event\r
+    //\r
+    Status = CoreRegisterProtocolNotify (\r
+              Entry->ProtocolGuid,\r
+              Entry->Event,\r
+              &Entry->Registration\r
+              );\r
+    ASSERT_EFI_ERROR(Status);\r
+\r
+  }\r
+}\r
+\r
+//\r
+// Following is needed to display missing architectural protocols in debug builds\r
+//\r
+typedef struct {\r
+  EFI_GUID                    *ProtocolGuid;\r
+  CHAR16                       *GuidString;\r
+} GUID_TO_STRING_PROTOCOL_ENTRY;\r
+\r
+static const GUID_TO_STRING_PROTOCOL_ENTRY MissingProtocols[] = {\r
+  { &gEfiSecurityArchProtocolGuid,         (CHAR16 *)L"Security"           },\r
+  { &gEfiCpuArchProtocolGuid,              (CHAR16 *)L"CPU"                },\r
+  { &gEfiMetronomeArchProtocolGuid,        (CHAR16 *)L"Metronome"          },\r
+  { &gEfiTimerArchProtocolGuid,            (CHAR16 *)L"Timer"              },\r
+  { &gEfiBdsArchProtocolGuid,              (CHAR16 *)L"Bds"                },\r
+  { &gEfiWatchdogTimerArchProtocolGuid,    (CHAR16 *)L"Watchdog Timer"     },\r
+  { &gEfiRuntimeArchProtocolGuid,          (CHAR16 *)L"Runtime"            },\r
+  { &gEfiVariableArchProtocolGuid,         (CHAR16 *)L"Variable"           },\r
+  { &gEfiVariableWriteArchProtocolGuid,    (CHAR16 *)L"Variable Write"     },\r
+  { &gEfiCapsuleArchProtocolGuid,          (CHAR16 *)L"Capsule"            },\r
+  { &gEfiMonotonicCounterArchProtocolGuid, (CHAR16 *)L"Monotonic Counter"  },\r
+  { &gEfiResetArchProtocolGuid,            (CHAR16 *)L"Reset"              },\r
+//  { &gEfiStatusCodeRuntimeProtocolGuid,       (CHAR16 *)L"Status Code"        },\r
+  { &gEfiRealTimeClockArchProtocolGuid,    (CHAR16 *)L"Real Time Clock"    }\r
+};\r
+\r
+VOID\r
+CoreDisplayMissingArchProtocols (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Displays Architectural protocols that were not loaded and are required for DXE core to function\r
+  Only used in Debug Builds\r
+\r
+Arguments:\r
+  NONE\r
+\r
+Returns:\r
+  NONE\r
+\r
+--*/\r
+{\r
+  const GUID_TO_STRING_PROTOCOL_ENTRY  *MissingEntry;\r
+  ARCHITECTURAL_PROTOCOL_ENTRY         *Entry;\r
+\r
+  for (Entry = mArchProtocols; Entry->ProtocolGuid != NULL; Entry++) {\r
+    if (!Entry->Present) {\r
+      MissingEntry = MissingProtocols;\r
+      for (MissingEntry = MissingProtocols; TRUE ; MissingEntry++) {\r
+        if (CompareGuid (Entry->ProtocolGuid, MissingEntry->ProtocolGuid)) {\r
+          DEBUG ((EFI_D_ERROR, "\n%s Arch Protocol not present!!\n", MissingEntry->GuidString));\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Event/event.c b/MdeModulePkg/Core/Dxe/Event/event.c
new file mode 100644 (file)
index 0000000..b3ba71d
--- /dev/null
@@ -0,0 +1,757 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+    event.c\r
+\r
+Abstract:\r
+\r
+    EFI Event support\r
+\r
+--*/\r
+\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// Enumerate the valid types\r
+//\r
+UINT32 mEventTable[] = {\r
+  //\r
+  // 0x80000200       Timer event with a notification function that is\r
+  // queue when the event is signaled with SignalEvent()\r
+  //\r
+  EVT_TIMER | EVT_NOTIFY_SIGNAL,\r
+  //\r
+  // 0x80000000       Timer event without a notification function. It can be\r
+  // signaled with SignalEvent() and checked with CheckEvent() or WaitForEvent().\r
+  //\r
+  EVT_TIMER,\r
+  //\r
+  // 0x00000100       Generic event with a notification function that\r
+  // can be waited on with CheckEvent() or WaitForEvent()\r
+  //\r
+  EVT_NOTIFY_WAIT,\r
+  //\r
+  // 0x00000200       Generic event with a notification function that\r
+  // is queue when the event is signaled with SignalEvent()\r
+  //\r
+  EVT_NOTIFY_SIGNAL,\r
+  //\r
+  // 0x00000201       ExitBootServicesEvent.\r
+  //\r
+  EVT_SIGNAL_EXIT_BOOT_SERVICES,\r
+  //\r
+  // 0x60000202       SetVirtualAddressMapEvent.\r
+  //\r
+  EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE,\r
+\r
+  //\r
+  // 0x00000000       Generic event without a notification function.\r
+  // It can be signaled with SignalEvent() and checked with CheckEvent()\r
+  // or WaitForEvent().\r
+  //\r
+  0x00000000,\r
+  //\r
+  // 0x80000100       Timer event with a notification function that can be\r
+  // waited on with CheckEvent() or WaitForEvent()\r
+  //\r
+  EVT_TIMER | EVT_NOTIFY_WAIT,\r
+};\r
+\r
+STATIC\r
+VOID\r
+CoreAcquireEventLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Enter critical section by acquiring the lock on gEventQueueLock.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreAcquireLock (&gEventQueueLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreReleaseEventLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Exit critical section by releasing the lock on gEventQueueLock.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&gEventQueueLock);\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreInitializeEventServices (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initializes "event" support and populates parts of the System and Runtime Table.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - Always return success\r
+\r
+--*/\r
+{\r
+  UINTN        Index;\r
+\r
+  for (Index=0; Index <= TPL_HIGH_LEVEL; Index++) {\r
+    InitializeListHead (&gEventQueue[Index]);\r
+  }\r
+\r
+  CoreInitializeTimer ();\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+VOID\r
+CoreDispatchEventNotifies (\r
+  IN EFI_TPL      Priority\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Dispatches all pending events.\r
+\r
+Arguments:\r
+\r
+  Priority - The task priority level of event notifications to dispatch\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  IEVENT          *Event;\r
+  LIST_ENTRY      *Head;\r
+\r
+  CoreAcquireEventLock ();\r
+  ASSERT (gEventQueueLock.OwnerTpl == Priority);\r
+  Head = &gEventQueue[Priority];\r
+\r
+  //\r
+  // Dispatch all the pending notifications\r
+  //\r
+  while (!IsListEmpty (Head)) {\r
+\r
+    Event = CR (Head->ForwardLink, IEVENT, NotifyLink, EVENT_SIGNATURE);\r
+    RemoveEntryList (&Event->NotifyLink);\r
+\r
+    Event->NotifyLink.ForwardLink = NULL;\r
+\r
+    //\r
+    // Only clear the SIGNAL status if it is a SIGNAL type event.\r
+    // WAIT type events are only cleared in CheckEvent()\r
+    //\r
+    if (Event->Type & EVT_NOTIFY_SIGNAL) {\r
+      Event->SignalCount = 0;\r
+    }\r
+\r
+    CoreReleaseEventLock ();\r
+\r
+    //\r
+    // Notify this event\r
+    //\r
+    ASSERT (Event->NotifyFunction != NULL);\r
+    Event->NotifyFunction (Event, Event->NotifyContext);\r
+\r
+    //\r
+    // Check for next pending event\r
+    //\r
+    CoreAcquireEventLock ();\r
+  }\r
+\r
+  gEventPending &= ~(1 << Priority);\r
+  CoreReleaseEventLock ();\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+CoreNotifyEvent (\r
+  IN  IEVENT      *Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Queues the event's notification function to fire\r
+\r
+Arguments:\r
+\r
+  Event       - The Event to notify\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+\r
+  //\r
+  // Event database must be locked\r
+  //\r
+  ASSERT_LOCKED (&gEventQueueLock);\r
+\r
+  //\r
+  // If the event is queued somewhere, remove it\r
+  //\r
+\r
+  if (Event->NotifyLink.ForwardLink != NULL) {\r
+    RemoveEntryList (&Event->NotifyLink);\r
+    Event->NotifyLink.ForwardLink = NULL;\r
+  }\r
+\r
+  //\r
+  // Queue the event to the pending notification list\r
+  //\r
+\r
+  InsertTailList (&gEventQueue[Event->NotifyTpl], &Event->NotifyLink);\r
+  gEventPending |= (UINTN)(1 << Event->NotifyTpl);\r
+}\r
+\r
+\r
+\r
+VOID\r
+CoreNotifySignalList (\r
+  IN EFI_GUID     *EventGroup\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Signals all events in the EventGroup\r
+\r
+Arguments:\r
+  EventGroup - The list to signal\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY              *Link;\r
+  LIST_ENTRY              *Head;\r
+  IEVENT                  *Event;\r
+\r
+  CoreAcquireEventLock ();\r
+\r
+  Head = &gEventSignalQueue;\r
+  for (Link = Head->ForwardLink; Link != Head; Link = Link->ForwardLink) {\r
+    Event = CR (Link, IEVENT, SignalLink, EVENT_SIGNATURE);\r
+    if (CompareGuid (&Event->EventGroup, EventGroup)) {\r
+      CoreNotifyEvent (Event);\r
+    }\r
+  }\r
+\r
+  CoreReleaseEventLock ();\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCreateEvent (\r
+  IN UINT32                   Type,\r
+  IN EFI_TPL                  NotifyTpl,\r
+  IN EFI_EVENT_NOTIFY         NotifyFunction, OPTIONAL\r
+  IN VOID                     *NotifyContext, OPTIONAL\r
+  OUT EFI_EVENT               *Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Creates a general-purpose event structure\r
+\r
+Arguments:\r
+  Type                - The type of event to create and its mode and attributes\r
+  NotifyTpl           - The task priority level of event notifications\r
+  NotifyFunction      - Pointer to the events notification function\r
+  NotifyContext       - Pointer to the notification functions context; corresponds to\r
+                        parameter "Context" in the notification function\r
+  Event               - Pointer to the newly created event if the call succeeds; undefined otherwise\r
+\r
+Returns:\r
+  EFI_SUCCESS           - The event structure was created\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value\r
+  EFI_OUT_OF_RESOURCES  - The event could not be allocated\r
+\r
+--*/\r
+{\r
+  EFI_GUID            *GuidPtr;\r
+  EFI_EVENT_NOTIFY    Function;\r
+\r
+  GuidPtr = NULL;\r
+  Function = NotifyFunction;\r
+\r
+  //\r
+  // Convert EFI 1.10 Events to thier UEFI 2.0 CreateEventEx mapping\r
+  //\r
+  if (Type == EVT_SIGNAL_EXIT_BOOT_SERVICES) {\r
+    GuidPtr = &gEfiEventExitBootServicesGuid;\r
+  } else if (Type == EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE) {\r
+    GuidPtr = &gEfiEventVirtualAddressChangeGuid;\r
+  }\r
+\r
+  return CoreCreateEventEx (Type, NotifyTpl, Function, NotifyContext, GuidPtr, Event);\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCreateEventEx (\r
+  IN UINT32                   Type,\r
+  IN EFI_TPL                  NotifyTpl,\r
+  IN EFI_EVENT_NOTIFY         NotifyFunction, OPTIONAL\r
+  IN CONST VOID               *NotifyContext, OPTIONAL\r
+  IN CONST EFI_GUID           *EventGroup,    OPTIONAL\r
+  OUT EFI_EVENT               *Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Creates a general-purpose event structure\r
+\r
+Arguments:\r
+  Type                - The type of event to create and its mode and attributes\r
+  NotifyTpl           - The task priority level of event notifications\r
+  NotifyFunction      - Pointer to the events notification function\r
+  NotifyContext       - Pointer to the notification functions context; corresponds to\r
+                        parameter "Context" in the notification function\r
+  EventGrout          - GUID for EventGroup if NULL act the same as gBS->CreateEvent().\r
+  Event               - Pointer to the newly created event if the call succeeds; undefined otherwise\r
+\r
+Returns:\r
+  EFI_SUCCESS           - The event structure was created\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value\r
+  EFI_OUT_OF_RESOURCES  - The event could not be allocated\r
+\r
+--*/\r
+{\r
+  EFI_STATUS      Status;\r
+  IEVENT          *IEvent;\r
+  INTN            Index;\r
+\r
+\r
+  if ((Event == NULL) || (NotifyTpl == TPL_APPLICATION)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Check to make sure no reserved flags are set\r
+  //\r
+  Status = EFI_INVALID_PARAMETER;\r
+  for (Index = 0; Index < (sizeof (mEventTable) / sizeof (UINT32)); Index++) {\r
+     if (Type == mEventTable[Index]) {\r
+       Status = EFI_SUCCESS;\r
+       break;\r
+     }\r
+  }\r
+  if(EFI_ERROR (Status)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // If it's a notify type of event, check its parameters\r
+  //\r
+  if ((Type & (EVT_NOTIFY_WAIT | EVT_NOTIFY_SIGNAL))) {\r
+    //\r
+    // Check for an invalid NotifyFunction or NotifyTpl\r
+    //\r
+    if ((NotifyFunction == NULL) ||\r
+        (NotifyTpl < TPL_APPLICATION) ||\r
+       (NotifyTpl >= TPL_HIGH_LEVEL)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+\r
+  } else {\r
+    //\r
+    // No notification needed, zero ignored values\r
+    //\r
+    NotifyTpl = 0;\r
+    NotifyFunction = NULL;\r
+    NotifyContext = NULL;\r
+  }\r
+\r
+  //\r
+  // Allcoate and initialize a new event structure.\r
+  //\r
+  Status = CoreAllocatePool (\r
+             (Type & EVT_RUNTIME) ? EfiRuntimeServicesData: EfiBootServicesData,\r
+             sizeof (IEVENT),\r
+             (VOID **)&IEvent\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  SetMem (IEvent, sizeof (IEVENT), 0);\r
+\r
+  IEvent->Signature = EVENT_SIGNATURE;\r
+  IEvent->Type = Type;\r
+\r
+  IEvent->NotifyTpl      = NotifyTpl;\r
+  IEvent->NotifyFunction = NotifyFunction;\r
+  IEvent->NotifyContext  = (VOID *)NotifyContext;\r
+  if (EventGroup != NULL) {\r
+    CopyGuid (&IEvent->EventGroup, EventGroup);\r
+    IEvent->ExFlag = TRUE;\r
+  }\r
+\r
+  *Event = IEvent;\r
+\r
+  if (Type & EVT_RUNTIME) {\r
+    //\r
+    // Keep a list of all RT events so we can tell the RT AP.\r
+    //\r
+    IEvent->RuntimeData.Type           = Type;\r
+    IEvent->RuntimeData.NotifyTpl      = NotifyTpl;\r
+    IEvent->RuntimeData.NotifyFunction = NotifyFunction;\r
+    IEvent->RuntimeData.NotifyContext  = (VOID *) NotifyContext;\r
+    IEvent->RuntimeData.Event          = (EFI_EVENT *) IEvent;\r
+    InsertTailList (&gRuntime->EventHead, &IEvent->RuntimeData.Link);\r
+  }\r
+\r
+  CoreAcquireEventLock ();\r
+\r
+  if ((Type & EVT_NOTIFY_SIGNAL) != 0x00000000) {\r
+    //\r
+    // The Event's NotifyFunction must be queued whenever the event is signaled\r
+    //\r
+    InsertHeadList (&gEventSignalQueue, &IEvent->SignalLink);\r
+  }\r
+\r
+  CoreReleaseEventLock ();\r
+\r
+  //\r
+  // Done\r
+  //\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSignalEvent (\r
+  IN EFI_EVENT    UserEvent\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Signals the event.  Queues the event to be notified if needed\r
+\r
+Arguments:\r
+\r
+  UserEvent - The event to signal\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER - Parameters are not valid.\r
+\r
+  EFI_SUCCESS - The event was signaled.\r
+\r
+--*/\r
+{\r
+  IEVENT          *Event;\r
+\r
+  Event = UserEvent;\r
+\r
+  if (Event == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Event->Signature != EVENT_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireEventLock ();\r
+\r
+  //\r
+  // If the event is not already signalled, do so\r
+  //\r
+\r
+  if (Event->SignalCount == 0x00000000) {\r
+    Event->SignalCount++;\r
+\r
+    //\r
+    // If signalling type is a notify function, queue it\r
+    //\r
+    if (Event->Type & EVT_NOTIFY_SIGNAL) {\r
+      if (Event->ExFlag) {\r
+        //\r
+        // The CreateEventEx() style requires all members of the Event Group\r
+        //  to be signaled.\r
+        //\r
+        CoreReleaseEventLock ();\r
+        CoreNotifySignalList (&Event->EventGroup);\r
+        CoreAcquireEventLock ();\r
+       } else {\r
+        CoreNotifyEvent (Event);\r
+      }\r
+    }\r
+  }\r
+\r
+  CoreReleaseEventLock ();\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCheckEvent (\r
+  IN EFI_EVENT        UserEvent\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check the status of an event\r
+\r
+Arguments:\r
+\r
+  UserEvent - The event to check\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event is in the signaled state\r
+  EFI_NOT_READY         - The event is not in the signaled state\r
+  EFI_INVALID_PARAMETER - Event is of type EVT_NOTIFY_SIGNAL\r
+\r
+--*/\r
+\r
+{\r
+  IEVENT      *Event;\r
+  EFI_STATUS  Status;\r
+\r
+  Event = UserEvent;\r
+\r
+  if (Event == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Event->Signature != EVENT_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Event->Type & EVT_NOTIFY_SIGNAL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Status = EFI_NOT_READY;\r
+\r
+  if (!Event->SignalCount && (Event->Type & EVT_NOTIFY_WAIT)) {\r
+\r
+    //\r
+    // Queue the wait notify function\r
+    //\r
+\r
+    CoreAcquireEventLock ();\r
+    if (!Event->SignalCount) {\r
+      CoreNotifyEvent (Event);\r
+    }\r
+    CoreReleaseEventLock ();\r
+  }\r
+\r
+  //\r
+  // If the even looks signalled, get the lock and clear it\r
+  //\r
+\r
+  if (Event->SignalCount) {\r
+    CoreAcquireEventLock ();\r
+\r
+    if (Event->SignalCount) {\r
+      Event->SignalCount = 0;\r
+      Status = EFI_SUCCESS;\r
+    }\r
+\r
+    CoreReleaseEventLock ();\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreWaitForEvent (\r
+  IN UINTN        NumberOfEvents,\r
+  IN EFI_EVENT    *UserEvents,\r
+  OUT UINTN       *UserIndex\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Stops execution until an event is signaled.\r
+\r
+Arguments:\r
+\r
+  NumberOfEvents  - The number of events in the UserEvents array\r
+  UserEvents      - An array of EFI_EVENT\r
+  UserIndex       - Pointer to the index of the event which satisfied the wait condition\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event indicated by Index was signaled.\r
+  EFI_INVALID_PARAMETER - The event indicated by Index has a notification function or\r
+                          Event was not a valid type\r
+  EFI_UNSUPPORTED       - The current TPL is not TPL_APPLICATION\r
+\r
+--*/\r
+\r
+{\r
+  EFI_STATUS      Status;\r
+  UINTN           Index;\r
+\r
+  //\r
+  // Can only WaitForEvent at TPL_APPLICATION\r
+  //\r
+  if (gEfiCurrentTpl != TPL_APPLICATION) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  for(;;) {\r
+\r
+    for(Index = 0; Index < NumberOfEvents; Index++) {\r
+\r
+      Status = CoreCheckEvent (UserEvents[Index]);\r
+\r
+      //\r
+      // provide index of event that caused problem\r
+      //\r
+      if (Status != EFI_NOT_READY) {\r
+        *UserIndex = Index;\r
+        return Status;\r
+      }\r
+    }\r
+\r
+    //\r
+    // This was the location of the Idle loop callback in EFI 1.x reference\r
+    // code. We don't have that concept in this base at this point.\r
+    //\r
+  }\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCloseEvent (\r
+  IN EFI_EVENT    UserEvent\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Closes an event and frees the event structure.\r
+\r
+Arguments:\r
+\r
+  UserEvent - Event to close\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER - Parameters are not valid.\r
+\r
+  EFI_SUCCESS - The event has been closed\r
+\r
+--*/\r
+\r
+{\r
+  EFI_STATUS  Status;\r
+  IEVENT      *Event;\r
+\r
+  Event = UserEvent;\r
+\r
+  if (Event == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Event->Signature != EVENT_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // If it's a timer event, make sure it's not pending\r
+  //\r
+  if (Event->Type & EVT_TIMER) {\r
+    CoreSetTimer (Event, TimerCancel, 0);\r
+  }\r
+\r
+  CoreAcquireEventLock ();\r
+\r
+  //\r
+  // If the event is queued somewhere, remove it\r
+  //\r
+\r
+  if (Event->RuntimeData.Link.ForwardLink != NULL) {\r
+    RemoveEntryList (&Event->RuntimeData.Link);\r
+  }\r
+\r
+  if (Event->NotifyLink.ForwardLink != NULL) {\r
+    RemoveEntryList (&Event->NotifyLink);\r
+  }\r
+\r
+  if (Event->SignalLink.ForwardLink != NULL) {\r
+    RemoveEntryList (&Event->SignalLink);\r
+  }\r
+\r
+  CoreReleaseEventLock ();\r
+\r
+  //\r
+  // If the event is registered on a protocol notify, then remove it from the protocol database\r
+  //\r
+  CoreUnregisterProtocolNotify (Event);\r
+\r
+  Status = CoreFreePool (Event);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  return Status;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Event/execdata.c b/MdeModulePkg/Core/Dxe/Event/execdata.c
new file mode 100644 (file)
index 0000000..a6d388a
--- /dev/null
@@ -0,0 +1,51 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+  \r
+  execdata.c\r
+\r
+Abstract:\r
+\r
+\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+//\r
+// gTpl - Task priority level\r
+//\r
+EFI_TPL  gEfiCurrentTpl = TPL_APPLICATION;\r
+\r
+\r
+//\r
+// gEventQueueLock - Protects the event queus\r
+//\r
+EFI_LOCK gEventQueueLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL);\r
+\r
+//\r
+// gEventQueue - A list of event's to notify for each priority level\r
+// gEventPending - A bitmask of the EventQueues that are pending\r
+//\r
+LIST_ENTRY      gEventQueue[TPL_HIGH_LEVEL + 1];\r
+UINTN           gEventPending = 0;\r
+\r
+\r
+//\r
+// gEventSignalQueue - A list of events to signal based on EventGroup type\r
+//\r
+LIST_ENTRY      gEventSignalQueue = INITIALIZE_LIST_HEAD_VARIABLE (gEventSignalQueue);\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Event/timer.c b/MdeModulePkg/Core/Dxe/Event/timer.c
new file mode 100644 (file)
index 0000000..0f886f9
--- /dev/null
@@ -0,0 +1,388 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  timer.c\r
+\r
+Abstract:\r
+\r
+  EFI Event support\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// Internal prototypes\r
+//\r
+STATIC\r
+UINT64\r
+CoreCurrentSystemTime (\r
+  VOID\r
+  );\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+CoreCheckTimers (\r
+  IN EFI_EVENT    Event,\r
+  IN VOID         *Context\r
+  );\r
+\r
+STATIC\r
+VOID\r
+CoreInsertEventTimer (\r
+  IN IEVENT       *Event\r
+  );\r
+\r
+//\r
+// Internal data\r
+//\r
+\r
+static LIST_ENTRY       mEfiTimerList = INITIALIZE_LIST_HEAD_VARIABLE (mEfiTimerList);\r
+static EFI_LOCK         mEfiTimerLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL - 1);\r
+static EFI_EVENT        mEfiCheckTimerEvent;\r
+\r
+static EFI_LOCK         mEfiSystemTimeLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL);\r
+static UINT64           mEfiSystemTime = 0;\r
+\r
+//\r
+// Timer functions\r
+//\r
+\r
+VOID\r
+CoreInitializeTimer (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initializes timer support\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = CoreCreateEvent (\r
+              EVT_NOTIFY_SIGNAL,\r
+              TPL_HIGH_LEVEL - 1,\r
+              CoreCheckTimers,\r
+              NULL,\r
+              &mEfiCheckTimerEvent\r
+              );\r
+  ASSERT_EFI_ERROR (Status);\r
+}\r
+\r
+STATIC\r
+UINT64\r
+CoreCurrentSystemTime (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Returns the current system time\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  Returns the current system time\r
+\r
+--*/\r
+{\r
+  UINT64          SystemTime;\r
+\r
+  CoreAcquireLock (&mEfiSystemTimeLock);\r
+  SystemTime = mEfiSystemTime;\r
+  CoreReleaseLock (&mEfiSystemTimeLock);\r
+  return SystemTime;\r
+}\r
+\r
+VOID\r
+EFIAPI\r
+CoreTimerTick (\r
+  IN UINT64   Duration\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called by the platform code to process a tick.\r
+\r
+Arguments:\r
+\r
+  Duration    - The number of 100ns elasped since the last call to TimerTick\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  IEVENT          *Event;\r
+\r
+  //\r
+  // Check runtiem flag in case there are ticks while exiting boot services\r
+  //\r
+\r
+  CoreAcquireLock (&mEfiSystemTimeLock);\r
+\r
+  //\r
+  // Update the system time\r
+  //\r
+\r
+  mEfiSystemTime += Duration;\r
+\r
+  //\r
+  // If the head of the list is expired, fire the timer event\r
+  // to process it\r
+  //\r
+\r
+  if (!IsListEmpty (&mEfiTimerList)) {\r
+    Event = CR (mEfiTimerList.ForwardLink, IEVENT, u.Timer.Link, EVENT_SIGNATURE);\r
+\r
+    if (Event->u.Timer.TriggerTime <= mEfiSystemTime) {\r
+      CoreSignalEvent (mEfiCheckTimerEvent);\r
+    }\r
+  }\r
+\r
+  CoreReleaseLock (&mEfiSystemTimeLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+CoreCheckTimers (\r
+  IN EFI_EVENT            CheckEvent,\r
+  IN VOID                 *Context\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Checks the sorted timer list against the current system time.\r
+  Signals any expired event timer.\r
+\r
+Arguments:\r
+\r
+  CheckEvent  - Not used\r
+\r
+  Context     - Not used\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  UINT64                  SystemTime;\r
+  IEVENT                  *Event;\r
+\r
+  //\r
+  // Check the timer database for expired timers\r
+  //\r
+\r
+  CoreAcquireLock (&mEfiTimerLock);\r
+  SystemTime = CoreCurrentSystemTime ();\r
+\r
+  while (!IsListEmpty (&mEfiTimerList)) {\r
+    Event = CR (mEfiTimerList.ForwardLink, IEVENT, u.Timer.Link, EVENT_SIGNATURE);\r
+\r
+    //\r
+    // If this timer is not expired, then we're done\r
+    //\r
+\r
+    if (Event->u.Timer.TriggerTime > SystemTime) {\r
+      break;\r
+    }\r
+\r
+    //\r
+    // Remove this timer from the timer queue\r
+    //\r
+\r
+    RemoveEntryList (&Event->u.Timer.Link);\r
+    Event->u.Timer.Link.ForwardLink = NULL;\r
+\r
+    //\r
+    // Signal it\r
+    //\r
+    CoreSignalEvent (Event);\r
+\r
+    //\r
+    // If this is a periodic timer, set it\r
+    //\r
+    if (Event->u.Timer.Period) {\r
+\r
+      //\r
+      // Compute the timers new trigger time\r
+      //\r
+\r
+      Event->u.Timer.TriggerTime = Event->u.Timer.TriggerTime + Event->u.Timer.Period;\r
+\r
+      //\r
+      // If that's before now, then reset the timer to start from now\r
+      //\r
+      if (Event->u.Timer.TriggerTime <= SystemTime) {\r
+        Event->u.Timer.TriggerTime = SystemTime;\r
+        CoreSignalEvent (mEfiCheckTimerEvent);\r
+      }\r
+\r
+      //\r
+      // Add the timer\r
+      //\r
+\r
+      CoreInsertEventTimer (Event);\r
+    }\r
+  }\r
+\r
+  CoreReleaseLock (&mEfiTimerLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreInsertEventTimer (\r
+  IN IEVENT   *Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Inserts the timer event\r
+\r
+Arguments:\r
+\r
+  Event - Points to the internal structure of timer event to be installed\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  UINT64          TriggerTime;\r
+  LIST_ENTRY      *Link;\r
+  IEVENT          *Event2;\r
+\r
+  ASSERT_LOCKED (&mEfiTimerLock);\r
+\r
+  //\r
+  // Get the timer's trigger time\r
+  //\r
+\r
+  TriggerTime = Event->u.Timer.TriggerTime;\r
+\r
+  //\r
+  // Insert the timer into the timer database in assending sorted order\r
+  //\r
+\r
+  for (Link = mEfiTimerList.ForwardLink; Link  != &mEfiTimerList; Link = Link->ForwardLink) {\r
+    Event2 = CR (Link, IEVENT, u.Timer.Link, EVENT_SIGNATURE);\r
+\r
+    if (Event2->u.Timer.TriggerTime > TriggerTime) {\r
+      break;\r
+    }\r
+  }\r
+\r
+  InsertTailList (Link, &Event->u.Timer.Link);\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSetTimer (\r
+  IN EFI_EVENT            UserEvent,\r
+  IN EFI_TIMER_DELAY      Type,\r
+  IN UINT64               TriggerTime\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Sets the type of timer and the trigger time for a timer event.\r
+\r
+Arguments:\r
+\r
+  UserEvent   - The timer event that is to be signaled at the specified time\r
+  Type        - The type of time that is specified in TriggerTime\r
+  TriggerTime - The number of 100ns units until the timer expires\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The event has been set to be signaled at the requested time\r
+  EFI_INVALID_PARAMETER - Event or Type is not valid\r
+\r
+--*/\r
+{\r
+  IEVENT      *Event;\r
+\r
+  Event = UserEvent;\r
+\r
+  if (Event == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Event->Signature != EVENT_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Type < 0 || Type > TimerRelative  || !(Event->Type & EVT_TIMER)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireLock (&mEfiTimerLock);\r
+\r
+  //\r
+  // If the timer is queued to the timer database, remove it\r
+  //\r
+\r
+  if (Event->u.Timer.Link.ForwardLink != NULL) {\r
+    RemoveEntryList (&Event->u.Timer.Link);\r
+    Event->u.Timer.Link.ForwardLink = NULL;\r
+  }\r
+\r
+  Event->u.Timer.TriggerTime = 0;\r
+  Event->u.Timer.Period = 0;\r
+\r
+  if (Type != TimerCancel) {\r
+\r
+    if (Type == TimerPeriodic) {\r
+      Event->u.Timer.Period = TriggerTime;\r
+    }\r
+\r
+    Event->u.Timer.TriggerTime = CoreCurrentSystemTime () + TriggerTime;\r
+    CoreInsertEventTimer (Event);\r
+\r
+    if (TriggerTime == 0) {\r
+      CoreSignalEvent (mEfiCheckTimerEvent);\r
+    }\r
+  }\r
+\r
+  CoreReleaseLock (&mEfiTimerLock);\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Event/tpl.c b/MdeModulePkg/Core/Dxe/Event/tpl.c
new file mode 100644 (file)
index 0000000..437665f
--- /dev/null
@@ -0,0 +1,198 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+    tpl.c\r
+\r
+Abstract:\r
+\r
+    Task priority function    \r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+STATIC\r
+VOID\r
+CoreSetInterruptState (\r
+  IN BOOLEAN      Enable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  \r
+  Set Interrupt State\r
+  \r
+Arguments:\r
+  \r
+  Enable - The state of enable or disable interrupt\r
+  \r
+Returns:\r
+  \r
+  None\r
+\r
+--*/\r
+\r
+{\r
+  if (gCpu != NULL) {\r
+    if (Enable) {\r
+      gCpu->EnableInterrupt(gCpu);\r
+    } else {\r
+      gCpu->DisableInterrupt(gCpu);\r
+    }\r
+  }\r
+}\r
+\r
+//\r
+// Return the highest set bit\r
+//\r
+UINTN\r
+CoreHighestSetBit (\r
+  IN UINTN     Number\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  \r
+  Return the highest set bit\r
+  \r
+Arguments:\r
+  \r
+  Number - The value to check\r
+  \r
+Returns:\r
+  \r
+  Bit position of the highest set bit\r
+\r
+--*/\r
+{\r
+  UINTN   msb;\r
+  \r
+  msb = 31;\r
+  while ((msb > 0) && ((Number & (UINTN)(1 << msb)) == 0)) {\r
+    msb--;\r
+  }\r
+\r
+  return msb;\r
+}\r
+\r
+\r
+\r
+EFI_TPL\r
+EFIAPI\r
+CoreRaiseTpl (\r
+  IN EFI_TPL      NewTpl\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Raise the task priority level to the new level.\r
+  High level is implemented by disabling processor interrupts.\r
+\r
+Arguments:\r
+\r
+  NewTpl  - New task priority level\r
+    \r
+Returns:\r
+\r
+  The previous task priority level\r
+\r
+--*/\r
+{\r
+  EFI_TPL     OldTpl;\r
+\r
+  OldTpl = gEfiCurrentTpl;\r
+  ASSERT (OldTpl <= NewTpl);\r
+  ASSERT (VALID_TPL (NewTpl));\r
+\r
+  //\r
+  // If raising to high level, disable interrupts\r
+  //\r
+  if (NewTpl >= TPL_HIGH_LEVEL  &&  OldTpl < TPL_HIGH_LEVEL) {\r
+    CoreSetInterruptState (FALSE);\r
+  }\r
+\r
+  //\r
+  // Set the new value\r
+  //\r
+  gEfiCurrentTpl = NewTpl;\r
+\r
+  return OldTpl;\r
+}\r
+\r
+\r
+\r
+VOID\r
+EFIAPI\r
+CoreRestoreTpl (\r
+  IN EFI_TPL NewTpl\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Lowers the task priority to the previous value.   If the new \r
+  priority unmasks events at a higher priority, they are dispatched.\r
+\r
+Arguments:\r
+\r
+  NewTpl  - New, lower, task priority\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_TPL     OldTpl;\r
+\r
+  OldTpl = gEfiCurrentTpl;\r
+  ASSERT (NewTpl <= OldTpl);\r
+  ASSERT (VALID_TPL (NewTpl));\r
+\r
+  //\r
+  // If lowering below HIGH_LEVEL, make sure\r
+  // interrupts are enabled\r
+  //\r
+\r
+  if (OldTpl >= TPL_HIGH_LEVEL  &&  NewTpl < TPL_HIGH_LEVEL) {\r
+    gEfiCurrentTpl = TPL_HIGH_LEVEL;  \r
+  }\r
+\r
+  //\r
+  // Dispatch any pending events\r
+  //\r
+\r
+  while ((-2 << NewTpl) & gEventPending) {\r
+    gEfiCurrentTpl = CoreHighestSetBit (gEventPending);\r
+    if (gEfiCurrentTpl < TPL_HIGH_LEVEL) {\r
+      CoreSetInterruptState (TRUE);\r
+    }\r
+    CoreDispatchEventNotifies (gEfiCurrentTpl);\r
+  }\r
+\r
+  //\r
+  // Set the new value\r
+  //\r
+\r
+  gEfiCurrentTpl = NewTpl;\r
+\r
+  //\r
+  // If lowering below HIGH_LEVEL, make sure\r
+  // interrupts are enabled\r
+  //\r
+  if (gEfiCurrentTpl < TPL_HIGH_LEVEL) {\r
+    CoreSetInterruptState (TRUE);\r
+  }\r
+\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Exec.h b/MdeModulePkg/Core/Dxe/Exec.h
new file mode 100644 (file)
index 0000000..5df7001
--- /dev/null
@@ -0,0 +1,208 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+  \r
+  exec.h\r
+\r
+Abstract:\r
+    \r
+  EFI Event support\r
+\r
+--*/\r
+\r
+#ifndef _EXEC_H_\r
+#define _EXEC_H_\r
+\r
+#define VALID_TPL(a)            ((a) <= TPL_HIGH_LEVEL)\r
+\r
+//\r
+// EFI_EVENT\r
+//\r
+\r
+\r
+\r
+#define EVENT_SIGNATURE         EFI_SIGNATURE_32('e','v','n','t')\r
+typedef struct {\r
+  UINTN                   Signature;\r
+  UINT32                  Type;\r
+  UINT32                  SignalCount;\r
+\r
+  //\r
+  // Entry if the event is registered to be signalled\r
+  //\r
+\r
+  LIST_ENTRY              SignalLink;\r
+\r
+  //\r
+  // Notification information for this event\r
+  //\r
+\r
+  EFI_TPL                 NotifyTpl;\r
+  EFI_EVENT_NOTIFY        NotifyFunction;\r
+  VOID                    *NotifyContext;\r
+  EFI_GUID                EventGroup;\r
+  LIST_ENTRY              NotifyLink; \r
+  BOOLEAN                 ExFlag;\r
+  \r
+  //\r
+  // A list of all runtime events\r
+  //\r
+  EFI_RUNTIME_EVENT_ENTRY   RuntimeData;\r
+\r
+  //\r
+  // Information by event type\r
+  //\r
+\r
+  union {\r
+    //\r
+    // For timer events\r
+    //\r
+    struct {\r
+      LIST_ENTRY      Link;\r
+      UINT64          TriggerTime;\r
+      UINT64          Period;\r
+    } Timer;\r
+  } u;\r
+\r
+} IEVENT;    \r
+\r
+//\r
+// Internal prototypes\r
+//\r
+\r
+VOID\r
+CoreDispatchEventNotifies (\r
+  IN EFI_TPL      Priority\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Dispatches all pending events. \r
+\r
+Arguments:\r
+\r
+  Priority - The task priority level of event notifications to dispatch\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+UINTN\r
+CoreHighestSetBit (\r
+  IN UINTN         Number\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  \r
+  Return the highest set bit\r
+  \r
+Arguments:\r
+  \r
+  Number - The value to check\r
+  \r
+Returns:\r
+  \r
+  Bit position of the highest set bit\r
+\r
+--*/\r
+;\r
+\r
+\r
+BOOLEAN\r
+GetInterruptState (\r
+  VOID               \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Disables CPU interrupts.\r
+\r
+Arguments:\r
+\r
+  This                - Protocol instance structure\r
+\r
+  State               - Pointer to the CPU's current interrupt state\r
+\r
+Returns: \r
+\r
+  EFI_SUCCESS           - If interrupts were disabled in the CPU.\r
+\r
+  EFI_INVALID_PARAMETER - State is NULL.\r
+  \r
+--*/\r
+;\r
+\r
+//\r
+// Exported functions\r
+//\r
+\r
+VOID\r
+CoreEventVirtualAddressFixup (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  A function out of date, should be removed.\r
+\r
+Arguments:\r
+\r
+  None\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+VOID\r
+CoreInitializeTimer (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initializes timer support\r
+\r
+Arguments:\r
+\r
+  None\r
+    \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+//\r
+// extern data declarations\r
+//\r
+\r
+extern EFI_LOCK       gEventQueueLock;\r
+extern UINTN          gEventPending;\r
+extern LIST_ENTRY     gEventQueue[];\r
+extern LIST_ENTRY     gEventSignalQueue;\r
+extern UINT8          gHSB[];\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/FwVol/Ffs.c b/MdeModulePkg/Core/Dxe/FwVol/Ffs.c
new file mode 100644 (file)
index 0000000..23c84b3
--- /dev/null
@@ -0,0 +1,266 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  Ffs.c\r
+\r
+Abstract:\r
+\r
+  FFS file access utilities.\r
+\r
+--*/\r
+\r
+\r
+#include <DxeMain.h>\r
+\r
+#define PHYSICAL_ADDRESS_TO_POINTER(Address) ((VOID *)((UINTN)(Address)))\r
+\r
+\r
+EFI_FFS_FILE_STATE\r
+GetFileState (\r
+  IN UINT8                ErasePolarity,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Get the FFS file state by checking the highest bit set in the header's state field\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file header\r
+    \r
+Returns:\r
+  FFS File state \r
+    \r
+--*/\r
+{\r
+  EFI_FFS_FILE_STATE      FileState;\r
+  UINT8                   HighestBit;\r
+\r
+  FileState = FfsHeader->State;\r
+\r
+  if (ErasePolarity != 0) {\r
+    FileState = (EFI_FFS_FILE_STATE)~FileState;\r
+  }\r
+\r
+  HighestBit = 0x80;\r
+  while (HighestBit != 0 && ((HighestBit & FileState) == 0)) {\r
+    HighestBit >>= 1;\r
+  }\r
+\r
+  return (EFI_FFS_FILE_STATE)HighestBit;\r
+}\r
+\r
+\r
+BOOLEAN\r
+IsBufferErased (\r
+  IN UINT8    ErasePolarity,\r
+  IN VOID     *InBuffer,\r
+  IN UINTN    BufferSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if a block of buffer is erased\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  InBuffer      -  The buffer to be checked\r
+  BufferSize    -  Size of the buffer in bytes\r
+    \r
+Returns:\r
+  TRUE  -  The block of buffer is erased\r
+  FALSE -  The block of buffer is not erased\r
+    \r
+--*/\r
+{\r
+  UINTN   Count;\r
+  UINT8   EraseByte;\r
+  UINT8   *Buffer;\r
+\r
+  if(ErasePolarity == 1) {\r
+    EraseByte = 0xFF;\r
+  } else {\r
+    EraseByte = 0;\r
+  }\r
+\r
+  Buffer = InBuffer;\r
+  for (Count = 0; Count < BufferSize; Count++) {\r
+    if (Buffer[Count] != EraseByte) {\r
+      return FALSE;\r
+    }\r
+  }\r
+\r
+  return TRUE;\r
+}\r
+\r
+\r
+BOOLEAN\r
+VerifyFvHeaderChecksum (\r
+  IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Verify checksum of the firmware volume header \r
+\r
+Arguments:\r
+  FvHeader  -  Points to the firmware volume header to be checked\r
+    \r
+Returns:\r
+  TRUE  -  Checksum verification passed\r
+  FALSE -  Checksum verification failed\r
+    \r
+--*/\r
+{\r
+  UINT32  Index;\r
+  UINT32  HeaderLength;\r
+  UINT16  Checksum;\r
+  UINT16  *ptr;\r
+\r
+  HeaderLength = FvHeader->HeaderLength;\r
+  ptr = (UINT16 *)FvHeader;\r
+  Checksum = 0;\r
+\r
+  for (Index = 0; Index < HeaderLength / sizeof (UINT16); Index++) {\r
+    Checksum = (UINT16)(Checksum + ptr[Index]);\r
+  }\r
+\r
+  if (Checksum == 0) {\r
+    return TRUE;\r
+  } else {\r
+    return FALSE;\r
+  }\r
+}\r
+\r
+STATIC\r
+BOOLEAN\r
+VerifyHeaderChecksum (\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Verify checksum of the FFS file header \r
+\r
+Arguments:\r
+  FfsHeader  -  Points to the FFS file header to be checked\r
+    \r
+Returns:\r
+  TRUE  -  Checksum verification passed\r
+  FALSE -  Checksum verification failed\r
+    \r
+--*/\r
+{\r
+  UINT32            Index;\r
+  UINT8             *ptr;\r
+  UINT8             HeaderChecksum;\r
+\r
+  ptr = (UINT8 *)FfsHeader;\r
+  HeaderChecksum = 0;\r
+  for (Index = 0; Index < sizeof(EFI_FFS_FILE_HEADER); Index++) {\r
+    HeaderChecksum = (UINT8)(HeaderChecksum + ptr[Index]);\r
+  }\r
+\r
+  HeaderChecksum = (UINT8) (HeaderChecksum - FfsHeader->State - FfsHeader->IntegrityCheck.Checksum.File);\r
+\r
+  if (HeaderChecksum == 0) {\r
+    return TRUE;\r
+  } else {\r
+    return FALSE;\r
+  }\r
+}\r
+\r
+\r
+BOOLEAN\r
+IsValidFfsHeader (\r
+  IN UINT8                ErasePolarity,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,\r
+  OUT EFI_FFS_FILE_STATE  *FileState\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if it's a valid FFS file header\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file header to be checked\r
+  FileState     -  FFS file state to be returned\r
+    \r
+Returns:\r
+  TRUE  -  Valid FFS file header\r
+  FALSE -  Invalid FFS file header\r
+    \r
+--*/\r
+{\r
+  *FileState = GetFileState (ErasePolarity, FfsHeader);\r
+\r
+  switch (*FileState) {\r
+    case EFI_FILE_HEADER_VALID:\r
+    case EFI_FILE_DATA_VALID:\r
+    case EFI_FILE_MARKED_FOR_UPDATE:\r
+    case EFI_FILE_DELETED:\r
+      //\r
+      // Here we need to verify header checksum\r
+      //\r
+      return VerifyHeaderChecksum (FfsHeader);\r
+    \r
+    case EFI_FILE_HEADER_CONSTRUCTION:\r
+    case EFI_FILE_HEADER_INVALID:\r
+    default:\r
+      return FALSE;\r
+  }\r
+}\r
+\r
+\r
+BOOLEAN\r
+IsValidFfsFile (\r
+  IN UINT8                ErasePolarity,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if it's a valid FFS file. \r
+  Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first.\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file to be checked\r
+    \r
+Returns:\r
+  TRUE  -  Valid FFS file\r
+  FALSE -  Invalid FFS file\r
+    \r
+--*/\r
+{\r
+  EFI_FFS_FILE_STATE  FileState;\r
+\r
+  FileState = GetFileState (ErasePolarity, FfsHeader);\r
+  switch (FileState) {\r
+\r
+    case EFI_FILE_DELETED:\r
+    case EFI_FILE_DATA_VALID:\r
+    case EFI_FILE_MARKED_FOR_UPDATE:\r
+      //\r
+      // Some other vliadation like file content checksum might be done here.\r
+      // For performance issue, Tiano only do FileState check.\r
+      //\r
+      return TRUE;\r
+\r
+    default:\r
+      return FALSE;\r
+  }\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVol.c b/MdeModulePkg/Core/Dxe/FwVol/FwVol.c
new file mode 100644 (file)
index 0000000..7fa346c
--- /dev/null
@@ -0,0 +1,547 @@
+/**@file\r
+  Firmware File System driver that produce Firmware Volume protocol.\r
+  Layers on top of Firmware Block protocol to produce a file abstraction \r
+  of FV based files.\r
+  \r
+Copyright (c) 2006 - 2007 Intel Corporation. <BR>\r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+**/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define KEYSIZE       sizeof (UINTN)\r
+\r
+//\r
+// Protocol notify related globals\r
+//\r
+VOID          *gEfiFwVolBlockNotifyReg;\r
+EFI_EVENT     gEfiFwVolBlockEvent;\r
+\r
+FV_DEVICE mFvDevice = {\r
+  FV_DEVICE_SIGNATURE,\r
+  NULL,\r
+  NULL,\r
+  {\r
+    FvGetVolumeAttributes,\r
+    FvSetVolumeAttributes,\r
+    FvReadFile,\r
+    FvReadFileSection,\r
+    FvWriteFile,\r
+    FvGetNextFile,\r
+    KEYSIZE\r
+  },\r
+  NULL,\r
+  NULL,\r
+  NULL,\r
+  NULL,\r
+  { NULL, NULL },\r
+  0\r
+};\r
+\r
+\r
+//\r
+// FFS helper functions\r
+//\r
+\r
+EFI_STATUS\r
+GetFwVolHeader (\r
+  IN     EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL     *Fvb,\r
+  OUT    EFI_FIRMWARE_VOLUME_HEADER             **FwVolHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  given the supplied FW_VOL_BLOCK_PROTOCOL, allocate a buffer for output and\r
+  copy the volume header into it.\r
+\r
+Arguments:\r
+  Fvb - The FW_VOL_BLOCK_PROTOCOL instance from which to read the volume\r
+          header\r
+  FwVolHeader - Pointer to pointer to allocated buffer in which the volume\r
+                  header is returned.\r
+\r
+Returns:\r
+  EFI_OUT_OF_RESOURCES    - No enough buffer could be allocated.\r
+  EFI_SUCCESS             - Successfully read volume header to the allocated buffer.\r
+\r
+--*/\r
+\r
+{\r
+  EFI_STATUS                  Status;\r
+  EFI_FIRMWARE_VOLUME_HEADER  TempFvh;\r
+  UINTN                       FvhLength;\r
+  UINT8                       *Buffer;\r
+\r
+\r
+  //\r
+  //Determine the real length of FV header\r
+  //\r
+  FvhLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER);\r
+  Status = Fvb->Read (Fvb, 0, 0, &FvhLength, (UINT8 *)&TempFvh);\r
+\r
+  //\r
+  // Allocate a buffer for the caller\r
+  //\r
+  *FwVolHeader = CoreAllocateBootServicesPool (TempFvh.HeaderLength);\r
+  if (*FwVolHeader == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Copy the standard header into the buffer\r
+  //\r
+  CopyMem (*FwVolHeader, &TempFvh, sizeof (EFI_FIRMWARE_VOLUME_HEADER));\r
+\r
+  //\r
+  // Read the rest of the header\r
+  //\r
+  FvhLength = TempFvh.HeaderLength - sizeof (EFI_FIRMWARE_VOLUME_HEADER);\r
+  Buffer = (UINT8 *)*FwVolHeader + sizeof (EFI_FIRMWARE_VOLUME_HEADER);\r
+  Status = Fvb->Read (Fvb, 0, sizeof (EFI_FIRMWARE_VOLUME_HEADER), &FvhLength, Buffer);\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // Read failed so free buffer\r
+    //\r
+    CoreFreePool (*FwVolHeader);\r
+  }\r
\r
+  return Status;\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+FreeFvDeviceResource (\r
+  IN FV_DEVICE  *FvDevice\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Free FvDevice resource when error happens\r
+\r
+Arguments:\r
+  FvDevice - pointer to the FvDevice to be freed.\r
+\r
+Returns:\r
+  None.\r
+\r
+--*/\r
+{\r
+  FFS_FILE_LIST_ENTRY         *FfsFileEntry;\r
+  LIST_ENTRY                  *NextEntry;\r
+\r
+  //\r
+  // Free File List Entry\r
+  //\r
+  FfsFileEntry = (FFS_FILE_LIST_ENTRY *)FvDevice->FfsFileListHeader.ForwardLink;\r
+  while (&FfsFileEntry->Link != &FvDevice->FfsFileListHeader) {\r
+    NextEntry = (&FfsFileEntry->Link)->ForwardLink;\r
+    \r
+    if (FfsFileEntry->StreamHandle != 0) {\r
+      //\r
+      // Close stream and free resources from SEP\r
+      //\r
+      FfsFileEntry->Sep->CloseSectionStream (FfsFileEntry->Sep, FfsFileEntry->StreamHandle);\r
+    }\r
+\r
+    CoreFreePool (FfsFileEntry);\r
+\r
+    FfsFileEntry = (FFS_FILE_LIST_ENTRY *)NextEntry;\r
+  }\r
+\r
+\r
+  //\r
+  // Free the cache\r
+  //\r
+  CoreFreePool (FvDevice->CachedFv);\r
+\r
+  //\r
+  // Free Volume Header\r
+  //\r
+  CoreFreePool (FvDevice->FwVolHeader);\r
+\r
+  return;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+FvCheck (\r
+  IN OUT FV_DEVICE  *FvDevice\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if a FV is consistent and allocate cache\r
+\r
+Arguments:\r
+  FvDevice - pointer to the FvDevice to be checked.\r
+\r
+Returns:\r
+  EFI_OUT_OF_RESOURCES    - No enough buffer could be allocated.\r
+  EFI_SUCCESS             - FV is consistent and cache is allocated.\r
+  EFI_VOLUME_CORRUPTED    - File system is corrupted.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                            Status;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *Fvb;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;\r
+  EFI_FVB_ATTRIBUTES                    FvbAttributes;\r
+  EFI_FV_BLOCK_MAP_ENTRY                *BlockMap;\r
+  FFS_FILE_LIST_ENTRY                   *FfsFileEntry;\r
+  EFI_FFS_FILE_HEADER                   *FfsHeader;\r
+  UINT8                                 *CacheLocation;\r
+  UINTN                                 LbaOffset;\r
+  UINTN                                 Index;\r
+  EFI_LBA                               LbaIndex;\r
+  UINTN                                 Size;\r
+  UINTN                                 FileLength;\r
+  EFI_FFS_FILE_STATE                    FileState;\r
+  UINT8                                 *TopFvAddress;\r
+  UINTN                                 TestLength;\r
+\r
+\r
+  Fvb = FvDevice->Fvb;\r
+  FwVolHeader = FvDevice->FwVolHeader;\r
\r
+  Status = Fvb->GetAttributes (Fvb, &FvbAttributes);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Size is the size of the FV minus the head. We have already allocated\r
+  // the header to check to make sure the volume is valid\r
+  //\r
+  Size = (UINTN)(FwVolHeader->FvLength - FwVolHeader->HeaderLength);\r
+  FvDevice->CachedFv = CoreAllocateBootServicesPool (Size);\r
+\r
+  if (FvDevice->CachedFv == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Remember a pointer to the end fo the CachedFv\r
+  //\r
+  FvDevice->EndOfCachedFv = FvDevice->CachedFv + Size;\r
+\r
+  //\r
+  // Copy FV minus header into memory using the block map we have all ready\r
+  // read into memory.\r
+  //\r
+  BlockMap = FwVolHeader->BlockMap;\r
+  CacheLocation = FvDevice->CachedFv;\r
+  LbaIndex = 0;\r
+  LbaOffset = FwVolHeader->HeaderLength;\r
+  while ((BlockMap->NumBlocks != 0) || (BlockMap->Length != 0)) {\r
+    \r
+    for (Index = 0; Index < BlockMap->NumBlocks; Index ++) {\r
+\r
+      Size = BlockMap->Length;\r
+      if (Index == 0) {\r
+        //\r
+        // Cache does not include FV Header\r
+        //\r
+        Size -= LbaOffset;\r
+      }\r
+      Status = Fvb->Read (Fvb,\r
+                          LbaIndex,\r
+                          LbaOffset,\r
+                          &Size,\r
+                          CacheLocation\r
+                          );\r
+      //\r
+      // Not check EFI_BAD_BUFFER_SIZE, for Size = BlockMap->Length\r
+      //\r
+      if (EFI_ERROR (Status)) {\r
+        goto Done;\r
+      }\r
+      \r
+      //\r
+      // After we skip Fv Header always read from start of block\r
+      //\r
+      LbaOffset = 0;\r
+\r
+      LbaIndex++;\r
+      CacheLocation += Size;\r
+    }\r
+    BlockMap++;\r
+  }\r
+\r
+  //\r
+  // Scan to check the free space & File list\r
+  //\r
+  if (FvbAttributes & EFI_FVB_ERASE_POLARITY) {\r
+    FvDevice->ErasePolarity = 1;\r
+  } else {\r
+    FvDevice->ErasePolarity = 0;\r
+  } \r
+\r
+\r
+  //\r
+  // go through the whole FV cache, check the consistence of the FV.\r
+  // Make a linked list off all the Ffs file headers\r
+  //\r
+  Status = EFI_SUCCESS;\r
+  InitializeListHead (&FvDevice->FfsFileListHeader);\r
+\r
+  //\r
+  // Build FFS list\r
+  //\r
+  FfsHeader = (EFI_FFS_FILE_HEADER *)FvDevice->CachedFv;\r
+  TopFvAddress = FvDevice->EndOfCachedFv;\r
+  while ((UINT8 *)FfsHeader < TopFvAddress) {\r
+\r
+    TestLength = TopFvAddress - ((UINT8 *)FfsHeader);\r
+    if (TestLength > sizeof (EFI_FFS_FILE_HEADER)) {\r
+      TestLength = sizeof (EFI_FFS_FILE_HEADER);\r
+    }\r
+\r
+    if (IsBufferErased (FvDevice->ErasePolarity, FfsHeader, TestLength)) {\r
+      //\r
+      // We have found the free space so we are done!\r
+      //\r
+      goto Done;\r
+    }\r
+\r
+    if (!IsValidFfsHeader (FvDevice->ErasePolarity, FfsHeader, &FileState)) {\r
+      if ((FileState == EFI_FILE_HEADER_INVALID) || \r
+          (FileState == EFI_FILE_HEADER_CONSTRUCTION)) {\r
+        FfsHeader++;\r
+      \r
+        continue;\r
+      \r
+      } else {\r
+        //\r
+        // File system is corrputed\r
+        //\r
+        Status = EFI_VOLUME_CORRUPTED;\r
+        goto Done;\r
+      }\r
+    }\r
+\r
+    if (!IsValidFfsFile (FvDevice->ErasePolarity, FfsHeader)) {\r
+      //\r
+      // File system is corrupted\r
+      //\r
+      Status = EFI_VOLUME_CORRUPTED;\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Size[3] is a three byte array, read 4 bytes and throw one away\r
+    //\r
+    FileLength = *(UINT32 *)&FfsHeader->Size[0] & 0x00FFFFFF;\r
+\r
+    FileState = GetFileState (FvDevice->ErasePolarity, FfsHeader);\r
+    \r
+    //\r
+    // check for non-deleted file\r
+    //\r
+    if (FileState != EFI_FILE_DELETED) {\r
+      //\r
+      // Create a FFS list entry for each non-deleted file\r
+      //\r
+      FfsFileEntry = CoreAllocateZeroBootServicesPool (sizeof (FFS_FILE_LIST_ENTRY));\r
+      if (FfsFileEntry == NULL) {\r
+        Status = EFI_OUT_OF_RESOURCES;\r
+        goto Done;\r
+      }\r
+    \r
+      FfsFileEntry->FfsHeader = FfsHeader;\r
+      InsertTailList (&FvDevice->FfsFileListHeader, &FfsFileEntry->Link);\r
+    }\r
+\r
+    FfsHeader =  (EFI_FFS_FILE_HEADER *)(((UINT8 *)FfsHeader) + FileLength);\r
+    \r
+    //\r
+    // Adjust pointer to the next 8-byte aligned boundry.\r
+    //\r
+    FfsHeader = (EFI_FFS_FILE_HEADER *)(((UINTN)FfsHeader + 7) & ~0x07);\r
+    \r
+  }\r
+\r
+Done:\r
+  if (EFI_ERROR (Status)) {\r
+    FreeFvDeviceResource (FvDevice);\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+NotifyFwVolBlock (\r
+  IN  EFI_EVENT Event,\r
+  IN  VOID      *Context\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This notification function is invoked when an instance of the\r
+    EFI_FW_VOLUME_BLOCK_PROTOCOL is produced.  It layers an instance of the\r
+    EFI_FIRMWARE_VOLUME_PROTOCOL on the same handle.  This is the function where\r
+    the actual initialization of the EFI_FIRMWARE_VOLUME_PROTOCOL is done.\r
+\r
+Arguments:\r
+    Event - The event that occured\r
+    Context - For EFI compatiblity.  Not used.\r
+\r
+Returns:\r
+\r
+    None.\r
+\r
+--*/\r
+{\r
+  EFI_HANDLE                            Handle;\r
+  EFI_STATUS                            Status;\r
+  UINTN                                 BufferSize;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *Fvb;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL          *Fv;\r
+  FV_DEVICE                             *FvDevice;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;\r
+  //\r
+  // Examine all new handles\r
+  //\r
+  for (;;) {\r
+    //\r
+    // Get the next handle\r
+    //\r
+    BufferSize = sizeof (Handle);\r
+    Status = CoreLocateHandle (\r
+              ByRegisterNotify,\r
+              NULL,\r
+              gEfiFwVolBlockNotifyReg,\r
+              &BufferSize,\r
+              &Handle\r
+              );\r
+\r
+    //\r
+    // If not found, we're done\r
+    //\r
+    if (EFI_NOT_FOUND == Status) {\r
+      break;\r
+    }\r
+\r
+    if (EFI_ERROR (Status)) {\r
+      continue;\r
+    }\r
+    \r
+    //\r
+    // Get the FirmwareVolumeBlock protocol on that handle\r
+    //\r
+    Status = CoreHandleProtocol (Handle, &gEfiFirmwareVolumeBlockProtocolGuid, (VOID **)&Fvb); \r
+    ASSERT_EFI_ERROR (Status);\r
+    \r
+\r
+    //\r
+    // Make sure the Fv Header is O.K.\r
+    //\r
+    Status = GetFwVolHeader (Fvb, &FwVolHeader);\r
+    if (EFI_ERROR (Status)) {\r
+      return;\r
+    }\r
+\r
+    if (!VerifyFvHeaderChecksum (FwVolHeader)) {\r
+      CoreFreePool (FwVolHeader);\r
+      continue;\r
+    }\r
+\r
+\r
+    //\r
+    // Check to see that the file system is indeed formatted in a way we can\r
+    // understand it...\r
+    //\r
+    if (!CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystemGuid)) {\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // Check if there is an FV protocol already installed in that handle\r
+    //\r
+    Status = CoreHandleProtocol (Handle, &gEfiFirmwareVolumeProtocolGuid, (VOID **)&Fv);\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Update Fv to use a new Fvb\r
+      //\r
+      FvDevice = _CR (Fv, FV_DEVICE, Fv);\r
+      if (FvDevice->Signature == FV_DEVICE_SIGNATURE) {\r
+        //\r
+        // Only write into our device structure if it's our device structure\r
+        //\r
+        FvDevice->Fvb = Fvb;\r
+      }\r
+\r
+    } else {\r
+      //\r
+      // No FwVol protocol on the handle so create a new one\r
+      //\r
+      FvDevice = CoreAllocateCopyPool (sizeof (FV_DEVICE), &mFvDevice);\r
+      if (FvDevice == NULL) {\r
+        return;\r
+      }\r
+      \r
+      FvDevice->Fvb         = Fvb;\r
+      FvDevice->Handle      = Handle;\r
+      FvDevice->FwVolHeader = FwVolHeader;\r
+      FvDevice->Fv.ParentHandle = Fvb->ParentHandle;\r
+      \r
+      //\r
+      // Install an New FV protocol on the existing handle\r
+      //\r
+      Status = CoreInstallProtocolInterface (\r
+                  &Handle,\r
+                  &gEfiFirmwareVolumeProtocolGuid,\r
+                  EFI_NATIVE_INTERFACE,\r
+                  &FvDevice->Fv\r
+                  );\r
+      ASSERT_EFI_ERROR (Status);\r
+    }\r
+  }\r
+  \r
+  return;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolDriverInit (\r
+  IN EFI_HANDLE                   ImageHandle,\r
+  IN EFI_SYSTEM_TABLE             *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine is the driver initialization entry point.  It initializes the\r
+    libraries, and registers two notification functions.  These notification\r
+    functions are responsible for building the FV stack dynamically.\r
+    \r
+Arguments:\r
+    ImageHandle   - The image handle.\r
+    SystemTable   - The system table.\r
+    \r
+Returns:\r
+    EFI_SUCCESS   - Function successfully returned.\r
+\r
+--*/\r
+{\r
+  gEfiFwVolBlockEvent = CoreCreateProtocolNotifyEvent (\r
+                          &gEfiFirmwareVolumeBlockProtocolGuid,\r
+                          TPL_CALLBACK,\r
+                          NotifyFwVolBlock,\r
+                          NULL,\r
+                          &gEfiFwVolBlockNotifyReg,\r
+                          TRUE\r
+                          );\r
+  return EFI_SUCCESS;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c
new file mode 100644 (file)
index 0000000..4a31a8d
--- /dev/null
@@ -0,0 +1,99 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolAttrib.c\r
+\r
+Abstract:\r
+\r
+  Implements get/set firmware volume attributes\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvGetVolumeAttributes (\r
+  IN  EFI_FIRMWARE_VOLUME_PROTOCOL  *This,\r
+  OUT EFI_FV_ATTRIBUTES             *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Retrieves attributes, insures positive polarity of attribute bits, returns\r
+    resulting attributes in output parameter\r
+\r
+Arguments:\r
+    This        - Calling context\r
+    Attributes  - output buffer which contains attributes\r
+\r
+Returns:\r
+    EFI_SUCCESS         - Successfully got volume attributes\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                                Status;\r
+  FV_DEVICE                                 *FvDevice;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL        *Fvb;\r
+  EFI_FVB_ATTRIBUTES                        FvbAttributes;\r
+\r
+  FvDevice = FV_DEVICE_FROM_THIS (This);\r
+  Fvb = FvDevice->Fvb;\r
+\r
+  if (FvDevice->CachedFv == NULL) {\r
+    Status = FvCheck (FvDevice);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+\r
+  //\r
+  // First get the Firmware Volume Block Attributes\r
+  //\r
+  Status = Fvb->GetAttributes (Fvb, &FvbAttributes);\r
+\r
+  //\r
+  // Mask out Fvb bits that are not defined in FV \r
+  //\r
+  FvbAttributes &= 0xfffff0ff;\r
+  \r
+  *Attributes = (EFI_FV_ATTRIBUTES)FvbAttributes; \r
+  \r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvSetVolumeAttributes (\r
+  IN EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN OUT EFI_FV_ATTRIBUTES          *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Sets current attributes for volume\r
+\r
+Arguments:\r
+    This       - Calling context\r
+    Attributes - At input, contains attributes to be set.  At output contains\r
+      new value of FV\r
+\r
+Returns:\r
+    EFI_UNSUPPORTED   - Could not be set.\r
+\r
+--*/\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c
new file mode 100644 (file)
index 0000000..ff2fcb8
--- /dev/null
@@ -0,0 +1,516 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolRead.c\r
+\r
+Abstract:\r
+\r
+  Implements read firmware file\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+/*++\r
+\r
+Required Alignment    Alignment Value in FFS       Alignment Value in\r
+(bytes)                        Attributes Field               Firmware Volume Interfaces\r
+1                                    0                                     0\r
+2                                    0                                     1\r
+4                                    0                                     2\r
+8                                    0                                     3\r
+16                                   1                                     4\r
+128                                  2                                     7\r
+512                                  3                                     9\r
+1 KB                                 4                                     10\r
+4 KB                                 5                                     12\r
+32 KB                                6                                     15\r
+64 KB                                7                                     16\r
+\r
+--*/\r
+\r
+UINT8 mFvAttributes[] = {0, 4, 7, 9, 10, 12, 15, 16}; \r
+\r
+\r
+STATIC\r
+EFI_FV_FILE_ATTRIBUTES\r
+FfsAttributes2FvFileAttributes (\r
+  IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+    Convert the FFS File Attributes to FV File Attributes\r
+    \r
+  Arguments:\r
+    FfsAttributes   -   The attributes of UINT8 type.\r
+    \r
+  Returns:\r
+    The attributes of EFI_FV_FILE_ATTRIBUTES\r
+    \r
+--*/\r
+{\r
+  FfsAttributes = (EFI_FFS_FILE_ATTRIBUTES)((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3);\r
+  ASSERT (FfsAttributes < 8);\r
+\r
+  return (EFI_FV_FILE_ATTRIBUTES) mFvAttributes[FfsAttributes];\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvGetNextFile (\r
+  IN         EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN OUT     VOID                            *Key,\r
+  IN OUT     EFI_FV_FILETYPE                *FileType,\r
+  OUT        EFI_GUID                      *NameGuid,\r
+  OUT        EFI_FV_FILE_ATTRIBUTES        *Attributes,\r
+  OUT        UINTN                           *Size\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Given the input key, search for the next matching file in the volume.\r
+\r
+Arguments:\r
+    This          -   Indicates the calling context.\r
+    FileType      -   FileType is a pointer to a caller allocated\r
+                      EFI_FV_FILETYPE. The GetNextFile() API can filter it's\r
+                      search for files based on the value of *FileType input.\r
+                      A *FileType input of 0 causes GetNextFile() to search for\r
+                      files of all types.  If a file is found, the file's type\r
+                      is returned in *FileType.  *FileType is not modified if\r
+                      no file is found.\r
+    Key           -   Key is a pointer to a caller allocated buffer that\r
+                      contains implementation specific data that is used to\r
+                      track where to begin the search for the next file.\r
+                      The size of the buffer must be at least This->KeySize\r
+                      bytes long. To reinitialize the search and begin from\r
+                      the beginning of the firmware volume, the entire buffer\r
+                      must be cleared to zero. Other than clearing the buffer\r
+                      to initiate a new search, the caller must not modify the\r
+                      data in the buffer between calls to GetNextFile().\r
+    NameGuid      -   NameGuid is a pointer to a caller allocated EFI_GUID.\r
+                      If a file is found, the file's name is returned in\r
+                      *NameGuid.  *NameGuid is not modified if no file is\r
+                      found.\r
+    Attributes    -   Attributes is a pointer to a caller allocated\r
+                      EFI_FV_FILE_ATTRIBUTES.  If a file is found, the file's\r
+                      attributes are returned in *Attributes. *Attributes is\r
+                      not modified if no file is found.\r
+    Size          -   Size is a pointer to a caller allocated UINTN.\r
+                      If a file is found, the file's size is returned in *Size.\r
+                      *Size is not modified if no file is found.\r
+\r
+Returns:\r
+    EFI_SUCCESS                 - Successfully find the file.\r
+    EFI_DEVICE_ERROR            - Device error.\r
+    EFI_ACCESS_DENIED           - Fv could not read.\r
+    EFI_NOT_FOUND               - No matching file found.\r
+    EFI_INVALID_PARAMETER       - Invalid parameter\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                                  Status;\r
+  FV_DEVICE                                   *FvDevice;\r
+  EFI_FV_ATTRIBUTES                           FvAttributes;\r
+  EFI_FFS_FILE_HEADER                         *FfsFileHeader;\r
+  UINTN                                       *KeyValue;\r
+  LIST_ENTRY                                  *Link;\r
+  FFS_FILE_LIST_ENTRY                         *FfsFileEntry;\r
+  UINTN                                       FileLength;\r
+\r
+  FvDevice = FV_DEVICE_FROM_THIS (This);\r
+\r
+  Status = FvGetVolumeAttributes (This, &FvAttributes);\r
+  if (EFI_ERROR (Status)){\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Check if read operation is enabled\r
+  //\r
+  if ((FvAttributes & EFI_FV_READ_STATUS) == 0) {\r
+    return EFI_ACCESS_DENIED;\r
+  }\r
+\r
+  if (*FileType > EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) {\r
+    //\r
+    // File type needs to be in 0 - 0x0B\r
+    //\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  KeyValue = (UINTN *)Key;\r
+  for (;;) {\r
+    if (*KeyValue == 0) {\r
+      //\r
+      // Search for 1st matching file\r
+      //\r
+      Link = &FvDevice->FfsFileListHeader;\r
+    } else {\r
+      //\r
+      // Key is pointer to FFsFileEntry, so get next one\r
+      //\r
+      Link = (LIST_ENTRY *)(*KeyValue);\r
+    }\r
+\r
+    if (Link->ForwardLink == &FvDevice->FfsFileListHeader) {\r
+      //\r
+      // Next is end of list so we did not find data\r
+      //\r
+      return EFI_NOT_FOUND;\r
+    }\r
+\r
+    FfsFileEntry = (FFS_FILE_LIST_ENTRY *)Link->ForwardLink;\r
+    FfsFileHeader = (EFI_FFS_FILE_HEADER *)FfsFileEntry->FfsHeader;\r
+\r
+    //\r
+    // remember the key\r
+    //\r
+    *KeyValue = (UINTN)FfsFileEntry;\r
+\r
+    if (FfsFileHeader->Type == EFI_FV_FILETYPE_FFS_PAD) {\r
+      //\r
+      // we ignore pad files\r
+      //\r
+      continue;\r
+    }\r
+\r
+    if (*FileType == 0) {\r
+      //\r
+      // Process all file types so we have a match\r
+      //\r
+      break;\r
+    }\r
+\r
+    if (*FileType == FfsFileHeader->Type) {\r
+      //\r
+      // Found a matching file type\r
+      //\r
+      break;\r
+    }\r
+\r
+  } \r
+\r
+  //\r
+  // Return FileType, NameGuid, and Attributes\r
+  //\r
+  *FileType = FfsFileHeader->Type;\r
+  CopyMem (NameGuid, &FfsFileHeader->Name, sizeof (EFI_GUID));\r
+  *Attributes = FfsAttributes2FvFileAttributes (FfsFileHeader->Attributes);\r
+\r
+  //\r
+  // Read four bytes out of the 3 byte array and throw out extra data\r
+  //\r
+  FileLength = *(UINT32 *)&FfsFileHeader->Size[0] & 0x00FFFFFF;\r
+\r
+  //\r
+  // we need to substract the header size\r
+  //\r
+  *Size = FileLength - sizeof(EFI_FFS_FILE_HEADER);\r
+\r
+  if (FfsFileHeader->Attributes & FFS_ATTRIB_TAIL_PRESENT) {\r
+    //\r
+    // If tail is present substract it's size;\r
+    //\r
+    *Size -= sizeof(EFI_FFS_FILE_TAIL);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvReadFile (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN     EFI_GUID                       *NameGuid,\r
+  IN OUT VOID                           **Buffer,\r
+  IN OUT UINTN                          *BufferSize,\r
+  OUT    EFI_FV_FILETYPE               *FoundType,\r
+  OUT    EFI_FV_FILE_ATTRIBUTES        *FileAttributes,\r
+  OUT    UINT32                        *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Locates a file in the firmware volume and\r
+    copies it to the supplied buffer.\r
+\r
+Arguments:\r
+    This              -   Indicates the calling context.\r
+    NameGuid          -   Pointer to an EFI_GUID, which is the filename.\r
+    Buffer            -   Buffer is a pointer to pointer to a buffer in\r
+                          which the file or section contents or are returned.\r
+    BufferSize        -   BufferSize is a pointer to caller allocated\r
+                          UINTN. On input *BufferSize indicates the size\r
+                          in bytes of the memory region pointed to by\r
+                          Buffer. On output, *BufferSize contains the number\r
+                          of bytes required to read the file.\r
+    FoundType         -   FoundType is a pointer to a caller allocated\r
+                          EFI_FV_FILETYPE that on successful return from Read()\r
+                          contains the type of file read.  This output reflects\r
+                          the file type irrespective of the value of the\r
+                          SectionType input.\r
+    FileAttributes    -   FileAttributes is a pointer to a caller allocated\r
+                          EFI_FV_FILE_ATTRIBUTES.  On successful return from\r
+                          Read(), *FileAttributes contains the attributes of\r
+                          the file read.\r
+    AuthenticationStatus -  AuthenticationStatus is a pointer to a caller\r
+                          allocated UINTN in which the authentication status\r
+                          is returned.\r
+Returns:\r
+    EFI_SUCCESS                   - Successfully read to memory buffer.\r
+    EFI_WARN_BUFFER_TOO_SMALL     - Buffer too small.\r
+    EFI_NOT_FOUND                 - Not found.\r
+    EFI_DEVICE_ERROR              - Device error.\r
+    EFI_ACCESS_DENIED             - Could not read.\r
+    EFI_INVALID_PARAMETER         - Invalid parameter.\r
+    EFI_OUT_OF_RESOURCES          - Not enough buffer to be allocated.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                        Status;\r
+  FV_DEVICE                         *FvDevice;\r
+  EFI_GUID                          SearchNameGuid;\r
+  EFI_FV_FILETYPE                   LocalFoundType;\r
+  EFI_FV_FILE_ATTRIBUTES            LocalAttributes;\r
+  UINTN                             FileSize;\r
+  UINT8                             *SrcPtr;\r
+  EFI_FFS_FILE_HEADER               *FfsHeader;\r
+  UINTN                             InputBufferSize;\r
+  \r
+  if (NULL == NameGuid) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  FvDevice = FV_DEVICE_FROM_THIS (This);\r
+  \r
+\r
+  //\r
+  // Keep looking until we find the matching NameGuid.\r
+  // The Key is really an FfsFileEntry\r
+  //\r
+  FvDevice->LastKey = 0;\r
+  do {\r
+    LocalFoundType = 0;\r
+    Status = FvGetNextFile (\r
+              This,\r
+              &FvDevice->LastKey,\r
+              &LocalFoundType,\r
+              &SearchNameGuid,\r
+              &LocalAttributes,\r
+              &FileSize\r
+              );\r
+    if (EFI_ERROR (Status)) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+  } while (!CompareGuid (&SearchNameGuid, NameGuid));\r
+\r
+  //\r
+  // Get a pointer to the header\r
+  //\r
+  FfsHeader = FvDevice->LastKey->FfsHeader;\r
+\r
+  //\r
+  // Remember callers buffer size\r
+  //\r
+  InputBufferSize = *BufferSize;\r
+\r
+  //\r
+  // Calculate return values\r
+  //\r
+  *FoundType = FfsHeader->Type;\r
+  *FileAttributes = FfsAttributes2FvFileAttributes (FfsHeader->Attributes);\r
+  *AuthenticationStatus = 0;\r
+  *BufferSize = FileSize;\r
+\r
+  if (Buffer == NULL) {\r
+    //\r
+    // If Buffer is NULL, we only want to get the information colected so far\r
+    //\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  //\r
+  // Skip over file header\r
+  //\r
+  SrcPtr = ((UINT8 *)FfsHeader) + sizeof (EFI_FFS_FILE_HEADER);\r
+\r
+  Status = EFI_SUCCESS;\r
+  if (*Buffer == NULL) {\r
+    //\r
+    // Caller passed in a pointer so allocate buffer for them\r
+    //\r
+    *Buffer = CoreAllocateBootServicesPool (FileSize);\r
+    if (*Buffer == NULL) {\r
+      return EFI_OUT_OF_RESOURCES;\r
+    }\r
+  } else if (FileSize > InputBufferSize) {\r
+    //\r
+    // Callers buffer was not big enough\r
+    // \r
+    Status = EFI_WARN_BUFFER_TOO_SMALL;\r
+    FileSize = InputBufferSize;\r
+  }\r
+  \r
+  //\r
+  // Copy data into callers buffer \r
+  //\r
+  CopyMem (*Buffer, SrcPtr, FileSize);\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvReadFileSection (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN     EFI_GUID                       *NameGuid,\r
+  IN     EFI_SECTION_TYPE               SectionType,\r
+  IN     UINTN                          SectionInstance,\r
+  IN OUT VOID                           **Buffer,\r
+  IN OUT UINTN                          *BufferSize,\r
+  OUT    UINT32                         *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+    Locates a section in a given FFS File and\r
+    copies it to the supplied buffer (not including section header).\r
+\r
+  Arguments:\r
+    This              -   Indicates the calling context.\r
+    NameGuid          -   Pointer to an EFI_GUID, which is the filename.\r
+    SectionType       -   Indicates the section type to return.\r
+    SectionInstance   -   Indicates which instance of sections with a type of\r
+                          SectionType to return.\r
+    Buffer            -   Buffer is a pointer to pointer to a buffer in which\r
+                          the file or section contents or are returned.\r
+    BufferSize        -   BufferSize is a pointer to caller allocated UINTN.\r
+    AuthenticationStatus -AuthenticationStatus is a pointer to a caller\r
+                          allocated UINT32 in which the authentication status\r
+                          is returned.\r
+\r
+  Returns:\r
+    EFI_SUCCESS                     - Successfully read the file section into buffer.\r
+    EFI_WARN_BUFFER_TOO_SMALL       - Buffer too small.\r
+    EFI_NOT_FOUND                   - Section not found.\r
+    EFI_DEVICE_ERROR                - Device error.\r
+    EFI_ACCESS_DENIED               - Could not read.\r
+    EFI_INVALID_PARAMETER           - Invalid parameter.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                        Status;\r
+  FV_DEVICE                         *FvDevice;\r
+  EFI_FV_FILETYPE                   FileType;\r
+  EFI_FV_FILE_ATTRIBUTES            FileAttributes;\r
+  UINTN                             FileSize;\r
+  UINT8                             *FileBuffer;\r
+  EFI_SECTION_EXTRACTION_PROTOCOL   *Sep;\r
+  FFS_FILE_LIST_ENTRY               *FfsEntry;\r
\r
+  if (NULL == NameGuid || Buffer == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  FvDevice = FV_DEVICE_FROM_THIS (This);\r
+\r
+  //\r
+  // Read the whole file into buffer\r
+  //\r
+  FileBuffer = NULL;\r
+  Status = FvReadFile (\r
+            This,\r
+            NameGuid,\r
+            (VOID **)&FileBuffer,\r
+            &FileSize,\r
+            &FileType,\r
+            &FileAttributes,\r
+            AuthenticationStatus\r
+            );             \r
+  //\r
+  // Get the last key used by our call to FvReadFile as it is the FfsEntry for this file.\r
+  //  \r
+  FfsEntry = (FFS_FILE_LIST_ENTRY *)FvDevice->LastKey;\r
+\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+  \r
+  //\r
+  // Check to see that the file actually HAS sections before we go any further.\r
+  //\r
+  if (FileType == EFI_FV_FILETYPE_RAW) {\r
+    Status = EFI_NOT_FOUND;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Use FfsEntry to cache Section Extraction Protocol Inforomation\r
+  //\r
+  if (FfsEntry->StreamHandle == 0) {\r
+    //\r
+    // Located the protocol\r
+    //\r
+    Status = CoreLocateProtocol (&gEfiSectionExtractionProtocolGuid, NULL, (VOID **)&Sep);\r
+    //\r
+    // Section Extraction Protocol is part of Dxe Core so this should never fail\r
+    //\r
+    ASSERT_EFI_ERROR (Status);\r
+\r
+    Status = Sep->OpenSectionStream (\r
+                    Sep,\r
+                    FileSize,\r
+                    FileBuffer,\r
+                    &FfsEntry->StreamHandle\r
+                    );\r
+    if (EFI_ERROR (Status)) {\r
+      goto Done;\r
+    }\r
+\r
+    FfsEntry->Sep = Sep;\r
+  } else {\r
+    //\r
+    // Get cached copy of Sep\r
+    //\r
+    Sep = FfsEntry->Sep;\r
+  }\r
+\r
+  //\r
+  // If SectionType == 0 We need the whole section stream\r
+  //\r
+  Status = Sep->GetSection (\r
+                  Sep,\r
+                            FfsEntry->StreamHandle,\r
+                            (SectionType == 0) ? NULL : &SectionType,\r
+                            NULL,\r
+                            (SectionType == 0) ? 0 : SectionInstance,\r
+                            Buffer,\r
+                            BufferSize,\r
+                            AuthenticationStatus\r
+                            );\r
+\r
+  //\r
+  // Close of stream defered to close of FfsHeader list to allow SEP to cache data\r
+  //\r
+\r
+Done:\r
+  CoreFreePool (FileBuffer);\r
+\r
+  return Status;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c
new file mode 100644 (file)
index 0000000..4368fe5
--- /dev/null
@@ -0,0 +1,60 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolWrite.c\r
+\r
+Abstract:\r
+\r
+  Implements write firmware file\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvWriteFile (\r
+  IN EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN UINT32                         NumberOfFiles,\r
+  IN EFI_FV_WRITE_POLICY            WritePolicy,\r
+  IN EFI_FV_WRITE_FILE_DATA         *FileData\r
+  )\r
+/*++\r
+\r
+    Routine Description:\r
+      Writes one or more files to the firmware volume.\r
+\r
+    Arguments:\r
+    This            - Indicates the calling context.\r
+    NumberOfFiles   - Number of files.\r
+    WritePolicy     - WritePolicy indicates the level of reliability for\r
+                      the write in the event of a power failure or other\r
+                      system failure during the write operation.\r
+    FileData        - FileData is an pointer to an array of EFI_FV_WRITE_DATA.\r
+                      Each element of FileData[] represents a file to be written.\r
+\r
+    Returns:\r
+      EFI_SUCCESS                   - Files successfully written to firmware volume\r
+      EFI_OUT_OF_RESOURCES          - Not enough buffer to be allocated.\r
+      EFI_DEVICE_ERROR              - Device error.\r
+      EFI_WRITE_PROTECTED           - Write protected.\r
+      EFI_NOT_FOUND                 - Not found.\r
+      EFI_INVALID_PARAMETER         - Invalid parameter.\r
+      EFI_UNSUPPORTED               - This function not supported.\r
+\r
+--*/\r
+{ \r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVolBlock.h b/MdeModulePkg/Core/Dxe/FwVolBlock.h
new file mode 100644 (file)
index 0000000..1ba25c3
--- /dev/null
@@ -0,0 +1,324 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolBlock.h\r
+\r
+Abstract:\r
+\r
+  Firmware Volume Block protocol..  Consumes FV hobs and creates\r
+  appropriate block protocols.\r
+\r
+  Also consumes NT_NON_MM_FV envinronment variable and produces appropriate\r
+  block protocols fro them also... (this is TBD)\r
+\r
+--*/\r
+\r
+#ifndef _FWVOL_BLOCK_H_\r
+#define _FWVOL_BLOCK_H_\r
+\r
+\r
+#define FVB_DEVICE_SIGNATURE       EFI_SIGNATURE_32('_','F','V','B')\r
+\r
+typedef struct {\r
+  UINTN                       Base;\r
+  UINTN                       Length;\r
+} LBA_CACHE;\r
+\r
+typedef struct {\r
+  MEMMAP_DEVICE_PATH          MemMapDevPath;\r
+  EFI_DEVICE_PATH_PROTOCOL    EndDevPath;\r
+} FV_DEVICE_PATH;\r
+\r
+\r
+typedef struct {\r
+  UINTN                                 Signature;\r
+  EFI_HANDLE                            Handle;\r
+  FV_DEVICE_PATH                        DevicePath;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    FwVolBlockInstance;\r
+  UINTN                                 NumBlocks;\r
+  LBA_CACHE                             *LbaCache;\r
+  UINT32                                FvbAttributes;\r
+  EFI_PHYSICAL_ADDRESS                  BaseAddress;\r
+} EFI_FW_VOL_BLOCK_DEVICE;\r
+\r
+#define FVB_DEVICE_FROM_THIS(a) \\r
+  CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance, FVB_DEVICE_SIGNATURE)\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockDriverInit (\r
+  IN EFI_HANDLE               ImageHandle,\r
+  IN EFI_SYSTEM_TABLE         *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine is the driver initialization entry point.  It initializes the\r
+    libraries, consumes FV hobs and NT_NON_MM_FV environment variable and\r
+    produces instances of FW_VOL_BLOCK_PROTOCOL as appropriate.\r
+Arguments:\r
+    ImageHandle   - The image handle.\r
+    SystemTable   - The system table.\r
+Returns:\r
+    EFI_SUCCESS   - Successfully initialized firmware volume block driver.\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetAttributes (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  OUT       EFI_FVB_ATTRIBUTES                  *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Retrieves Volume attributes.  No polarity translations are done.\r
+\r
+Arguments:\r
+    This - Calling context\r
+    Attributes - output buffer which contains attributes\r
+\r
+Returns:\r
+    EFI_SUCCESS - The firmware volume attributes were returned.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockSetAttributes (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  IN CONST  EFI_FVB_ATTRIBUTES                  *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Modifies the current settings of the firmware volume according to the input parameter.\r
+\r
+Arguments:\r
+  This - Calling context\r
+  Attributes - input buffer which contains attributes\r
+\r
+Returns:\r
+  EFI_SUCCESS -  The firmware volume attributes were returned.\r
+  EFI_INVALID_PARAMETER  -  The attributes requested are in conflict with the capabilities as\r
+                             declared in the firmware volume header.\r
+  EFI_UNSUPPORTED        -  Not supported.\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockEraseBlock (\r
+  IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *This,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  The EraseBlock() function erases one or more blocks as denoted by the \r
+variable argument list. The entire parameter list of blocks must be verified\r
+prior to erasing any blocks.  If a block is requested that does not exist \r
+within the associated firmware volume (it has a larger index than the last \r
+block of the firmware volume), the EraseBlock() function must return\r
+EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.\r
+\r
+Arguments:\r
+  This - Calling context\r
+  ...  - Starting LBA followed by Number of Lba to erase. a -1 to terminate\r
+           the list.\r
+    \r
+Returns:\r
+  EFI_SUCCESS   -  The erase request was successfully completed.\r
+  EFI_ACCESS_DENIED   -  The firmware volume is in the WriteDisabled state.\r
+  EFI_DEVICE_ERROR    -  The block device is not functioning correctly and could not be\r
+                         written. The firmware device may have been partially erased.\r
+  EFI_INVALID_PARAMETER  -  One or more of the LBAs listed in the variable argument list do\r
+  EFI_UNSUPPORTED        -  Not supported.\r
+    \r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockReadBlock (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL   *This,\r
+  IN CONST  EFI_LBA                              Lba,\r
+  IN CONST  UINTN                                Offset,\r
+  IN OUT    UINTN                                *NumBytes,\r
+  IN OUT    UINT8                                *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Read the specified number of bytes from the block to the input buffer.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Lba           -  The starting logical block index to read.\r
+  Offset        -  Offset into the block at which to begin reading.\r
+  NumBytes      -  Pointer to a UINT32. At entry, *NumBytes contains the\r
+                   total size of the buffer. At exit, *NumBytes contains the\r
+                   total number of bytes actually read.\r
+  Buffer        -  Pinter to a caller-allocated buffer that contains the destine\r
+                   for the read.    \r
+\r
+Returns:      \r
+  EFI_SUCCESS  -  The firmware volume was read successfully.\r
+  EFI_BAD_BUFFER_SIZE -  The read was attempted across an LBA boundary.\r
+  EFI_ACCESS_DENIED  -  Access denied.\r
+  EFI_DEVICE_ERROR   -  The block device is malfunctioning and could not be read.\r
+--*/\r
+;\r
+\r
+  \r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockWriteBlock (\r
+  IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *This,\r
+  IN EFI_LBA                              Lba,\r
+  IN UINTN                                Offset,\r
+  IN OUT UINTN                            *NumBytes,\r
+  IN UINT8                                *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Writes the specified number of bytes from the input buffer to the block.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Lba           -  The starting logical block index to write to.\r
+  Offset        -  Offset into the block at which to begin writing.\r
+  NumBytes      -  Pointer to a UINT32. At entry, *NumBytes contains the\r
+                   total size of the buffer. At exit, *NumBytes contains the\r
+                   total number of bytes actually written.\r
+  Buffer        -  Pinter to a caller-allocated buffer that contains the source\r
+                   for the write.    \r
+\r
+Returns:     \r
+  EFI_SUCCESS  -  The firmware volume was written successfully.\r
+  EFI_BAD_BUFFER_SIZE -  The write was attempted across an LBA boundary. On output,\r
+                         NumBytes contains the total number of bytes actually written.\r
+  EFI_ACCESS_DENIED  -  The firmware volume is in the WriteDisabled state.\r
+  EFI_DEVICE_ERROR   -  The block device is malfunctioning and could not be written.\r
+  EFI_UNSUPPORTED    -  Not supported.\r
+--*/\r
+;\r
+\r
+    \r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetPhysicalAddress (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *This,\r
+  OUT       EFI_PHYSICAL_ADDRESS                  *Address\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Get Fvb's base address.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Address       -  Fvb device base address.\r
+\r
+Returns:     \r
+  EFI_SUCCESS  -  Successfully got Fvb's base address.\r
+  EFI_UNSUPPORTED -  Not supported.\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetBlockSize (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  IN CONST  EFI_LBA                             Lba,\r
+  OUT       UINTN                               *BlockSize,\r
+  OUT       UINTN                               *NumberOfBlocks\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Retrieves the size in bytes of a specific block within a firmware volume.\r
+\r
+Arguments:\r
+  This            -  Indicates the calling context.\r
+  Lba             -  Indicates the block for which to return the size.\r
+  BlockSize       -  Pointer to a caller-allocated UINTN in which the size of the\r
+                     block is returned.\r
+  NumberOfBlocks  -  Pointer to a caller-allocated UINTN in which the number of\r
+                     consecutive blocks starting with Lba is returned. All blocks\r
+                     in this range have a size of BlockSize.   \r
+Returns:\r
+  EFI_SUCCESS  -  The firmware volume base address is returned.\r
+  EFI_INVALID_PARAMETER  -  The requested LBA is out of range.\r
+--*/\r
+;\r
+EFI_STATUS\r
+FwVolBlockDriverInit (\r
+  IN EFI_HANDLE               ImageHandle,\r
+  IN EFI_SYSTEM_TABLE         *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine is the driver initialization entry point.  It initializes the\r
+    libraries, consumes FV hobs and NT_NON_MM_FV environment variable and\r
+    produces instances of FW_VOL_BLOCK_PROTOCOL as appropriate.\r
+Arguments:\r
+    ImageHandle   - The image handle.\r
+    SystemTable   - The system table.\r
+Returns:\r
+    Status code\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+ProduceFVBProtocolOnBuffer (\r
+  IN EFI_PHYSICAL_ADDRESS   BaseAddress,\r
+  IN UINT64                 Length,\r
+  IN EFI_HANDLE             ParentHandle,\r
+  OUT EFI_HANDLE            *FvProtocolHandle  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine produces a firmware volume block protocol on a given\r
+    buffer. \r
+\r
+Arguments:\r
+    BaseAddress     - base address of the firmware volume image\r
+    Length          - length of the firmware volume image\r
+    ParentHandle    - handle of parent firmware volume, if this\r
+                      image came from an FV image file in another\r
+                      firmware volume (ala capsules)\r
+    FvProtocolHandle  - Firmware volume block protocol produced.\r
+    \r
+Returns:\r
+    EFI_VOLUME_CORRUPTED    - Volume corrupted.\r
+    EFI_OUT_OF_RESOURCES    - No enough buffer to be allocated.\r
+    EFI_SUCCESS             - Successfully produced a FVB protocol on given buffer.\r
+                     \r
+--*/\r
+;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c b/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c
new file mode 100644 (file)
index 0000000..e07eea2
--- /dev/null
@@ -0,0 +1,598 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolBlock.c\r
+\r
+Abstract:\r
+\r
+  Firmware Volume Block protocol..  Consumes FV hobs and creates\r
+  appropriate block protocols.\r
+\r
+  Also consumes NT_NON_MM_FV envinronment variable and produces appropriate\r
+  block protocols fro them also... (this is TBD)\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+EFI_FW_VOL_BLOCK_DEVICE  mFwVolBlock = {\r
+  FVB_DEVICE_SIGNATURE,\r
+  NULL,\r
+  {\r
+    {\r
+      {\r
+        HARDWARE_DEVICE_PATH,\r
+        HW_MEMMAP_DP,\r
+        { (UINT8)(sizeof (MEMMAP_DEVICE_PATH)), (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8) }\r
+      },\r
+      EfiMemoryMappedIO,\r
+      (EFI_PHYSICAL_ADDRESS)0,\r
+      (EFI_PHYSICAL_ADDRESS)0,\r
+    },\r
+    {\r
+      END_DEVICE_PATH_TYPE,\r
+      END_ENTIRE_DEVICE_PATH_SUBTYPE,\r
+      { END_DEVICE_PATH_LENGTH, 0 }      \r
+    },\r
+  },\r
+  {\r
+    FwVolBlockGetAttributes,\r
+    (EFI_FVB_SET_ATTRIBUTES)FwVolBlockSetAttributes,\r
+    FwVolBlockGetPhysicalAddress,\r
+    FwVolBlockGetBlockSize,\r
+    FwVolBlockReadBlock,\r
+    (EFI_FVB_WRITE)FwVolBlockWriteBlock,\r
+    (EFI_FVB_ERASE_BLOCKS)FwVolBlockEraseBlock,\r
+    NULL      \r
+  },\r
+  0,\r
+  NULL,\r
+  0,\r
+  0\r
+};\r
+\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetAttributes (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  OUT       EFI_FVB_ATTRIBUTES                  *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Retrieves Volume attributes.  No polarity translations are done.\r
+\r
+Arguments:\r
+    This - Calling context\r
+    Attributes - output buffer which contains attributes\r
+\r
+Returns:\r
+    EFI_SUCCESS - The firmware volume attributes were returned.\r
+\r
+--*/\r
+{\r
+  EFI_FW_VOL_BLOCK_DEVICE               *FvbDevice;\r
+  \r
+  FvbDevice = FVB_DEVICE_FROM_THIS (This);\r
+\r
+  //\r
+  // Since we are read only, it's safe to get attributes data from our in-memory copy.\r
+  //\r
+  *Attributes = FvbDevice->FvbAttributes;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockSetAttributes (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  IN CONST  EFI_FVB_ATTRIBUTES                  *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Modifies the current settings of the firmware volume according to the input parameter.\r
+\r
+Arguments:\r
+  This - Calling context\r
+  Attributes - input buffer which contains attributes\r
+\r
+Returns:\r
+  EFI_SUCCESS -  The firmware volume attributes were returned.\r
+  EFI_INVALID_PARAMETER  -  The attributes requested are in conflict with the capabilities as\r
+                             declared in the firmware volume header.\r
+  EFI_UNSUPPORTED        -  Not supported.\r
+--*/\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockEraseBlock (\r
+  IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *This,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  The EraseBlock() function erases one or more blocks as denoted by the \r
+variable argument list. The entire parameter list of blocks must be verified\r
+prior to erasing any blocks.  If a block is requested that does not exist \r
+within the associated firmware volume (it has a larger index than the last \r
+block of the firmware volume), the EraseBlock() function must return\r
+EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.\r
+\r
+Arguments:\r
+  This - Calling context\r
+  ...  - Starting LBA followed by Number of Lba to erase. a -1 to terminate\r
+           the list.\r
+    \r
+Returns:\r
+  EFI_SUCCESS   -  The erase request was successfully completed.\r
+  EFI_ACCESS_DENIED   -  The firmware volume is in the WriteDisabled state.\r
+  EFI_DEVICE_ERROR    -  The block device is not functioning correctly and could not be\r
+                         written. The firmware device may have been partially erased.\r
+  EFI_INVALID_PARAMETER  -  One or more of the LBAs listed in the variable argument list do\r
+  EFI_UNSUPPORTED        -  Not supported.\r
+    \r
+--*/\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockReadBlock (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL   *This,\r
+  IN CONST  EFI_LBA                              Lba,\r
+  IN CONST  UINTN                                Offset,\r
+  IN OUT    UINTN                                *NumBytes,\r
+  IN OUT    UINT8                                *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Read the specified number of bytes from the block to the input buffer.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Lba           -  The starting logical block index to read.\r
+  Offset        -  Offset into the block at which to begin reading.\r
+  NumBytes      -  Pointer to a UINT32. At entry, *NumBytes contains the\r
+                   total size of the buffer. At exit, *NumBytes contains the\r
+                   total number of bytes actually read.\r
+  Buffer        -  Pinter to a caller-allocated buffer that contains the destine\r
+                   for the read.    \r
+\r
+Returns:      \r
+  EFI_SUCCESS  -  The firmware volume was read successfully.\r
+  EFI_BAD_BUFFER_SIZE -  The read was attempted across an LBA boundary.\r
+  EFI_ACCESS_DENIED  -  Access denied.\r
+  EFI_DEVICE_ERROR   -  The block device is malfunctioning and could not be read.\r
+--*/\r
+{\r
+  EFI_FW_VOL_BLOCK_DEVICE               *FvbDevice;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;\r
+  UINT8                                 *LbaOffset;\r
+  UINTN                                 LbaStart;\r
+  UINTN                                 NumOfBytesRead;\r
+  UINTN                                 LbaIndex;\r
+  \r
+  FvbDevice = FVB_DEVICE_FROM_THIS (This);\r
+\r
+  //\r
+  // Check if This FW can be read\r
+  //\r
+  if ((FvbDevice->FvbAttributes & EFI_FVB_READ_STATUS) == 0) {\r
+    return EFI_ACCESS_DENIED;\r
+  }\r
+  \r
+  LbaIndex = (UINTN)Lba;\r
+  if (LbaIndex >= FvbDevice->NumBlocks) {\r
+    //\r
+    // Invalid Lba, read nothing.\r
+    //\r
+    *NumBytes = 0;\r
+    return EFI_BAD_BUFFER_SIZE;\r
+  }\r
+  \r
+  if (Offset > FvbDevice->LbaCache[LbaIndex].Length) {\r
+    //\r
+    // all exceed boundry, read nothing.\r
+    //\r
+    *NumBytes = 0;\r
+    return EFI_BAD_BUFFER_SIZE;\r
+  }\r
+  \r
+  NumOfBytesRead = *NumBytes;\r
+  if (Offset + NumOfBytesRead > FvbDevice->LbaCache[LbaIndex].Length) {\r
+    //\r
+    // partial exceed boundry, read data from current postion to end.\r
+    //\r
+    NumOfBytesRead = FvbDevice->LbaCache[LbaIndex].Length - Offset;\r
+  }\r
+  \r
+  LbaStart = FvbDevice->LbaCache[LbaIndex].Base;\r
+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINTN)FvbDevice->BaseAddress);\r
+  LbaOffset = (UINT8 *)FwVolHeader + LbaStart + Offset;\r
+\r
+  //\r
+  // Perform read operation\r
+  //\r
+  CopyMem (Buffer, LbaOffset, NumOfBytesRead);\r
+  \r
+  if (NumOfBytesRead == *NumBytes) {\r
+    return EFI_SUCCESS;\r
+  }\r
+    \r
+  *NumBytes = NumOfBytesRead;\r
+  return EFI_BAD_BUFFER_SIZE;\r
+}\r
+  \r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockWriteBlock (\r
+  IN     EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL   *This,\r
+  IN     EFI_LBA                              Lba,\r
+  IN     UINTN                                Offset,\r
+  IN OUT UINTN                                *NumBytes,\r
+  IN     UINT8                                *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Writes the specified number of bytes from the input buffer to the block.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Lba           -  The starting logical block index to write to.\r
+  Offset        -  Offset into the block at which to begin writing.\r
+  NumBytes      -  Pointer to a UINT32. At entry, *NumBytes contains the\r
+                   total size of the buffer. At exit, *NumBytes contains the\r
+                   total number of bytes actually written.\r
+  Buffer        -  Pinter to a caller-allocated buffer that contains the source\r
+                   for the write.    \r
+\r
+Returns:     \r
+  EFI_SUCCESS  -  The firmware volume was written successfully.\r
+  EFI_BAD_BUFFER_SIZE -  The write was attempted across an LBA boundary. On output,\r
+                         NumBytes contains the total number of bytes actually written.\r
+  EFI_ACCESS_DENIED  -  The firmware volume is in the WriteDisabled state.\r
+  EFI_DEVICE_ERROR   -  The block device is malfunctioning and could not be written.\r
+  EFI_UNSUPPORTED    -  Not supported.\r
+--*/\r
+{\r
+  return EFI_UNSUPPORTED;\r
+}\r
\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetPhysicalAddress (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  OUT       EFI_PHYSICAL_ADDRESS                *Address\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Get Fvb's base address.\r
+\r
+Arguments:\r
+  This          -  Indicates the calling context.\r
+  Address       -  Fvb device base address.\r
+\r
+Returns:     \r
+  EFI_SUCCESS  -  Successfully got Fvb's base address.\r
+  EFI_UNSUPPORTED -  Not supported.\r
+--*/\r
+{\r
+  EFI_FW_VOL_BLOCK_DEVICE               *FvbDevice;\r
+  \r
+  FvbDevice = FVB_DEVICE_FROM_THIS (This);\r
+  \r
+  if (FvbDevice->FvbAttributes & EFI_FVB_MEMORY_MAPPED) {\r
+    *Address = FvbDevice->BaseAddress;\r
+    return EFI_SUCCESS;\r
+  }\r
+  \r
+  return EFI_UNSUPPORTED;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockGetBlockSize (\r
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *This,\r
+  IN CONST  EFI_LBA                             Lba,\r
+  IN OUT    UINTN                               *BlockSize,\r
+  IN OUT    UINTN                               *NumberOfBlocks\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Retrieves the size in bytes of a specific block within a firmware volume.\r
+\r
+Arguments:\r
+  This            -  Indicates the calling context.\r
+  Lba             -  Indicates the block for which to return the size.\r
+  BlockSize       -  Pointer to a caller-allocated UINTN in which the size of the\r
+                     block is returned.\r
+  NumberOfBlocks  -  Pointer to a caller-allocated UINTN in which the number of\r
+                     consecutive blocks starting with Lba is returned. All blocks\r
+                     in this range have a size of BlockSize.   \r
+Returns:\r
+  EFI_SUCCESS  -  The firmware volume base address is returned.\r
+  EFI_INVALID_PARAMETER  -  The requested LBA is out of range.\r
+--*/\r
+{\r
+  UINTN                                 TotalBlocks;\r
+  EFI_FW_VOL_BLOCK_DEVICE               *FvbDevice;\r
+  EFI_FV_BLOCK_MAP_ENTRY                *PtrBlockMapEntry;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;\r
+  \r
+  FvbDevice = FVB_DEVICE_FROM_THIS (This);\r
+  \r
+  //\r
+  // Do parameter checking\r
+  //\r
+  if (Lba >= FvbDevice->NumBlocks) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINTN)FvbDevice->BaseAddress);\r
+  \r
+  PtrBlockMapEntry = FwVolHeader->BlockMap;\r
+  \r
+  //\r
+  // Search the block map for the given block\r
+  //\r
+  TotalBlocks = 0;\r
+  while ((PtrBlockMapEntry->NumBlocks != 0) || (PtrBlockMapEntry->Length !=0 )) {\r
+    TotalBlocks += PtrBlockMapEntry->NumBlocks;\r
+    if (Lba < TotalBlocks) {\r
+      //\r
+      // We find the range\r
+      //\r
+      break;\r
+    }\r
+    \r
+    PtrBlockMapEntry++;\r
+  }\r
+  \r
+  *BlockSize = PtrBlockMapEntry->Length;\r
+  *NumberOfBlocks = TotalBlocks - (UINTN)Lba;\r
+  \r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+ProduceFVBProtocolOnBuffer (\r
+  IN EFI_PHYSICAL_ADDRESS   BaseAddress,\r
+  IN UINT64                 Length,\r
+  IN EFI_HANDLE             ParentHandle,\r
+  OUT EFI_HANDLE            *FvProtocol  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine produces a firmware volume block protocol on a given\r
+    buffer. \r
+\r
+Arguments:\r
+    BaseAddress     - base address of the firmware volume image\r
+    Length          - length of the firmware volume image\r
+    ParentHandle    - handle of parent firmware volume, if this\r
+                      image came from an FV image file in another\r
+                      firmware volume (ala capsules)\r
+    FvProtocol      - Firmware volume block protocol produced.\r
+    \r
+Returns:\r
+    EFI_VOLUME_CORRUPTED    - Volume corrupted.\r
+    EFI_OUT_OF_RESOURCES    - No enough buffer to be allocated.\r
+    EFI_SUCCESS             - Successfully produced a FVB protocol on given buffer.\r
+                     \r
+--*/\r
+{\r
+  EFI_STATUS                    Status;\r
+  EFI_FW_VOL_BLOCK_DEVICE       *FvbDev;\r
+  EFI_FIRMWARE_VOLUME_HEADER    *FwVolHeader;\r
+  UINTN                         BlockIndex;\r
+  UINTN                         BlockIndex2;\r
+  UINTN                         LinearOffset;\r
+  EFI_FV_BLOCK_MAP_ENTRY        *PtrBlockMapEntry;\r
+\r
+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;\r
+  //\r
+  // Validate FV Header, if not as expected, return\r
+  //\r
+  if (FwVolHeader->Signature != EFI_FVH_SIGNATURE) {\r
+    return EFI_VOLUME_CORRUPTED;\r
+  }\r
+  //\r
+  // Allocate EFI_FW_VOL_BLOCK_DEVICE \r
+  //\r
+  FvbDev = CoreAllocateCopyPool (sizeof (EFI_FW_VOL_BLOCK_DEVICE), &mFwVolBlock);\r
+  if (FvbDev == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  FvbDev->BaseAddress   = BaseAddress;\r
+  FvbDev->FvbAttributes = FwVolHeader->Attributes;\r
+  FvbDev->FwVolBlockInstance.ParentHandle = ParentHandle;\r
+\r
+  //\r
+  // Init the block caching fields of the device\r
+  // First, count the number of blocks\r
+  //\r
+  FvbDev->NumBlocks = 0;\r
+  for (PtrBlockMapEntry = FwVolHeader->BlockMap;\r
+        PtrBlockMapEntry->NumBlocks != 0;\r
+        PtrBlockMapEntry++) {\r
+    FvbDev->NumBlocks += PtrBlockMapEntry->NumBlocks;\r
+  }\r
+  //\r
+  // Second, allocate the cache\r
+  //\r
+  FvbDev->LbaCache = CoreAllocateBootServicesPool (FvbDev->NumBlocks * sizeof (LBA_CACHE));\r
+  if (FvbDev->LbaCache == NULL) {\r
+    CoreFreePool (FvbDev);\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+  //\r
+  // Last, fill in the cache with the linear address of the blocks\r
+  //\r
+  BlockIndex = 0;\r
+  LinearOffset = 0;\r
+  for (PtrBlockMapEntry = FwVolHeader->BlockMap;\r
+        PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {\r
+    for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) {\r
+      FvbDev->LbaCache[BlockIndex].Base = LinearOffset;\r
+      FvbDev->LbaCache[BlockIndex].Length = PtrBlockMapEntry->Length;\r
+      LinearOffset += PtrBlockMapEntry->Length;\r
+      BlockIndex++;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Set up the devicepath\r
+  //\r
+  FvbDev->DevicePath.MemMapDevPath.StartingAddress = BaseAddress;\r
+  FvbDev->DevicePath.MemMapDevPath.EndingAddress = BaseAddress + FwVolHeader->FvLength - 1;\r
+\r
+  //\r
+  //\r
+  // Attach FvVolBlock Protocol to new handle\r
+  //\r
+  Status = CoreInstallMultipleProtocolInterfaces (\r
+            &FvbDev->Handle,\r
+            &gEfiFirmwareVolumeBlockProtocolGuid,     &FvbDev->FwVolBlockInstance,\r
+            &gEfiDevicePathProtocolGuid,              &FvbDev->DevicePath,\r
+            &gEfiFirmwareVolumeDispatchProtocolGuid,  NULL,\r
+            NULL\r
+            );\r
+\r
+  //\r
+  // If they want the handle back, set it.\r
+  //\r
+  if (FvProtocol != NULL) {\r
+    *FvProtocol = FvbDev->Handle;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FwVolBlockDriverInit (\r
+  IN EFI_HANDLE                 ImageHandle,\r
+  IN EFI_SYSTEM_TABLE           *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This routine is the driver initialization entry point.  It initializes the\r
+    libraries, consumes FV hobs and NT_NON_MM_FV environment variable and\r
+    produces instances of FW_VOL_BLOCK_PROTOCOL as appropriate.\r
+Arguments:\r
+    ImageHandle   - The image handle.\r
+    SystemTable   - The system table.\r
+Returns:\r
+    EFI_SUCCESS   - Successfully initialized firmware volume block driver.\r
+--*/\r
+{\r
+  EFI_PEI_HOB_POINTERS          FvHob;\r
+  //\r
+  // Core Needs Firmware Volumes to function\r
+  //\r
+  FvHob.Raw = GetHobList ();\r
+  while ((FvHob.Raw = GetNextHob (EFI_HOB_TYPE_FV, FvHob.Raw)) != NULL) {\r
+    //\r
+    // Produce an FVB protocol for it\r
+    //\r
+    ProduceFVBProtocolOnBuffer (FvHob.FirmwareVolume->BaseAddress, FvHob.FirmwareVolume->Length, NULL, NULL);    \r
+    FvHob.Raw = GET_NEXT_HOB (FvHob);\r
+  }\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreProcessFirmwareVolume (\r
+  IN VOID                             *FvHeader,\r
+  IN UINTN                            Size, \r
+  OUT EFI_HANDLE                      *FVProtocolHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    This DXE service routine is used to process a firmware volume. In\r
+    particular, it can be called by BDS to process a single firmware\r
+    volume found in a capsule. \r
+\r
+Arguments:\r
+    FvHeader              - pointer to a firmware volume header\r
+    Size                  - the size of the buffer pointed to by FvHeader\r
+    FVProtocolHandle      - the handle on which a firmware volume protocol\r
+                            was produced for the firmware volume passed in.\r
+\r
+Returns:\r
+    EFI_OUT_OF_RESOURCES  - if an FVB could not be produced due to lack of \r
+                            system resources\r
+    EFI_VOLUME_CORRUPTED  - if the volume was corrupted\r
+    EFI_SUCCESS           - a firmware volume protocol was produced for the\r
+                            firmware volume\r
+\r
+--*/\r
+{\r
+  VOID        *Ptr;\r
+  EFI_STATUS  Status;\r
+\r
+  *FVProtocolHandle = NULL;\r
+  Status = ProduceFVBProtocolOnBuffer ( \r
+            (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, \r
+            (UINT64)Size, \r
+            NULL, \r
+            FVProtocolHandle\r
+            );\r
+  //\r
+  // Since in our implementation we use register-protocol-notify to put a\r
+  // FV protocol on the FVB protocol handle, we can't directly verify that\r
+  // the FV protocol was produced. Therefore here we will check the handle\r
+  // and make sure an FV protocol is on it. This indicates that all went \r
+  // well. Otherwise we have to assume that the volume was corrupted \r
+  // somehow.\r
+  //\r
+  if (!EFI_ERROR(Status)) {\r
+    Ptr = NULL;\r
+    Status = CoreHandleProtocol (*FVProtocolHandle, &gEfiFirmwareVolumeProtocolGuid, (VOID **)&Ptr);\r
+    if (EFI_ERROR(Status) || (Ptr == NULL)) {\r
+      return EFI_VOLUME_CORRUPTED;\r
+    }\r
+    return EFI_SUCCESS;\r
+  }\r
+  return Status;\r
+}\r
+\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/FwVolDriver.h b/MdeModulePkg/Core/Dxe/FwVolDriver.h
new file mode 100644 (file)
index 0000000..fb4e0d5
--- /dev/null
@@ -0,0 +1,466 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  FwVolDriver.h\r
+\r
+Abstract:\r
+\r
+  Firmware File System protocol. Layers on top of Firmware\r
+  Block protocol to produce a file abstraction of FV based files.\r
+\r
+--*/\r
+\r
+#ifndef __FWVOL_H\r
+#define __FWVOL_H\r
+\r
+\r
+//\r
+// Used to track all non-deleted files\r
+//\r
+typedef struct {\r
+  LIST_ENTRY                      Link;\r
+  EFI_FFS_FILE_HEADER             *FfsHeader;\r
+  UINTN                           StreamHandle;\r
+  EFI_SECTION_EXTRACTION_PROTOCOL *Sep;\r
+} FFS_FILE_LIST_ENTRY;\r
+\r
+typedef struct {\r
+  UINTN                                   Signature;\r
+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL      *Fvb;\r
+  EFI_HANDLE                              Handle;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL            Fv;\r
+\r
+  EFI_FIRMWARE_VOLUME_HEADER              *FwVolHeader;\r
+  UINT8                                   *CachedFv;\r
+  UINT8                                   *EndOfCachedFv;\r
+\r
+  FFS_FILE_LIST_ENTRY                     *LastKey;\r
+\r
+  LIST_ENTRY                              FfsFileListHeader;\r
+\r
+  UINT8                                   ErasePolarity;\r
+} FV_DEVICE;\r
+\r
+#define FV_DEVICE_FROM_THIS(a) CR(a, FV_DEVICE, Fv, FV_DEVICE_SIGNATURE)\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvGetVolumeAttributes (\r
+  IN    EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  OUT   EFI_FV_ATTRIBUTES              *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Retrieves attributes, insures positive polarity of attribute bits, returns\r
+    resulting attributes in output parameter\r
+\r
+Arguments:\r
+    This        - Calling context\r
+    Attributes  - output buffer which contains attributes\r
+\r
+Returns:\r
+    EFI_SUCCESS         - Successfully got volume attributes\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvSetVolumeAttributes (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN OUT EFI_FV_ATTRIBUTES              *Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Sets current attributes for volume\r
+\r
+Arguments:\r
+    This       - Calling context\r
+    Attributes - At input, contains attributes to be set.  At output contains\r
+      new value of FV\r
+\r
+Returns:\r
+    EFI_UNSUPPORTED   - Could not be set.\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvGetNextFile (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN OUT VOID                           *Key,\r
+  IN OUT EFI_FV_FILETYPE                *FileType,\r
+  OUT    EFI_GUID                       *NameGuid,\r
+  OUT    EFI_FV_FILE_ATTRIBUTES         *Attributes,\r
+  OUT    UINTN                          *Size\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Given the input key, search for the next matching file in the volume.\r
+\r
+Arguments:\r
+    This          -   Indicates the calling context.\r
+    FileType      -   FileType is a pointer to a caller allocated\r
+                      EFI_FV_FILETYPE. The GetNextFile() API can filter it's\r
+                      search for files based on the value of *FileType input.\r
+                      A *FileType input of 0 causes GetNextFile() to search for\r
+                      files of all types.  If a file is found, the file's type\r
+                      is returned in *FileType.  *FileType is not modified if\r
+                      no file is found.\r
+    Key           -   Key is a pointer to a caller allocated buffer that\r
+                      contains implementation specific data that is used to\r
+                      track where to begin the search for the next file.\r
+                      The size of the buffer must be at least This->KeySize\r
+                      bytes long. To reinitialize the search and begin from\r
+                      the beginning of the firmware volume, the entire buffer\r
+                      must be cleared to zero. Other than clearing the buffer\r
+                      to initiate a new search, the caller must not modify the\r
+                      data in the buffer between calls to GetNextFile().\r
+    NameGuid      -   NameGuid is a pointer to a caller allocated EFI_GUID.\r
+                      If a file is found, the file's name is returned in\r
+                      *NameGuid.  *NameGuid is not modified if no file is\r
+                      found.\r
+    Attributes    -   Attributes is a pointer to a caller allocated\r
+                      EFI_FV_FILE_ATTRIBUTES.  If a file is found, the file's\r
+                      attributes are returned in *Attributes. *Attributes is\r
+                      not modified if no file is found.\r
+    Size          -   Size is a pointer to a caller allocated UINTN.\r
+                      If a file is found, the file's size is returned in *Size.\r
+                      *Size is not modified if no file is found.\r
+\r
+Returns:    \r
+    EFI_SUCCESS                 - Successfully find the file.\r
+    EFI_DEVICE_ERROR            - Device error.\r
+    EFI_ACCESS_DENIED           - Fv could not read.\r
+    EFI_NOT_FOUND               - No matching file found.\r
+    EFI_INVALID_PARAMETER       - Invalid parameter\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvReadFile (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN     EFI_GUID                       *NameGuid,\r
+  IN OUT VOID                           **Buffer,\r
+  IN OUT UINTN                          *BufferSize,\r
+  OUT    EFI_FV_FILETYPE                *FoundType,\r
+  OUT    EFI_FV_FILE_ATTRIBUTES         *FileAttributes,\r
+  OUT    UINT32                         *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Locates a file in the firmware volume and\r
+    copies it to the supplied buffer.\r
+\r
+Arguments:\r
+    This              -   Indicates the calling context.\r
+    NameGuid          -   Pointer to an EFI_GUID, which is the filename.\r
+    Buffer            -   Buffer is a pointer to pointer to a buffer in\r
+                          which the file or section contents or are returned.\r
+    BufferSize        -   BufferSize is a pointer to caller allocated\r
+                          UINTN. On input *BufferSize indicates the size\r
+                          in bytes of the memory region pointed to by\r
+                          Buffer. On output, *BufferSize contains the number\r
+                          of bytes required to read the file.\r
+    FoundType         -   FoundType is a pointer to a caller allocated\r
+                          EFI_FV_FILETYPE that on successful return from Read()\r
+                          contains the type of file read.  This output reflects\r
+                          the file type irrespective of the value of the\r
+                          SectionType input.\r
+    FileAttributes    -   FileAttributes is a pointer to a caller allocated\r
+                          EFI_FV_FILE_ATTRIBUTES.  On successful return from\r
+                          Read(), *FileAttributes contains the attributes of\r
+                          the file read.\r
+    AuthenticationStatus -  AuthenticationStatus is a pointer to a caller\r
+                          allocated UINTN in which the authentication status\r
+                          is returned.\r
+Returns:\r
+    EFI_SUCCESS                   - Successfully read to memory buffer.\r
+    EFI_WARN_BUFFER_TOO_SMALL     - Buffer too small.\r
+    EFI_NOT_FOUND                 - Not found.\r
+    EFI_DEVICE_ERROR              - Device error.\r
+    EFI_ACCESS_DENIED             - Could not read.\r
+    EFI_INVALID_PARAMETER         - Invalid parameter.\r
+    EFI_OUT_OF_RESOURCES          - Not enough buffer to be allocated.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvReadFileSection (\r
+  IN     EFI_FIRMWARE_VOLUME_PROTOCOL   *This,\r
+  IN     EFI_GUID                       *NameGuid,\r
+  IN     EFI_SECTION_TYPE               SectionType,\r
+  IN     UINTN                          SectionInstance,\r
+  IN OUT VOID                           **Buffer,\r
+  IN OUT UINTN                          *BufferSize,\r
+  OUT    UINT32                         *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+    Locates a section in a given FFS File and\r
+    copies it to the supplied buffer (not including section header).\r
+\r
+  Arguments:\r
+    This              -   Indicates the calling context.\r
+    NameGuid          -   Pointer to an EFI_GUID, which is the filename.\r
+    SectionType       -   Indicates the section type to return.\r
+    SectionInstance   -   Indicates which instance of sections with a type of\r
+                          SectionType to return.\r
+    Buffer            -   Buffer is a pointer to pointer to a buffer in which\r
+                          the file or section contents or are returned.\r
+    BufferSize        -   BufferSize is a pointer to caller allocated UINTN.\r
+    AuthenticationStatus -AuthenticationStatus is a pointer to a caller\r
+                          allocated UINT32 in which the authentication status\r
+                          is returned.\r
+\r
+  Returns:\r
+    EFI_SUCCESS                     - Successfully read the file section into buffer.\r
+    EFI_WARN_BUFFER_TOO_SMALL       - Buffer too small.\r
+    EFI_NOT_FOUND                   - Section not found.\r
+    EFI_DEVICE_ERROR                - Device error.\r
+    EFI_ACCESS_DENIED               - Could not read.\r
+    EFI_INVALID_PARAMETER           - Invalid parameter.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+FvWriteFile (\r
+  IN EFI_FIRMWARE_VOLUME_PROTOCOL       *This,\r
+  IN UINT32                             NumberOfFiles,\r
+  IN EFI_FV_WRITE_POLICY                WritePolicy,\r
+  IN EFI_FV_WRITE_FILE_DATA             *FileData\r
+  )\r
+/*++\r
+\r
+    Routine Description:\r
+      Writes one or more files to the firmware volume.\r
+\r
+    Arguments:\r
+    This        - Indicates the calling context.\r
+    WritePolicy - WritePolicy indicates the level of reliability for\r
+                  the write in the event of a power failure or other\r
+                  system failure during the write operation.\r
+    FileData    - FileData is an pointer to an array of EFI_FV_WRITE_DATA.\r
+                  Each element of FileData[] represents a file to be written.\r
+\r
+    Returns:\r
+      EFI_SUCCESS                   - Files successfully written to firmware volume\r
+      EFI_OUT_OF_RESOURCES          - Not enough buffer to be allocated.\r
+      EFI_DEVICE_ERROR              - Device error.\r
+      EFI_WRITE_PROTECTED           - Write protected.\r
+      EFI_NOT_FOUND                 - Not found.\r
+      EFI_INVALID_PARAMETER         - Invalid parameter.\r
+      EFI_UNSUPPORTED               - This function not supported.\r
+\r
+--*/\r
+;\r
+\r
+\r
+  \r
+//\r
+//Internal functions\r
+//\r
+typedef enum {\r
+  EfiCheckSumUint8    = 0,\r
+  EfiCheckSumUint16   = 1,\r
+  EfiCheckSumUint32   = 2,\r
+  EfiCheckSumUint64   = 3,\r
+  EfiCheckSumMaximum  = 4\r
+} EFI_CHECKSUM_TYPE;\r
+\r
+\r
+BOOLEAN\r
+IsBufferErased (\r
+  IN UINT8    ErasePolarity,\r
+  IN VOID     *Buffer,\r
+  IN UINTN    BufferSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if a block of buffer is erased\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  Buffer        -  The buffer to be checked\r
+  BufferSize    -  Size of the buffer in bytes\r
+    \r
+Returns:\r
+  TRUE  -  The block of buffer is erased\r
+  FALSE -  The block of buffer is not erased\r
+    \r
+--*/\r
+;\r
+\r
+EFI_FFS_FILE_STATE \r
+GetFileState (\r
+  IN UINT8                ErasePolarity,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Get the FFS file state by checking the highest bit set in the header's state field\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file header\r
+    \r
+Returns:\r
+  FFS File state \r
+    \r
+--*/\r
+;\r
+\r
+VOID\r
+SetFileState (\r
+  IN UINT8                State,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Set the FFS file state.\r
+\r
+Arguments:\r
+  State         -  The state to be set.\r
+  FfsHeader     -  Points to the FFS file header\r
+    \r
+Returns:\r
+  None.\r
+    \r
+--*/\r
+;\r
+\r
+BOOLEAN\r
+VerifyFvHeaderChecksum (\r
+  IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Verify checksum of the firmware volume header \r
+\r
+Arguments:\r
+  FvHeader  -  Points to the firmware volume header to be checked\r
+    \r
+Returns:\r
+  TRUE  -  Checksum verification passed\r
+  FALSE -  Checksum verification failed\r
+    \r
+--*/\r
+;\r
+    \r
+BOOLEAN\r
+IsValidFfsHeader (\r
+  IN  UINT8                ErasePolarity,\r
+  IN  EFI_FFS_FILE_HEADER  *FfsHeader,\r
+  OUT EFI_FFS_FILE_STATE   *FileState\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if it's a valid FFS file header\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file header to be checked\r
+  FileState     -  FFS file state to be returned\r
+    \r
+Returns:\r
+  TRUE  -  Valid FFS file header\r
+  FALSE -  Invalid FFS file header\r
+    \r
+--*/\r
+;\r
+\r
+BOOLEAN\r
+IsValidFfsFile (\r
+  IN UINT8                ErasePolarity,\r
+  IN EFI_FFS_FILE_HEADER  *FfsHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if it's a valid FFS file. \r
+  Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first.\r
+\r
+Arguments:\r
+  ErasePolarity -  Erase polarity attribute of the firmware volume\r
+  FfsHeader     -  Points to the FFS file to be checked\r
+    \r
+Returns:\r
+  TRUE  -  Valid FFS file\r
+  FALSE -  Invalid FFS file\r
+    \r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+GetFwVolHeader (\r
+  IN  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL      *Fvb,\r
+  OUT EFI_FIRMWARE_VOLUME_HEADER              **FwVolHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  given the supplied FW_VOL_BLOCK_PROTOCOL, allocate a buffer for output and\r
+  copy the volume header into it.\r
+\r
+Arguments:\r
+  Fvb - The FW_VOL_BLOCK_PROTOCOL instance from which to read the volume\r
+          header\r
+  FwVolHeader - Pointer to pointer to allocated buffer in which the volume\r
+                  header is returned.\r
+\r
+Returns:\r
+  Status code.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+FvCheck (\r
+  IN OUT FV_DEVICE  *FvDevice\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if a FV is consistent and allocate cache\r
+\r
+Arguments:\r
+  FvDevice - pointer to the FvDevice to be checked.\r
+\r
+Returns:\r
+  EFI_OUT_OF_RESOURCES    - Not enough buffer to be allocated.\r
+  EFI_SUCCESS             - FV is consistent and cache is allocated.\r
+  EFI_VOLUME_CORRUPTED    - File system is corrupted.\r
+\r
+--*/\r
+;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/Gcd/gcd.c b/MdeModulePkg/Core/Dxe/Gcd/gcd.c
new file mode 100644 (file)
index 0000000..be3dbdd
--- /dev/null
@@ -0,0 +1,2495 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+    gcd.c\r
+\r
+Abstract:\r
+    The file contains the GCD related services in the EFI Boot Services Table.\r
+    The GCD services are used to manage the memory and I/O regions that \r
+    are accessible to the CPU that is executing the DXE core.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define MINIMUM_INITIAL_MEMORY_SIZE 0x10000\r
+\r
+#define MEMORY_ATTRIBUTE_MASK         (EFI_RESOURCE_ATTRIBUTE_PRESENT             | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_INITIALIZED         | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_TESTED              | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED      | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED     | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_16_BIT_IO           | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_32_BIT_IO           | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_64_BIT_IO           ) \r
+\r
+#define TESTED_MEMORY_ATTRIBUTES      (EFI_RESOURCE_ATTRIBUTE_PRESENT     | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_INITIALIZED | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_TESTED      )\r
+\r
+#define INITIALIZED_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT     | \\r
+                                       EFI_RESOURCE_ATTRIBUTE_INITIALIZED )\r
+\r
+#define PRESENT_MEMORY_ATTRIBUTES     (EFI_RESOURCE_ATTRIBUTE_PRESENT)\r
+\r
+#define INVALID_CPU_ARCH_ATTRIBUTES   0xffffffff\r
+\r
+//\r
+// Module Variables\r
+//\r
+EFI_LOCK           mGcdMemorySpaceLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
+EFI_LOCK           mGcdIoSpaceLock     = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
+LIST_ENTRY         mGcdMemorySpaceMap  = INITIALIZE_LIST_HEAD_VARIABLE (mGcdMemorySpaceMap);\r
+LIST_ENTRY         mGcdIoSpaceMap      = INITIALIZE_LIST_HEAD_VARIABLE (mGcdIoSpaceMap);\r
+\r
+EFI_GCD_MAP_ENTRY mGcdMemorySpaceMapEntryTemplate = {\r
+  EFI_GCD_MAP_SIGNATURE,\r
+  { NULL, NULL },\r
+  0,\r
+  0,\r
+  0,\r
+  0,\r
+  EfiGcdMemoryTypeNonExistent,\r
+  (EFI_GCD_IO_TYPE) 0,\r
+  NULL,\r
+  NULL\r
+};\r
+\r
+EFI_GCD_MAP_ENTRY mGcdIoSpaceMapEntryTemplate = {\r
+  EFI_GCD_MAP_SIGNATURE,\r
+  { NULL, NULL },\r
+  0,\r
+  0,\r
+  0,\r
+  0,\r
+  (EFI_GCD_MEMORY_TYPE) 0,\r
+  EfiGcdIoTypeNonExistent,\r
+  NULL,\r
+  NULL\r
+};\r
+\r
+GCD_ATTRIBUTE_CONVERSION_ENTRY mAttributeConversionTable[] = {\r
+  { EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE,             EFI_MEMORY_UC,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_UNCACHED_EXPORTED,       EFI_MEMORY_UCE,         TRUE  },   \r
+  { EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE,       EFI_MEMORY_WC,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE, EFI_MEMORY_WT,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE,    EFI_MEMORY_WB,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED,          EFI_MEMORY_RP,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED,         EFI_MEMORY_WP,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED,     EFI_MEMORY_XP,          TRUE  },\r
+  { EFI_RESOURCE_ATTRIBUTE_PRESENT,                 EFI_MEMORY_PRESENT,     FALSE },\r
+  { EFI_RESOURCE_ATTRIBUTE_INITIALIZED,             EFI_MEMORY_INITIALIZED, FALSE },\r
+  { EFI_RESOURCE_ATTRIBUTE_TESTED,                  EFI_MEMORY_TESTED,      FALSE },\r
+  { 0, 0, FALSE }\r
+};\r
+\r
+VOID\r
+CoreAcquireGcdMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Acquire memory lock on mGcdMemorySpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+{\r
+  CoreAcquireLock (&mGcdMemorySpaceLock);\r
+}\r
+\r
+\r
+VOID\r
+CoreReleaseGcdMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Release memory lock on mGcdMemorySpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&mGcdMemorySpaceLock);\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+CoreAcquireGcdIoLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Acquire memory lock on mGcdIoSpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+{\r
+  CoreAcquireLock (&mGcdIoSpaceLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreReleaseGcdIoLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+    Release memory lock on mGcdIoSpaceLock\r
+\r
+Arguments:\r
+    None\r
+\r
+Returns:\r
+    None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&mGcdIoSpaceLock);\r
+}\r
+\r
+\r
+\r
+//\r
+// GCD Initialization Worker Functions\r
+//\r
+STATIC\r
+UINT64\r
+AlignValue (\r
+  IN UINT64   Value,\r
+  IN UINTN    Alignment,\r
+  IN BOOLEAN  RoundUp\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Aligns a value to the specified boundary.\r
+\r
+Arguments:\r
+\r
+  Value     - 64 bit value to align\r
+  Alignment - Log base 2 of the boundary to align Value to\r
+  RoundUp   - TRUE if Value is to be rounded up to the nearest aligned boundary. \r
+              FALSE is Value is to be rounded down to the nearest aligned boundary.\r
+\r
+Returns:\r
+\r
+  A 64 bit value is the aligned to the value nearest Value with an alignment by Alignment.\r
+\r
+--*/\r
+{\r
+  UINT64  AlignmentMask;\r
+\r
+  AlignmentMask = LShiftU64 (1, Alignment) - 1;\r
+  if (RoundUp) {\r
+    Value += AlignmentMask;\r
+  }\r
+  return Value & (~AlignmentMask);\r
+}\r
+\r
+STATIC\r
+UINT64\r
+PageAlignAddress (\r
+  IN UINT64 Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Aligns address to the page boundary.\r
+\r
+Arguments:\r
+\r
+  Value     - 64 bit address to align\r
+\r
+Returns:\r
+\r
+  A 64 bit value is the aligned to the value nearest Value with an alignment by Alignment.\r
+\r
+--*/\r
+{\r
+  return AlignValue (Value, EFI_PAGE_SHIFT, TRUE);\r
+}\r
+\r
+STATIC\r
+UINT64\r
+PageAlignLength (\r
+  IN UINT64 Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Aligns length to the page boundary.\r
+\r
+Arguments:\r
+\r
+  Value     - 64 bit length to align\r
+\r
+Returns:\r
+\r
+  A 64 bit value is the aligned to the value nearest Value with an alignment by Alignment.\r
+\r
+--*/\r
+{\r
+  return AlignValue (Value, EFI_PAGE_SHIFT, FALSE);\r
+}\r
+\r
+//\r
+// GCD Memory Space Worker Functions\r
+//\r
+STATIC\r
+EFI_STATUS\r
+CoreAllocateGcdMapEntry (\r
+  IN OUT EFI_GCD_MAP_ENTRY  **TopEntry,\r
+  IN OUT EFI_GCD_MAP_ENTRY  **BottomEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool for two entries.\r
+\r
+Arguments:\r
+\r
+  TopEntry      - An entry of GCD map\r
+  BottomEntry   - An entry of GCD map\r
+\r
+Returns:\r
+\r
+  EFI_OUT_OF_RESOURCES    - No enough buffer to be allocated.\r
+  EFI_SUCCESS             - Both entries successfully allocated.\r
+\r
+--*/\r
+{\r
+  *TopEntry = CoreAllocateZeroBootServicesPool (sizeof (EFI_GCD_MAP_ENTRY));\r
+  if (*TopEntry == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  *BottomEntry = CoreAllocateZeroBootServicesPool (sizeof (EFI_GCD_MAP_ENTRY));\r
+  if (*BottomEntry == NULL) {\r
+    CoreFreePool (*TopEntry);\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreInsertGcdMapEntry (\r
+  IN LIST_ENTRY           *Link,\r
+  IN EFI_GCD_MAP_ENTRY     *Entry,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN EFI_GCD_MAP_ENTRY     *TopEntry,\r
+  IN EFI_GCD_MAP_ENTRY     *BottomEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Inserts a new descriptor into a sorted list\r
+\r
+Arguments:\r
+\r
+  Link        - The linked list to insert the range BaseAddress and Length into\r
+\r
+  Entry     -   A pointer to the entry that is inserted\r
+\r
+  BaseAddress - The base address of the new range\r
+  \r
+  Length      - The length of the new range in bytes\r
+  \r
+  TopEntry    - Top pad entry to insert if needed.\r
+\r
+  BottomEntry - Bottom pad entry to insert if needed.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - The new range was inserted into the linked list\r
+  \r
+--*/\r
+{\r
+  ASSERT (Length != 0);\r
+  ASSERT (TopEntry->Signature == 0);\r
+  ASSERT (BottomEntry->Signature == 0);\r
+\r
+  if (BaseAddress > Entry->BaseAddress) {\r
+    CopyMem (BottomEntry, Entry, sizeof (EFI_GCD_MAP_ENTRY));\r
+    Entry->BaseAddress      = BaseAddress;\r
+    BottomEntry->EndAddress = BaseAddress - 1;\r
+    InsertTailList (Link, &BottomEntry->Link);\r
+  } \r
+\r
+  if ((BaseAddress + Length - 1) < Entry->EndAddress) {\r
+    CopyMem (TopEntry, Entry, sizeof (EFI_GCD_MAP_ENTRY));\r
+    TopEntry->BaseAddress = BaseAddress + Length;\r
+    Entry->EndAddress     = BaseAddress + Length - 1;\r
+    InsertHeadList (Link, &TopEntry->Link);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreMergeGcdMapEntry (\r
+  IN LIST_ENTRY      *Link,\r
+  IN BOOLEAN         Forward,\r
+  IN LIST_ENTRY      *Map\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Merge the Gcd region specified by Link and its adjacent entry\r
+\r
+Arguments:\r
+\r
+  Link      - Specify the entry to be merged (with its adjacent entry).\r
+  \r
+  Forward   - Direction (forward or backward).\r
+  \r
+  Map       - Boundary.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS     - Successfully returned.\r
+  \r
+  EFI_UNSUPPORTED - These adjacent regions could not merge.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY         *AdjacentLink;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+  EFI_GCD_MAP_ENTRY  *AdjacentEntry;\r
+\r
+  //\r
+  // Get adjacent entry\r
+  //\r
+  if (Forward) {\r
+    AdjacentLink = Link->ForwardLink;\r
+  } else {\r
+    AdjacentLink = Link->BackLink;\r
+  }\r
+\r
+  //\r
+  // If AdjacentLink is the head of the list, then no merge can be performed\r
+  //\r
+  if (AdjacentLink == Map) {\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  Entry         = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+  AdjacentEntry = CR (AdjacentLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+\r
+  if (Entry->Capabilities != AdjacentEntry->Capabilities) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  if (Entry->Attributes != AdjacentEntry->Attributes) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  if (Entry->GcdMemoryType != AdjacentEntry->GcdMemoryType) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  if (Entry->GcdIoType != AdjacentEntry->GcdIoType) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  if (Entry->ImageHandle != AdjacentEntry->ImageHandle) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  if (Entry->DeviceHandle != AdjacentEntry->DeviceHandle) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  if (Forward) {\r
+    Entry->EndAddress  = AdjacentEntry->EndAddress;\r
+  } else {\r
+    Entry->BaseAddress = AdjacentEntry->BaseAddress;\r
+  }\r
+  RemoveEntryList (AdjacentLink);\r
+  CoreFreePool (AdjacentEntry);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreCleanupGcdMapEntry (\r
+  IN EFI_GCD_MAP_ENTRY  *TopEntry,\r
+  IN EFI_GCD_MAP_ENTRY  *BottomEntry,\r
+  IN LIST_ENTRY         *StartLink,\r
+  IN LIST_ENTRY         *EndLink,\r
+  IN LIST_ENTRY         *Map\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Merge adjacent entries on total chain.\r
+\r
+Arguments:\r
+\r
+  TopEntry      - Top entry of GCD map.\r
+  \r
+  BottomEntry   - Bottom entry of GCD map.\r
+  \r
+  StartLink     - Start link of the list for this loop.\r
+  \r
+  EndLink       - End link of the list for this loop.\r
+  \r
+  Map           - Boundary.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - GCD map successfully cleaned up.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY  *Link;\r
+\r
+  if (TopEntry->Signature == 0) {\r
+    CoreFreePool (TopEntry);\r
+  }\r
+  if (BottomEntry->Signature == 0) {\r
+    CoreFreePool (BottomEntry);\r
+  }\r
+\r
+  Link = StartLink;\r
+  while (Link != EndLink->ForwardLink) {\r
+    CoreMergeGcdMapEntry (Link, FALSE, Map);\r
+    Link = Link->ForwardLink;\r
+  }\r
+  CoreMergeGcdMapEntry (EndLink, TRUE, Map);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreSearchGcdMapEntry (\r
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN  UINT64                Length,\r
+  OUT LIST_ENTRY            **StartLink,\r
+  OUT LIST_ENTRY            **EndLink,\r
+  IN  LIST_ENTRY            *Map\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Search a segment of memory space in GCD map. The result is a range of GCD entry list.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - The start address of the segment.\r
+  \r
+  Length            - The length of the segment.\r
+  \r
+  StartLink         - The first GCD entry involves this segment of memory space.\r
+  \r
+  EndLink           - The first GCD entry involves this segment of memory space.\r
+  \r
+  Map               - Points to the start entry to search.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully found the entry.\r
+  \r
+  EFI_NOT_FOUND     - Not found.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY         *Link;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+\r
+  ASSERT (Length != 0);\r
+\r
+  *StartLink = NULL;\r
+  *EndLink   = NULL;\r
+\r
+  Link = Map->ForwardLink;\r
+  while (Link != Map) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    if (BaseAddress >= Entry->BaseAddress && BaseAddress <= Entry->EndAddress) {\r
+      *StartLink = Link;\r
+    }\r
+    if (*StartLink != NULL) {\r
+      if ((BaseAddress + Length - 1) >= Entry->BaseAddress && \r
+          (BaseAddress + Length - 1) <= Entry->EndAddress     ) {\r
+        *EndLink = Link;\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+    Link = Link->ForwardLink;\r
+  }\r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+STATIC\r
+UINTN\r
+CoreCountGcdMapEntry (\r
+  IN LIST_ENTRY  *Map\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Count the amount of GCD map entries.\r
+\r
+Arguments:\r
+\r
+  Map       - Points to the start entry to do the count loop.\r
+\r
+Returns:\r
+\r
+  The count.\r
+\r
+--*/\r
+{\r
+  UINTN           Count;\r
+  LIST_ENTRY      *Link;\r
+\r
+  Count = 0;\r
+  Link = Map->ForwardLink;\r
+  while (Link != Map) {\r
+    Count++;\r
+    Link = Link->ForwardLink;\r
+  }\r
+  return Count;\r
+}\r
+\r
+\r
+STATIC\r
+UINT64\r
+ConverToCpuArchAttributes (\r
+  UINT64 Attributes\r
+  ) \r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return the memory attribute specified by Attributes\r
+\r
+Arguments:\r
+\r
+  Attributes        - A num with some attribute bits on.\r
+\r
+Returns:\r
+\r
+  The enum value of memory attribute.\r
+\r
+--*/\r
+{\r
+  if ( (Attributes & EFI_MEMORY_UC) == EFI_MEMORY_UC) {\r
+    return EFI_MEMORY_UC;\r
+  }\r
+\r
+  if ( (Attributes & EFI_MEMORY_WC ) == EFI_MEMORY_WC) {\r
+    return EFI_MEMORY_WC;\r
+  }\r
+\r
+  if ( (Attributes & EFI_MEMORY_WT ) == EFI_MEMORY_WT) {\r
+    return EFI_MEMORY_WT;\r
+  }\r
+\r
+  if ( (Attributes & EFI_MEMORY_WB) == EFI_MEMORY_WB) {\r
+    return EFI_MEMORY_WB;\r
+  }\r
+\r
+  if ( (Attributes & EFI_MEMORY_WP) == EFI_MEMORY_WP) {\r
+    return EFI_MEMORY_WP;\r
+  }\r
+\r
+  return INVALID_CPU_ARCH_ATTRIBUTES;\r
+\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreConvertSpace (\r
+  IN UINTN                 Operation,\r
+  IN EFI_GCD_MEMORY_TYPE   GcdMemoryType,\r
+  IN EFI_GCD_IO_TYPE       GcdIoType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Capabilities,\r
+  IN UINT64                Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Do operation on a segment of memory space specified (add, free, remove, change attribute ...).\r
+\r
+Arguments:\r
+\r
+  Operation       - The type of the operation\r
+  \r
+  GcdMemoryType   - Additional information for the operation\r
+  \r
+  GcdIoType       - Additional information for the operation\r
+  \r
+  BaseAddress     - Start address of the segment\r
+  \r
+  Length          - length of the segment\r
+  \r
+  Capabilities    - The alterable attributes of a newly added entry\r
+  \r
+  Attributes      - The attributes needs to be set\r
+  \r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Length is 0 or address (length) not aligned when setting attribute.\r
+  \r
+  EFI_SUCCESS                 - Action successfully done.\r
+  \r
+  EFI_UNSUPPORTED             - Could not find the proper descriptor on this segment or \r
+                                set an upsupported attribute.\r
+  \r
+  EFI_ACCESS_DENIED           - Operate on an space non-exist or is used for an image.\r
+  \r
+  EFI_NOT_FOUND               - Free a non-using space or remove a non-exist space, and so on.\r
+  \r
+  EFI_OUT_OF_RESOURCES        - No buffer could be allocated.\r
+\r
+Returns:\r
+\r
+--*/\r
+{\r
+  EFI_STATUS         Status;\r
+  LIST_ENTRY         *Map;\r
+  LIST_ENTRY         *Link;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+  EFI_GCD_MAP_ENTRY  *TopEntry;\r
+  EFI_GCD_MAP_ENTRY  *BottomEntry;\r
+  LIST_ENTRY         *StartLink;\r
+  LIST_ENTRY         *EndLink;\r
+  \r
+  EFI_CPU_ARCH_PROTOCOL           *CpuArch;\r
+  UINT64                          CpuArchAttributes;\r
+\r
+  if (Length == 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Map = NULL;\r
+  if (Operation & GCD_MEMORY_SPACE_OPERATION) {\r
+    CoreAcquireGcdMemoryLock ();\r
+    Map = &mGcdMemorySpaceMap;\r
+  }\r
+  if (Operation & GCD_IO_SPACE_OPERATION) {\r
+    CoreAcquireGcdIoLock ();\r
+    Map = &mGcdIoSpaceMap;\r
+  }\r
+\r
+  //\r
+  // Search for the list of descriptors that cover the range BaseAddress to BaseAddress+Length\r
+  //\r
+  Status = CoreSearchGcdMapEntry (BaseAddress, Length, &StartLink, &EndLink, Map);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_UNSUPPORTED;\r
+\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Verify that the list of descriptors are unallocated non-existent memory.\r
+  //\r
+  Link = StartLink;\r
+  while (Link != EndLink->ForwardLink) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    switch (Operation) {\r
+    //\r
+    // Add operations\r
+    //\r
+    case GCD_ADD_MEMORY_OPERATION:\r
+      if (Entry->GcdMemoryType != EfiGcdMemoryTypeNonExistent ||\r
+          Entry->ImageHandle   != NULL                           ) {\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto Done;\r
+      }\r
+      break;\r
+    case GCD_ADD_IO_OPERATION:\r
+      if (Entry->GcdIoType   != EfiGcdIoTypeNonExistent ||\r
+          Entry->ImageHandle != NULL                       ) {\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto Done;\r
+      }\r
+      break;\r
+    //\r
+    // Free operations\r
+    //\r
+    case GCD_FREE_MEMORY_OPERATION:\r
+    case GCD_FREE_IO_OPERATION:\r
+      if (Entry->ImageHandle == NULL) {\r
+        Status = EFI_NOT_FOUND;\r
+        goto Done;\r
+      }\r
+      break;\r
+    //\r
+    // Remove operations\r
+    //\r
+    case GCD_REMOVE_MEMORY_OPERATION:\r
+      if (Entry->GcdMemoryType == EfiGcdMemoryTypeNonExistent) {\r
+        Status = EFI_NOT_FOUND;\r
+        goto Done;\r
+      }\r
+      if (Entry->ImageHandle != NULL) {\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto Done;\r
+      }\r
+      break;\r
+    case GCD_REMOVE_IO_OPERATION:\r
+      if (Entry->GcdIoType == EfiGcdIoTypeNonExistent) {\r
+        Status = EFI_NOT_FOUND;\r
+        goto Done;\r
+      }\r
+      if (Entry->ImageHandle != NULL) {\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto Done;\r
+      }\r
+      break;\r
+    //\r
+    // Set attribute operations\r
+    //\r
+    case GCD_SET_ATTRIBUTES_MEMORY_OPERATION:\r
+      if (Attributes & EFI_MEMORY_RUNTIME) {\r
+        if ((BaseAddress & EFI_PAGE_MASK) != 0 || (Length & EFI_PAGE_MASK) != 0) {\r
+          Status = EFI_INVALID_PARAMETER;\r
+\r
+          goto Done;\r
+        }\r
+      }\r
+      if ((Entry->Capabilities & Attributes) != Attributes) {\r
+        Status = EFI_UNSUPPORTED;\r
+        goto Done;\r
+      }\r
+      break;\r
+    }\r
+    Link = Link->ForwardLink;\r
+  }\r
+\r
+  //\r
+  // Allocate work space to perform this operation\r
+  //\r
+  Status = CoreAllocateGcdMapEntry (&TopEntry, &BottomEntry);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  //\r
+  //\r
+  if (Operation == GCD_SET_ATTRIBUTES_MEMORY_OPERATION) {\r
+    //\r
+    // Call CPU Arch Protocol to attempt to set attributes on the range\r
+    //\r
+    CpuArchAttributes = ConverToCpuArchAttributes (Attributes);\r
+    if ( CpuArchAttributes != INVALID_CPU_ARCH_ATTRIBUTES ) {\r
+      Status = CoreLocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&CpuArch);\r
+      if (EFI_ERROR (Status)) {\r
+        Status = EFI_ACCESS_DENIED;\r
+        goto Done;\r
+      }\r
+\r
+      Status = CpuArch->SetMemoryAttributes (\r
+                          CpuArch,\r
+                          BaseAddress,\r
+                          Length,\r
+                          CpuArchAttributes\r
+                          );\r
+      if (EFI_ERROR (Status)) {\r
+        goto Done;\r
+      }\r
+    }\r
+\r
+  }\r
+\r
+  //\r
+  // Convert/Insert the list of descriptors from StartLink to EndLink\r
+  //\r
+  Link = StartLink;\r
+  while (Link != EndLink->ForwardLink) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    CoreInsertGcdMapEntry (Link, Entry, BaseAddress, Length, TopEntry, BottomEntry);\r
+    switch (Operation) {\r
+    //\r
+    // Add operations\r
+    //\r
+    case GCD_ADD_MEMORY_OPERATION:\r
+      Entry->GcdMemoryType = GcdMemoryType;\r
+      if (GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) {\r
+        Entry->Capabilities  = Capabilities | EFI_MEMORY_RUNTIME | EFI_MEMORY_PORT_IO;\r
+      } else {\r
+        Entry->Capabilities  = Capabilities | EFI_MEMORY_RUNTIME;\r
+      }\r
+      break;\r
+    case GCD_ADD_IO_OPERATION:\r
+      Entry->GcdIoType = GcdIoType;\r
+      break;\r
+    //\r
+    // Free operations\r
+    //\r
+    case GCD_FREE_MEMORY_OPERATION:\r
+    case GCD_FREE_IO_OPERATION:\r
+      Entry->ImageHandle  = NULL;\r
+      Entry->DeviceHandle = NULL;\r
+      break;\r
+    //\r
+    // Remove operations\r
+    //\r
+    case GCD_REMOVE_MEMORY_OPERATION:\r
+      Entry->GcdMemoryType = EfiGcdMemoryTypeNonExistent;\r
+      Entry->Capabilities  = 0;\r
+      break;\r
+    case GCD_REMOVE_IO_OPERATION:\r
+      Entry->GcdIoType = EfiGcdIoTypeNonExistent;\r
+      break;\r
+    //\r
+    // Set attribute operations\r
+    //\r
+    case GCD_SET_ATTRIBUTES_MEMORY_OPERATION:\r
+      Entry->Attributes = Attributes;\r
+      break;\r
+    }\r
+    Link = Link->ForwardLink;\r
+  }\r
+\r
+  //\r
+  // Cleanup\r
+  //\r
+  Status = CoreCleanupGcdMapEntry (TopEntry, BottomEntry, StartLink, EndLink, Map);\r
+\r
+Done:\r
+  if (Operation & GCD_MEMORY_SPACE_OPERATION) {\r
+    CoreReleaseGcdMemoryLock ();\r
+  }\r
+  if (Operation & GCD_IO_SPACE_OPERATION) {\r
+    CoreReleaseGcdIoLock ();\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreAllocateSpaceCheckEntry (\r
+  IN UINTN                Operation,\r
+  IN EFI_GCD_MAP_ENTRY    *Entry,\r
+  IN EFI_GCD_MEMORY_TYPE  GcdMemoryType,\r
+  IN EFI_GCD_IO_TYPE      GcdIoType\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check whether an entry could be used to allocate space.\r
+\r
+Arguments:\r
+\r
+  Operation       - Allocate memory or IO\r
+  \r
+  Entry           - The entry to be tested\r
+  \r
+  GcdMemoryType   - The desired memory type\r
+  \r
+  GcdIoType       - The desired IO type\r
+  \r
+Returns:\r
+\r
+  EFI_NOT_FOUND   - The memory type does not match or there's an image handle on the entry.\r
+  \r
+  EFI_UNSUPPORTED - The operation unsupported.\r
+  \r
+  EFI_SUCCESS     - It's ok for this entry to be used to allocate space.\r
+\r
+--*/\r
+{\r
+  if (Entry->ImageHandle != NULL) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  switch (Operation) {\r
+  case GCD_ALLOCATE_MEMORY_OPERATION:\r
+    if (Entry->GcdMemoryType != GcdMemoryType) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+    break;\r
+  case GCD_ALLOCATE_IO_OPERATION:\r
+    if (Entry->GcdIoType != GcdIoType) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+    break;\r
+  default:\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreAllocateSpace (\r
+  IN     UINTN                  Operation,\r
+  IN     EFI_GCD_ALLOCATE_TYPE  GcdAllocateType,\r
+  IN     EFI_GCD_MEMORY_TYPE    GcdMemoryType,\r
+  IN     EFI_GCD_IO_TYPE        GcdIoType,\r
+  IN     UINTN                  Alignment,\r
+  IN     UINT64                 Length,\r
+  IN OUT EFI_PHYSICAL_ADDRESS   *BaseAddress,\r
+  IN     EFI_HANDLE             ImageHandle,\r
+  IN     EFI_HANDLE             DeviceHandle OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate space on specified address and length.\r
+\r
+Arguments:\r
+\r
+  Operation         - The type of operation (memory or IO)\r
+  \r
+  GcdAllocateType   - The type of allocate operation\r
+  \r
+  GcdMemoryType     - The desired memory type\r
+  \r
+  GcdIoType         - The desired IO type\r
+  \r
+  Alignment         - Align with 2^Alignment\r
+  \r
+  Length            - Length to allocate\r
+  \r
+  BaseAddress       - Base address to allocate\r
+  \r
+  ImageHandle       - The image handle consume the allocated space.\r
+  \r
+  DeviceHandle      - The device handle consume the allocated space.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter.\r
+  \r
+  EFI_NOT_FOUND               - No descriptor for the desired space exists.\r
+  \r
+  EFI_SUCCESS                 - Space successfully allocated.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS            Status;\r
+  EFI_PHYSICAL_ADDRESS  AlignmentMask;\r
+  EFI_PHYSICAL_ADDRESS  MaxAddress;\r
+  LIST_ENTRY            *Map;\r
+  LIST_ENTRY            *Link;\r
+  LIST_ENTRY            *SubLink;\r
+  EFI_GCD_MAP_ENTRY     *Entry;\r
+  EFI_GCD_MAP_ENTRY     *TopEntry;\r
+  EFI_GCD_MAP_ENTRY     *BottomEntry;\r
+  LIST_ENTRY            *StartLink;\r
+  LIST_ENTRY            *EndLink;\r
+  BOOLEAN               Found;\r
+\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (GcdAllocateType < 0 || GcdAllocateType >= EfiGcdMaxAllocateType) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (GcdMemoryType < 0 || GcdMemoryType >= EfiGcdMemoryTypeMaximum) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (GcdIoType < 0 || GcdIoType >= EfiGcdIoTypeMaximum) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (BaseAddress == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (ImageHandle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (Alignment >= 64) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  if (Length == 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Map = NULL;\r
+  if (Operation & GCD_MEMORY_SPACE_OPERATION) {\r
+    CoreAcquireGcdMemoryLock ();\r
+    Map = &mGcdMemorySpaceMap;\r
+  }\r
+  if (Operation & GCD_IO_SPACE_OPERATION) {\r
+    CoreAcquireGcdIoLock ();\r
+    Map = &mGcdIoSpaceMap;\r
+  }\r
+\r
+  Found     = FALSE;\r
+  StartLink = NULL;\r
+  EndLink   = NULL;\r
+  //\r
+  // Compute alignment bit mask\r
+  //\r
+  AlignmentMask = LShiftU64 (1, Alignment) - 1;\r
+\r
+  if (GcdAllocateType == EfiGcdAllocateAddress) {\r
+    //\r
+    // Verify that the BaseAddress passed in is aligned correctly\r
+    //\r
+    if ((*BaseAddress & AlignmentMask) != 0) {\r
+      Status = EFI_NOT_FOUND;\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Search for the list of descriptors that cover the range BaseAddress to BaseAddress+Length\r
+    //\r
+    Status = CoreSearchGcdMapEntry (*BaseAddress, Length, &StartLink, &EndLink, Map);\r
+    if (EFI_ERROR (Status)) {\r
+      Status = EFI_NOT_FOUND;\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Verify that the list of descriptors are unallocated memory matching GcdMemoryType.\r
+    //\r
+    Link = StartLink;\r
+    while (Link != EndLink->ForwardLink) {\r
+      Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+      Link = Link->ForwardLink;\r
+      Status = CoreAllocateSpaceCheckEntry (Operation, Entry, GcdMemoryType, GcdIoType);\r
+      if (EFI_ERROR (Status)) {\r
+        goto Done;\r
+      }\r
+    }\r
+    Found = TRUE;\r
+  } else {\r
+\r
+    Entry = CR (Map->BackLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+\r
+    //\r
+    // Compute the maximum address to use in the search algorithm\r
+    //\r
+    if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchBottomUp ||\r
+        GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown     ) {\r
+      MaxAddress = *BaseAddress;\r
+    } else {\r
+      MaxAddress = Entry->EndAddress;\r
+    }\r
+\r
+    //\r
+    // Verify that the list of descriptors are unallocated memory matching GcdMemoryType.\r
+    //\r
+    if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown ||\r
+        GcdAllocateType == EfiGcdAllocateAnySearchTopDown ) {\r
+      Link = Map->BackLink;\r
+    } else {\r
+      Link = Map->ForwardLink;\r
+    }\r
+    while (Link != Map) {\r
+      Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+\r
+      if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown ||\r
+          GcdAllocateType == EfiGcdAllocateAnySearchTopDown           ) {\r
+        Link = Link->BackLink;\r
+      } else {\r
+        Link = Link->ForwardLink;\r
+      }\r
+\r
+      Status = CoreAllocateSpaceCheckEntry (Operation, Entry, GcdMemoryType, GcdIoType);\r
+      if (EFI_ERROR (Status)) {\r
+        continue;\r
+      }\r
+\r
+      if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown ||\r
+          GcdAllocateType == EfiGcdAllocateAnySearchTopDown           ) {\r
+        if ((Entry->BaseAddress + Length) > MaxAddress) {\r
+          continue;\r
+        }\r
+        if (Length > (Entry->EndAddress + 1)) {\r
+          Status = EFI_NOT_FOUND;\r
+          goto Done;\r
+        }\r
+        if (Entry->EndAddress > MaxAddress) {\r
+          *BaseAddress = MaxAddress;\r
+        } else {\r
+          *BaseAddress = Entry->EndAddress;\r
+        }\r
+        *BaseAddress = (*BaseAddress + 1 - Length) & (~AlignmentMask);\r
+      } else {\r
+        *BaseAddress = (Entry->BaseAddress + AlignmentMask) & (~AlignmentMask);\r
+        if ((*BaseAddress + Length - 1) > MaxAddress) {\r
+          Status = EFI_NOT_FOUND;\r
+          goto Done;\r
+        }\r
+      }\r
+\r
+      //\r
+      // Search for the list of descriptors that cover the range BaseAddress to BaseAddress+Length\r
+      //\r
+      Status = CoreSearchGcdMapEntry (*BaseAddress, Length, &StartLink, &EndLink, Map);\r
+      if (EFI_ERROR (Status)) {\r
+        Status = EFI_NOT_FOUND;\r
+        goto Done;\r
+      }\r
+\r
+      Link = StartLink;\r
+      //\r
+      // Verify that the list of descriptors are unallocated memory matching GcdMemoryType.\r
+      //\r
+      Found = TRUE;\r
+      SubLink = StartLink;\r
+      while (SubLink != EndLink->ForwardLink) {\r
+        Entry = CR (SubLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+        Status = CoreAllocateSpaceCheckEntry (Operation, Entry, GcdMemoryType, GcdIoType);\r
+        if (EFI_ERROR (Status)) {\r
+          Link = SubLink;\r
+          Found = FALSE;\r
+          break;\r
+        }\r
+        SubLink = SubLink->ForwardLink;\r
+      }\r
+      if (Found) {\r
+        break;\r
+      }\r
+    }\r
+  }\r
+  if (!Found) {\r
+    Status = EFI_NOT_FOUND;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Allocate work space to perform this operation\r
+  //\r
+  Status = CoreAllocateGcdMapEntry (&TopEntry, &BottomEntry);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Convert/Insert the list of descriptors from StartLink to EndLink\r
+  //\r
+  Link = StartLink;\r
+  while (Link != EndLink->ForwardLink) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    CoreInsertGcdMapEntry (Link, Entry, *BaseAddress, Length, TopEntry, BottomEntry);\r
+    Entry->ImageHandle  = ImageHandle;\r
+    Entry->DeviceHandle = DeviceHandle;\r
+    Link = Link->ForwardLink;\r
+  }\r
+\r
+  //\r
+  // Cleanup\r
+  //\r
+  Status = CoreCleanupGcdMapEntry (TopEntry, BottomEntry, StartLink, EndLink, Map);\r
+\r
+Done:\r
+  if (Operation & GCD_MEMORY_SPACE_OPERATION) {\r
+    CoreReleaseGcdMemoryLock ();\r
+  }\r
+  if (Operation & GCD_IO_SPACE_OPERATION) {\r
+    CoreReleaseGcdIoLock ();\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreInternalAddMemorySpace (\r
+  IN EFI_GCD_MEMORY_TYPE   GcdMemoryType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Capabilities\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add a segment of memory to GCD map.\r
+\r
+Arguments:\r
+\r
+  GcdMemoryType     - Memory type of the segment.\r
+  \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+  Capabilities      - alterable attributes of the segment.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameters.\r
+  \r
+  EFI_SUCCESS                 - Successfully add a segment of memory space.\r
+\r
+--*/\r
+{\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (GcdMemoryType <= EfiGcdMemoryTypeNonExistent || GcdMemoryType >= EfiGcdMemoryTypeMaximum) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  return CoreConvertSpace (GCD_ADD_MEMORY_OPERATION, GcdMemoryType, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, Capabilities, 0);\r
+}\r
+\r
+//\r
+// GCD Core Services\r
+//\r
+EFI_STATUS\r
+CoreAllocateMemorySpace (\r
+  IN     EFI_GCD_ALLOCATE_TYPE  GcdAllocateType,\r
+  IN     EFI_GCD_MEMORY_TYPE    GcdMemoryType,\r
+  IN     UINTN                  Alignment,\r
+  IN     UINT64                 Length,\r
+  IN OUT EFI_PHYSICAL_ADDRESS   *BaseAddress,\r
+  IN     EFI_HANDLE             ImageHandle,\r
+  IN     EFI_HANDLE             DeviceHandle OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocates nonexistent memory, reserved memory, system memory, or memorymapped\r
+I/O resources from the global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  GcdAllocateType   - The type of allocate operation\r
+  \r
+  GcdMemoryType     - The desired memory type\r
+  \r
+  Alignment         - Align with 2^Alignment\r
+  \r
+  Length            - Length to allocate\r
+  \r
+  BaseAddress       - Base address to allocate\r
+  \r
+  ImageHandle       - The image handle consume the allocated space.\r
+  \r
+  DeviceHandle      - The device handle consume the allocated space.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter.\r
+  \r
+  EFI_NOT_FOUND               - No descriptor contains the desired space.\r
+  \r
+  EFI_SUCCESS                 - Memory space successfully allocated.\r
+\r
+--*/\r
+{\r
+  return CoreAllocateSpace (\r
+           GCD_ALLOCATE_MEMORY_OPERATION, \r
+           GcdAllocateType, \r
+           GcdMemoryType, \r
+           (EFI_GCD_IO_TYPE) 0, \r
+           Alignment, \r
+           Length, \r
+           BaseAddress, \r
+           ImageHandle, \r
+           DeviceHandle\r
+           );\r
+}\r
+\r
+EFI_STATUS\r
+CoreAddMemorySpace (\r
+  IN EFI_GCD_MEMORY_TYPE   GcdMemoryType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Capabilities\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Adds reserved memory, system memory, or memory-mapped I/O resources to the\r
+global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  GcdMemoryType     - Memory type of the memory space.\r
+  \r
+  BaseAddress       - Base address of the memory space.\r
+  \r
+  Length            - Length of the memory space.\r
+  \r
+  Capabilities      - alterable attributes of the memory space.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Merged this memory space into GCD map.  \r
+\r
+--*/\r
+{\r
+  EFI_STATUS            Status;\r
+  EFI_PHYSICAL_ADDRESS  PageBaseAddress;\r
+  UINT64                PageLength;\r
+\r
+  Status = CoreInternalAddMemorySpace (GcdMemoryType, BaseAddress, Length, Capabilities);\r
+\r
+  if (!EFI_ERROR (Status) && GcdMemoryType == EfiGcdMemoryTypeSystemMemory) {\r
+\r
+    PageBaseAddress = PageAlignLength (BaseAddress);\r
+    PageLength      = PageAlignLength (BaseAddress + Length - PageBaseAddress);\r
+\r
+    Status = CoreAllocateMemorySpace (\r
+               EfiGcdAllocateAddress,\r
+               GcdMemoryType,\r
+               EFI_PAGE_SHIFT,         \r
+               PageLength,\r
+               &PageBaseAddress,\r
+               gDxeCoreImageHandle,\r
+               NULL\r
+               );\r
+\r
+    if (!EFI_ERROR (Status)) {\r
+      CoreAddMemoryDescriptor (\r
+        EfiConventionalMemory,\r
+        PageBaseAddress,\r
+        RShiftU64 (PageLength, EFI_PAGE_SHIFT),\r
+        Capabilities\r
+        );\r
+    } else {\r
+      for (; PageLength != 0; PageLength -= EFI_PAGE_SIZE, PageBaseAddress += EFI_PAGE_SIZE) {\r
+        Status = CoreAllocateMemorySpace (\r
+                   EfiGcdAllocateAddress,\r
+                   GcdMemoryType,\r
+                   EFI_PAGE_SHIFT,         \r
+                   EFI_PAGE_SIZE,\r
+                   &PageBaseAddress,\r
+                   gDxeCoreImageHandle,\r
+                   NULL\r
+                   );\r
+\r
+        if (!EFI_ERROR (Status)) {\r
+          CoreAddMemoryDescriptor (\r
+            EfiConventionalMemory,\r
+            PageBaseAddress,\r
+            1,\r
+            Capabilities\r
+            );\r
+        }\r
+      }\r
+    }\r
+  }\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+CoreFreeMemorySpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees nonexistent memory, reserved memory, system memory, or memory-mapped\r
+I/O resources from the global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Base address of the memory space.\r
+  \r
+  Length            - Length of the memory space.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Space successfully freed.\r
+\r
+--*/\r
+{\r
+  return CoreConvertSpace (GCD_FREE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0);\r
+}\r
+\r
+EFI_STATUS\r
+CoreRemoveMemorySpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes reserved memory, system memory, or memory-mapped I/O resources from\r
+the global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Base address of the memory space.\r
+  \r
+  Length            - Length of the memory space.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully remove a segment of memory space.\r
+\r
+--*/\r
+{\r
+  return CoreConvertSpace (GCD_REMOVE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0);\r
+}\r
+\r
+STATIC\r
+VOID\r
+BuildMemoryDescriptor (\r
+  IN OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *Descriptor,\r
+  IN EFI_GCD_MAP_ENTRY                *Entry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Build a memory descriptor according to an entry.\r
+\r
+Arguments:\r
+\r
+  Descriptor          - The descriptor to be built\r
+  \r
+  Entry               - According to this entry\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  Descriptor->BaseAddress   = Entry->BaseAddress;\r
+  Descriptor->Length        = Entry->EndAddress - Entry->BaseAddress + 1;\r
+  Descriptor->Capabilities  = Entry->Capabilities;\r
+  Descriptor->Attributes    = Entry->Attributes;\r
+  Descriptor->GcdMemoryType = Entry->GcdMemoryType;\r
+  Descriptor->ImageHandle   = Entry->ImageHandle;\r
+  Descriptor->DeviceHandle  = Entry->DeviceHandle;\r
+}\r
+\r
+EFI_STATUS\r
+CoreGetMemorySpaceDescriptor (\r
+  IN  EFI_PHYSICAL_ADDRESS             BaseAddress,\r
+  OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *Descriptor\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Retrieves the descriptor for a memory region containing a specified address.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Descriptor        - Specified length\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+  \r
+  EFI_SUCCESS                 - Successfully get memory space descriptor.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS         Status;\r
+  LIST_ENTRY         *StartLink;\r
+  LIST_ENTRY         *EndLink;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (Descriptor == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireGcdMemoryLock ();\r
+\r
+  //\r
+  // Search for the list of descriptors that contain BaseAddress \r
+  //\r
+  Status = CoreSearchGcdMapEntry (BaseAddress, 1, &StartLink, &EndLink, &mGcdMemorySpaceMap);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else {\r
+    //\r
+    // Copy the contents of the found descriptor into Descriptor\r
+    //\r
+    Entry = CR (StartLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    BuildMemoryDescriptor (Descriptor, Entry);\r
+  }\r
+\r
+  CoreReleaseGcdMemoryLock ();\r
+\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+CoreSetMemorySpaceAttributes (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length,\r
+  IN UINT64                Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Modifies the attributes for a memory region in the global coherency domain of the\r
+processor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Length            - Specified length\r
+  \r
+  Attributes        - Specified attributes\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully set attribute of a segment of memory space.\r
+\r
+--*/\r
+{\r
+  return CoreConvertSpace (GCD_SET_ATTRIBUTES_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, Attributes);\r
+}\r
+\r
+EFI_STATUS\r
+CoreGetMemorySpaceMap (\r
+  OUT UINTN                            *NumberOfDescriptors,\r
+  OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR  **MemorySpaceMap\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Returns a map of the memory resources in the global coherency domain of the\r
+processor.\r
+\r
+Arguments:\r
+\r
+  NumberOfDescriptors       - Number of descriptors.\r
+  \r
+  MemorySpaceMap            - Descriptor array\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Successfully get memory space map.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                       Status;\r
+  LIST_ENTRY                       *Link;\r
+  EFI_GCD_MAP_ENTRY                *Entry;\r
+  EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *Descriptor;\r
+\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (NumberOfDescriptors == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (MemorySpaceMap == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireGcdMemoryLock ();\r
+\r
+  //\r
+  // Count the number of descriptors\r
+  //\r
+  *NumberOfDescriptors = CoreCountGcdMapEntry (&mGcdMemorySpaceMap);\r
+\r
+  //\r
+  // Allocate the MemorySpaceMap\r
+  //\r
+  *MemorySpaceMap = CoreAllocateBootServicesPool (*NumberOfDescriptors * sizeof (EFI_GCD_MEMORY_SPACE_DESCRIPTOR));\r
+  if (*MemorySpaceMap == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Fill in the MemorySpaceMap\r
+  //\r
+  Descriptor = *MemorySpaceMap;\r
+  Link = mGcdMemorySpaceMap.ForwardLink;\r
+  while (Link != &mGcdMemorySpaceMap) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    BuildMemoryDescriptor (Descriptor, Entry);\r
+    Descriptor++;\r
+    Link = Link->ForwardLink;\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\r
+  CoreReleaseGcdMemoryLock ();\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+CoreAddIoSpace (\r
+  IN EFI_GCD_IO_TYPE       GcdIoType,\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Adds reserved I/O or I/O resources to the global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  GcdIoType         - IO type of the segment.\r
+  \r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Merged this segment into GCD map.\r
+  EFI_INVALID_PARAMETER    - Parameter not valid\r
+\r
+--*/\r
+{\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (GcdIoType <= EfiGcdIoTypeNonExistent || GcdIoType >= EfiGcdIoTypeMaximum) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  return CoreConvertSpace (GCD_ADD_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, GcdIoType, BaseAddress, Length, 0, 0);\r
+}\r
+\r
+EFI_STATUS\r
+CoreAllocateIoSpace (\r
+  IN     EFI_GCD_ALLOCATE_TYPE  GcdAllocateType,\r
+  IN     EFI_GCD_IO_TYPE        GcdIoType,\r
+  IN     UINTN                  Alignment,\r
+  IN     UINT64                 Length,\r
+  IN OUT EFI_PHYSICAL_ADDRESS   *BaseAddress,\r
+  IN     EFI_HANDLE             ImageHandle,\r
+  IN     EFI_HANDLE             DeviceHandle OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocates nonexistent I/O, reserved I/O, or I/O resources from the global coherency\r
+domain of the processor.\r
+\r
+Arguments:\r
+\r
+  GcdAllocateType   - The type of allocate operation\r
+  \r
+  GcdIoType         - The desired IO type\r
+  \r
+  Alignment         - Align with 2^Alignment\r
+  \r
+  Length            - Length to allocate\r
+  \r
+  BaseAddress       - Base address to allocate\r
+  \r
+  ImageHandle       - The image handle consume the allocated space.\r
+  \r
+  DeviceHandle      - The device handle consume the allocated space.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter.\r
+  \r
+  EFI_NOT_FOUND               - No descriptor contains the desired space.\r
+  \r
+  EFI_SUCCESS                 - IO space successfully allocated.\r
+\r
+--*/\r
+{\r
+  return CoreAllocateSpace (\r
+           GCD_ALLOCATE_IO_OPERATION, \r
+           GcdAllocateType, \r
+           (EFI_GCD_MEMORY_TYPE) 0, \r
+           GcdIoType, \r
+           Alignment, \r
+           Length, \r
+           BaseAddress, \r
+           ImageHandle, \r
+           DeviceHandle\r
+           );\r
+}\r
+\r
+EFI_STATUS\r
+CoreFreeIoSpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees nonexistent I/O, reserved I/O, or I/O resources from the global coherency\r
+domain of the processor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Space successfully freed.\r
+\r
+--*/\r
+{\r
+  return CoreConvertSpace (GCD_FREE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0);\r
+}\r
+\r
+EFI_STATUS\r
+CoreRemoveIoSpace (\r
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,\r
+  IN UINT64                Length\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes reserved I/O or I/O resources from the global coherency domain of the\r
+processor.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Base address of the segment.\r
+  \r
+  Length            - Length of the segment.\r
+  \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Successfully removed a segment of IO space.\r
+\r
+--*/\r
+{\r
+  return CoreConvertSpace (GCD_REMOVE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0);\r
+}\r
+\r
+STATIC\r
+VOID\r
+BuildIoDescriptor (\r
+  IN EFI_GCD_IO_SPACE_DESCRIPTOR  *Descriptor,\r
+  IN EFI_GCD_MAP_ENTRY            *Entry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Build a IO descriptor according to an entry.\r
+\r
+Arguments:\r
+\r
+  Descriptor          - The descriptor to be built\r
+  \r
+  Entry               - According to this entry\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  Descriptor->BaseAddress  = Entry->BaseAddress;\r
+  Descriptor->Length       = Entry->EndAddress - Entry->BaseAddress + 1;\r
+  Descriptor->GcdIoType    = Entry->GcdIoType;\r
+  Descriptor->ImageHandle  = Entry->ImageHandle;\r
+  Descriptor->DeviceHandle = Entry->DeviceHandle;\r
+}\r
+\r
+EFI_STATUS\r
+CoreGetIoSpaceDescriptor (\r
+  IN  EFI_PHYSICAL_ADDRESS         BaseAddress,\r
+  OUT EFI_GCD_IO_SPACE_DESCRIPTOR  *Descriptor\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Retrieves the descriptor for an I/O region containing a specified address.\r
+\r
+Arguments:\r
+\r
+  BaseAddress       - Specified start address\r
+  \r
+  Descriptor        - Specified length\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Descriptor is NULL.\r
+  \r
+  EFI_SUCCESS                 - Successfully get the IO space descriptor.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS         Status;\r
+  LIST_ENTRY         *StartLink;\r
+  LIST_ENTRY         *EndLink;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (Descriptor == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireGcdIoLock ();\r
+\r
+  //\r
+  // Search for the list of descriptors that contain BaseAddress \r
+  //\r
+  Status = CoreSearchGcdMapEntry (BaseAddress, 1, &StartLink, &EndLink, &mGcdIoSpaceMap);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else {\r
+    //\r
+    // Copy the contents of the found descriptor into Descriptor\r
+    //\r
+    Entry = CR (StartLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    BuildIoDescriptor (Descriptor, Entry);\r
+  }\r
+\r
+  CoreReleaseGcdIoLock ();\r
+\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+CoreGetIoSpaceMap (\r
+  OUT UINTN                        *NumberOfDescriptors,\r
+  OUT EFI_GCD_IO_SPACE_DESCRIPTOR  **IoSpaceMap\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Returns a map of the I/O resources in the global coherency domain of the processor.\r
+\r
+Arguments:\r
+\r
+  NumberOfDescriptors       - Number of descriptors.\r
+  \r
+  IoSpaceMap                - Descriptor array\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Successfully get IO space map.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                   Status;\r
+  LIST_ENTRY                   *Link;\r
+  EFI_GCD_MAP_ENTRY            *Entry;\r
+  EFI_GCD_IO_SPACE_DESCRIPTOR  *Descriptor;\r
+\r
+  //\r
+  // Make sure parameters are valid\r
+  //\r
+  if (NumberOfDescriptors == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (IoSpaceMap == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireGcdIoLock ();\r
+\r
+  //\r
+  // Count the number of descriptors\r
+  //\r
+  *NumberOfDescriptors = CoreCountGcdMapEntry (&mGcdIoSpaceMap);\r
+\r
+  //\r
+  // Allocate the IoSpaceMap\r
+  //\r
+  *IoSpaceMap = CoreAllocateBootServicesPool (*NumberOfDescriptors * sizeof (EFI_GCD_IO_SPACE_DESCRIPTOR));\r
+  if (*IoSpaceMap == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Fill in the IoSpaceMap\r
+  //\r
+  Descriptor = *IoSpaceMap;\r
+  Link = mGcdIoSpaceMap.ForwardLink;\r
+  while (Link != &mGcdIoSpaceMap) {\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    BuildIoDescriptor (Descriptor, Entry);\r
+    Descriptor++;\r
+    Link = Link->ForwardLink;\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\r
+  CoreReleaseGcdIoLock ();\r
+  return Status;\r
+}  \r
+\r
+STATIC\r
+UINT64\r
+CoreConvertResourceDescriptorHobAttributesToCapabilities (\r
+  EFI_GCD_MEMORY_TYPE  GcdMemoryType,\r
+  UINT64               Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Converts a Resource Descriptor HOB attributes mask to an EFI Memory Descriptor \r
+  capabilities mask\r
+\r
+Arguments:\r
+\r
+  GcdMemoryType   - Type of resource in the GCD memory map.\r
+  Attributes      - The attribute mask in the Resource Descriptor HOB.\r
+\r
+Returns:\r
+\r
+  The capabilities mask for an EFI Memory Descriptor.\r
+\r
+--*/\r
+{\r
+  UINT64                          Capabilities;\r
+  GCD_ATTRIBUTE_CONVERSION_ENTRY  *Conversion;\r
+  \r
+  //\r
+  // Convert the Resource HOB Attributes to an EFI Memory Capabilities mask\r
+  //\r
+  for (Capabilities = 0, Conversion = mAttributeConversionTable; Conversion->Attribute != 0; Conversion++) {\r
+    if (Conversion->Memory || (GcdMemoryType != EfiGcdMemoryTypeSystemMemory)) {\r
+      if (Attributes & Conversion->Attribute) {\r
+        Capabilities |= Conversion->Capability;\r
+      }\r
+    }\r
+  }\r
+  \r
+  return Capabilities;\r
+}\r
+\r
+EFI_STATUS\r
+CoreInitializeMemoryServices (\r
+  IN  VOID                  **HobStart,\r
+  OUT EFI_PHYSICAL_ADDRESS  *MemoryBaseAddress,\r
+  OUT UINT64                *MemoryLength\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  External function. Initializes the GCD and memory services based on the memory \r
+  descriptor HOBs.  This function is responsible for priming the GCD map and the\r
+  memory map, so memory allocations and resource allocations can be made.  The first\r
+  part of this function can not depend on any memory services until at least one\r
+  memory descriptor is provided to the memory services.  Then the memory services\r
+  can be used to intialize the GCD map.\r
+\r
+Arguments:\r
+\r
+  HobStart            - The start address of the HOB.\r
+  MemoryBaseAddress   - Start address of memory region found to init DXE core.\r
+  MemoryLength        - Length of memory region found to init DXE core.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   - Memory services successfully initialized.\r
+\r
+--*/\r
+{\r
+  EFI_PEI_HOB_POINTERS               Hob;\r
+  EFI_MEMORY_TYPE_INFORMATION        *EfiMemoryTypeInformation;\r
+  UINTN                              DataSize;\r
+  BOOLEAN                            Found;\r
+  EFI_HOB_HANDOFF_INFO_TABLE         *PhitHob;\r
+  EFI_HOB_RESOURCE_DESCRIPTOR        *ResourceHob;\r
+  EFI_HOB_RESOURCE_DESCRIPTOR        *PhitResourceHob;\r
+  EFI_PHYSICAL_ADDRESS               BaseAddress;\r
+  UINT64                             Length;\r
+  UINT64                             Attributes;\r
+  UINT64                             Capabilities;\r
+  EFI_PHYSICAL_ADDRESS               MaxMemoryBaseAddress;\r
+  UINT64                             MaxMemoryLength;\r
+  UINT64                             MaxMemoryAttributes;\r
+  EFI_PHYSICAL_ADDRESS               MaxAddress;\r
+  EFI_PHYSICAL_ADDRESS               HighAddress;\r
+  EFI_HOB_RESOURCE_DESCRIPTOR        *MaxResourceHob;\r
+  EFI_HOB_GUID_TYPE                  *GuidHob;\r
+\r
+  //\r
+  // Point at the first HOB.  This must be the PHIT HOB.\r
+  //\r
+  Hob.Raw = *HobStart;\r
+  ASSERT (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_HANDOFF);\r
+\r
+  //\r
+  // Initialize the spin locks and maps in the memory services.\r
+  // Also fill in the memory services into the EFI Boot Services Table\r
+  //\r
+  CoreInitializePool ();\r
+\r
+  //\r
+  // Initialize Local Variables\r
+  //\r
+  PhitResourceHob       = NULL;\r
+  MaxResourceHob        = NULL;\r
+  ResourceHob           = NULL;\r
+  BaseAddress           = 0;\r
+  Length                = 0;\r
+  Attributes            = 0;\r
+  MaxMemoryBaseAddress  = 0;\r
+  MaxMemoryLength       = 0;\r
+  MaxMemoryAttributes   = 0;\r
+\r
+  //\r
+  // Cache the PHIT HOB for later use\r
+  //\r
+  PhitHob = Hob.HandoffInformationTable;\r
+\r
+  //\r
+  // See if a Memory Type Information HOB is available\r
+  //\r
+  GuidHob = GetFirstGuidHob (&gEfiMemoryTypeInformationGuid);\r
+  if (GuidHob != NULL) {\r
+    EfiMemoryTypeInformation = GET_GUID_HOB_DATA (GuidHob);\r
+    DataSize                 = GET_GUID_HOB_DATA_SIZE (GuidHob);\r
+    if (EfiMemoryTypeInformation != NULL && DataSize > 0 && DataSize <= (EfiMaxMemoryType + 1) * sizeof (EFI_MEMORY_TYPE_INFORMATION)) {\r
+      CopyMem (&gMemoryTypeInformation, EfiMemoryTypeInformation, DataSize);\r
+    }\r
+  }\r
+\r
+  //\r
+  // Find the Resource Descriptor HOB that contains range FreeMemoryBaseAddress..FreeMemoryLength\r
+  //\r
+  Length = 0;\r
+  Found  = FALSE;\r
+  for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) {\r
+\r
+    if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) {\r
+\r
+      ResourceHob = Hob.ResourceDescriptor;\r
+\r
+      if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY                                       &&\r
+          (ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == TESTED_MEMORY_ATTRIBUTES    ) {\r
+\r
+        if (PhitHob->EfiFreeMemoryBottom >= ResourceHob->PhysicalStart                         && \r
+            PhitHob->EfiFreeMemoryTop    <= (ResourceHob->PhysicalStart + ResourceHob->ResourceLength)    ) {\r
+\r
+          //\r
+          // Cache the resource descriptor HOB for the memory region described by the PHIT HOB\r
+          //\r
+          PhitResourceHob = ResourceHob;\r
+          Found = TRUE;\r
+\r
+          Attributes  = PhitResourceHob->ResourceAttribute;\r
+          BaseAddress = PageAlignAddress (PhitHob->EfiMemoryTop);\r
+          Length      = PageAlignLength  (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - BaseAddress);\r
+          if (Length < MINIMUM_INITIAL_MEMORY_SIZE) {\r
+            BaseAddress = PageAlignAddress (PhitHob->EfiFreeMemoryBottom);\r
+            Length      = PageAlignLength  (PhitHob->EfiFreeMemoryTop - BaseAddress);\r
+            if (Length < MINIMUM_INITIAL_MEMORY_SIZE) {\r
+              BaseAddress = PageAlignAddress (ResourceHob->PhysicalStart);\r
+              Length      = PageAlignLength  ((UINT64)((UINTN)*HobStart - BaseAddress));\r
+            }\r
+          }\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Assert if a resource descriptor HOB for the memory region described by the PHIT was not found\r
+  //\r
+  ASSERT (Found);\r
+\r
+  //\r
+  // Search all the resource descriptor HOBs from the highest possible addresses down for a memory\r
+  // region that is big enough to initialize the DXE core.  Always skip the PHIT Resource HOB.\r
+  // The max address must be within the physically addressible range for the processor.\r
+  //\r
+  MaxMemoryLength = 0;\r
+  MaxAddress      = EFI_MAX_ADDRESS;\r
+  do {\r
+    HighAddress = 0;\r
+    Found       = FALSE;\r
+    //\r
+    // Search for a tested memory region that is below MaxAddress\r
+    //\r
+    for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) {\r
+\r
+      //\r
+      // See if this is a resource descriptor HOB that does not contain the PHIT.\r
+      //\r
+      if (Hob.ResourceDescriptor != PhitResourceHob && GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) {\r
+\r
+        ResourceHob = Hob.ResourceDescriptor;\r
+        //\r
+        // See if this resource descrior HOB describes tested system memory below MaxAddress\r
+        //\r
+        if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY                                       &&\r
+            (ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == TESTED_MEMORY_ATTRIBUTES &&\r
+            ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MaxAddress                            ) {\r
+\r
+          //\r
+          // See if this is the highest tested system memory region below MaxAddress\r
+          //\r
+          if (ResourceHob->PhysicalStart > HighAddress) {\r
+\r
+            MaxResourceHob = ResourceHob;\r
+            HighAddress = MaxResourceHob->PhysicalStart;\r
+            Found = TRUE;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    if (Found) {\r
+      //\r
+      // Compute the size of the tested memory region below MaxAddrees\r
+      //\r
+      MaxMemoryBaseAddress = PageAlignAddress (MaxResourceHob->PhysicalStart);\r
+      MaxMemoryLength      = PageAlignLength  (MaxResourceHob->PhysicalStart + MaxResourceHob->ResourceLength - MaxMemoryBaseAddress);\r
+      MaxMemoryAttributes  = MaxResourceHob->ResourceAttribute;\r
+    }\r
+    MaxAddress = ResourceHob->PhysicalStart;\r
+  } while (Found && MaxMemoryLength < MINIMUM_INITIAL_MEMORY_SIZE);\r
+\r
+  //\r
+  //\r
+  //\r
+  if ((Length < MINIMUM_INITIAL_MEMORY_SIZE)                                                 ||\r
+      (MaxMemoryBaseAddress > BaseAddress && MaxMemoryLength >= MINIMUM_INITIAL_MEMORY_SIZE)    ) {\r
+    BaseAddress = MaxMemoryBaseAddress;\r
+    Length      = MaxMemoryLength;\r
+    Attributes  = MaxMemoryAttributes;\r
+  }\r
+\r
+  //\r
+  // If no memory regions are found that are big enough to initialize the DXE core, then ASSERT().\r
+  //\r
+  ASSERT (Length >= MINIMUM_INITIAL_MEMORY_SIZE);\r
+\r
+  //\r
+  // Convert the Resource HOB Attributes to an EFI Memory Capabilities mask\r
+  //\r
+  Capabilities = CoreConvertResourceDescriptorHobAttributesToCapabilities (EfiGcdMemoryTypeSystemMemory, Attributes);\r
+\r
+  //\r
+  // Declare the very first memory region, so the EFI Memory Services are available.\r
+  //\r
+  CoreAddMemoryDescriptor (\r
+    EfiConventionalMemory,\r
+    BaseAddress,\r
+    RShiftU64 (Length, EFI_PAGE_SHIFT),\r
+    Capabilities\r
+    );\r
+\r
+  *MemoryBaseAddress = BaseAddress;\r
+  *MemoryLength      = Length;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+EFI_STATUS\r
+CoreInitializeGcdServices (\r
+  IN VOID                  **HobStart,\r
+  IN EFI_PHYSICAL_ADDRESS  MemoryBaseAddress,\r
+  IN UINT64                MemoryLength\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  External function. Initializes the GCD and memory services based on the memory \r
+  descriptor HOBs.  This function is responsible for priming the GCD map and the\r
+  memory map, so memory allocations and resource allocations can be made.  The first\r
+  part of this function can not depend on any memory services until at least one\r
+  memory descriptor is provided to the memory services.  Then the memory services\r
+  can be used to intialize the GCD map.\r
+\r
+Arguments:\r
+\r
+  HobStart - The start address of the HOB\r
+\r
+  MemoryBaseAddress   - Start address of memory region found to init DXE core.\r
+  \r
+  MemoryLength        - Length of memory region found to init DXE core.\r
+\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS         - GCD services successfully initialized.\r
+\r
+--*/\r
+{\r
+  EFI_PEI_HOB_POINTERS                   Hob;\r
+  VOID                               *NewHobList;\r
+  EFI_HOB_HANDOFF_INFO_TABLE  *PhitHob;\r
+  UINT8                              SizeOfMemorySpace;\r
+  UINT8                              SizeOfIoSpace;\r
+  EFI_HOB_RESOURCE_DESCRIPTOR        *ResourceHob;\r
+  EFI_PHYSICAL_ADDRESS               BaseAddress;\r
+  UINT64                             Length;\r
+  EFI_STATUS                         Status;\r
+  EFI_GCD_MAP_ENTRY                  *Entry;\r
+  EFI_GCD_MEMORY_TYPE                GcdMemoryType;\r
+  EFI_GCD_IO_TYPE                    GcdIoType;\r
+  EFI_GCD_MEMORY_SPACE_DESCRIPTOR    Descriptor;\r
+  EFI_HOB_MEMORY_ALLOCATION          *MemoryHob;\r
+  EFI_HOB_FIRMWARE_VOLUME            *FirmwareVolumeHob;\r
+  UINTN                              NumberOfDescriptors;\r
+  EFI_GCD_MEMORY_SPACE_DESCRIPTOR    *MemorySpaceMap;\r
+  UINTN                              Index;\r
+  UINT64                             Capabilities;\r
+  EFI_HOB_CPU *                      CpuHob;\r
+  //\r
+  // Cache the PHIT HOB for later use\r
+  //\r
+  PhitHob = (EFI_HOB_HANDOFF_INFO_TABLE *)(*HobStart);\r
+\r
+  //\r
+  // Get the number of address lines in the I/O and Memory space for the CPU\r
+  //\r
+  CpuHob = GetFirstHob (EFI_HOB_TYPE_CPU);\r
+  ASSERT (CpuHob != NULL);\r
+  SizeOfMemorySpace = CpuHob->SizeOfMemorySpace;\r
+  SizeOfIoSpace     = CpuHob->SizeOfIoSpace;\r
\r
+  //\r
+  // Initialize the GCD Memory Space Map\r
+  //\r
+  Entry = CoreAllocateCopyPool (sizeof (EFI_GCD_MAP_ENTRY), &mGcdMemorySpaceMapEntryTemplate);\r
+  ASSERT (Entry != NULL);\r
+\r
+  Entry->EndAddress = LShiftU64 (1, SizeOfMemorySpace) - 1;\r
+\r
+  InsertHeadList (&mGcdMemorySpaceMap, &Entry->Link);\r
+\r
+  //\r
+  // Initialize the GCD I/O Space Map\r
+  //\r
+  Entry = CoreAllocateCopyPool (sizeof (EFI_GCD_MAP_ENTRY), &mGcdIoSpaceMapEntryTemplate);\r
+  ASSERT (Entry != NULL);\r
+\r
+  Entry->EndAddress = LShiftU64 (1, SizeOfIoSpace) - 1;\r
+\r
+  InsertHeadList (&mGcdIoSpaceMap, &Entry->Link);\r
+\r
+  //\r
+  // Walk the HOB list and add all resource descriptors to the GCD \r
+  //\r
+  for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) {\r
+\r
+    GcdMemoryType = EfiGcdMemoryTypeNonExistent;\r
+    GcdIoType     = EfiGcdIoTypeNonExistent;\r
+\r
+    if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) {\r
+\r
+      ResourceHob = Hob.ResourceDescriptor;\r
+\r
+      switch (ResourceHob->ResourceType) {\r
+      case EFI_RESOURCE_SYSTEM_MEMORY:\r
+        if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == TESTED_MEMORY_ATTRIBUTES) {\r
+          GcdMemoryType = EfiGcdMemoryTypeSystemMemory;\r
+        }\r
+        if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == INITIALIZED_MEMORY_ATTRIBUTES) {\r
+          GcdMemoryType = EfiGcdMemoryTypeReserved;\r
+        }\r
+        if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == PRESENT_MEMORY_ATTRIBUTES) {\r
+          GcdMemoryType = EfiGcdMemoryTypeReserved;\r
+        }\r
+        break;\r
+      case EFI_RESOURCE_MEMORY_MAPPED_IO:\r
+      case EFI_RESOURCE_FIRMWARE_DEVICE:\r
+        GcdMemoryType = EfiGcdMemoryTypeMemoryMappedIo;\r
+        break;\r
+      case EFI_RESOURCE_MEMORY_MAPPED_IO_PORT:\r
+      case EFI_RESOURCE_MEMORY_RESERVED:\r
+        GcdMemoryType = EfiGcdMemoryTypeReserved;\r
+        break;\r
+      case EFI_RESOURCE_IO:\r
+        GcdIoType = EfiGcdIoTypeIo;\r
+        break;\r
+      case EFI_RESOURCE_IO_RESERVED:\r
+        GcdIoType = EfiGcdIoTypeReserved;\r
+        break;\r
+      }\r
+\r
+      if (GcdMemoryType != EfiGcdMemoryTypeNonExistent) {\r
+\r
+        //\r
+        // Convert the Resource HOB Attributes to an EFI Memory Capabilities mask\r
+        //\r
+        Capabilities = CoreConvertResourceDescriptorHobAttributesToCapabilities (\r
+                         GcdMemoryType,\r
+                         ResourceHob->ResourceAttribute\r
+                         );\r
+\r
+        Status = CoreInternalAddMemorySpace (\r
+                   GcdMemoryType,\r
+                   ResourceHob->PhysicalStart,\r
+                   ResourceHob->ResourceLength,\r
+                   Capabilities\r
+                   );\r
+      }\r
+\r
+      if (GcdIoType != EfiGcdIoTypeNonExistent) {\r
+        Status = CoreAddIoSpace (\r
+                   GcdIoType,\r
+                   ResourceHob->PhysicalStart,\r
+                   ResourceHob->ResourceLength\r
+                   );\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Allocate first memory region from the GCD by the DXE core\r
+  //\r
+  Status = CoreAllocateMemorySpace (\r
+             EfiGcdAllocateAddress,\r
+             EfiGcdMemoryTypeSystemMemory,\r
+             0,\r
+             MemoryLength,\r
+             &MemoryBaseAddress,\r
+             gDxeCoreImageHandle,\r
+             NULL\r
+             );\r
+\r
+  //\r
+  // Walk the HOB list and allocate all memory space that is consumed by memory allocation HOBs,\r
+  // and Firmware Volume HOBs.  Also update the EFI Memory Map with the memory allocation HOBs.\r
+  //\r
+  for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) {\r
+    if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) {\r
+      MemoryHob = Hob.MemoryAllocation;\r
+      BaseAddress = MemoryHob->AllocDescriptor.MemoryBaseAddress;\r
+      Status = CoreAllocateMemorySpace (\r
+                 EfiGcdAllocateAddress,\r
+                 EfiGcdMemoryTypeSystemMemory, \r
+                 0,\r
+                 MemoryHob->AllocDescriptor.MemoryLength,\r
+                 &BaseAddress,\r
+                 gDxeCoreImageHandle,\r
+                 NULL\r
+                 );\r
+      if (!EFI_ERROR (Status)) {\r
+        Status = CoreGetMemorySpaceDescriptor (MemoryHob->AllocDescriptor.MemoryBaseAddress, &Descriptor);\r
+        if (!EFI_ERROR (Status)) {\r
+          CoreAddMemoryDescriptor (\r
+            MemoryHob->AllocDescriptor.MemoryType,\r
+            MemoryHob->AllocDescriptor.MemoryBaseAddress,\r
+            RShiftU64 (MemoryHob->AllocDescriptor.MemoryLength, EFI_PAGE_SHIFT),\r
+            Descriptor.Capabilities & (~EFI_MEMORY_RUNTIME)\r
+            );\r
+        }\r
+      }\r
+    }\r
+\r
+    if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) {\r
+      FirmwareVolumeHob = Hob.FirmwareVolume;\r
+      BaseAddress = FirmwareVolumeHob->BaseAddress;\r
+      Status = CoreAllocateMemorySpace (\r
+                 EfiGcdAllocateAddress,\r
+                 EfiGcdMemoryTypeMemoryMappedIo, \r
+                 0,\r
+                 FirmwareVolumeHob->Length,\r
+                 &BaseAddress,\r
+                 gDxeCoreImageHandle,\r
+                 NULL\r
+                 );\r
+    }\r
+  }\r
+\r
+  //\r
+  // Relocate HOB List to an allocated pool buffer.\r
+  //\r
+  NewHobList = CoreAllocateCopyPool (\r
+                 (UINTN)PhitHob->EfiFreeMemoryBottom - (UINTN)(*HobStart), \r
+                 *HobStart\r
+                 );\r
+  ASSERT (NewHobList != NULL);\r
+\r
+  *HobStart = NewHobList;\r
+\r
+  //\r
+  // Add and allocate the remaining unallocated system memory to the memory services.\r
+  //\r
+  Status = CoreGetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);\r
+  for (Index = 0; Index < NumberOfDescriptors; Index++) {\r
+    if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeSystemMemory) {\r
+      if (MemorySpaceMap[Index].ImageHandle == NULL) {\r
+        BaseAddress  = PageAlignAddress (MemorySpaceMap[Index].BaseAddress);\r
+        Length       = PageAlignLength  (MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - BaseAddress);\r
+        CoreAddMemoryDescriptor (\r
+          EfiConventionalMemory,\r
+          BaseAddress,\r
+          RShiftU64 (Length, EFI_PAGE_SHIFT),\r
+          MemorySpaceMap[Index].Capabilities & (~EFI_MEMORY_RUNTIME)\r
+          );\r
+        Status = CoreAllocateMemorySpace (\r
+                   EfiGcdAllocateAddress,\r
+                   EfiGcdMemoryTypeSystemMemory,\r
+                   0,\r
+                   Length,\r
+                   &BaseAddress,\r
+                   gDxeCoreImageHandle,\r
+                   NULL\r
+                   );\r
+      }\r
+    }\r
+  }\r
+  CoreFreePool (MemorySpaceMap);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c b/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c
new file mode 100644 (file)
index 0000000..e8a400c
--- /dev/null
@@ -0,0 +1,845 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+    DriverSupport.c\r
+    \r
+Abstract:\r
+\r
+    EFI Driver Support Protocol\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+GetHandleFromDriverBinding (\r
+  IN EFI_DRIVER_BINDING_PROTOCOL           *DriverBindingNeed,\r
+  OUT  EFI_HANDLE                          *Handle \r
+  );\r
+\r
+\r
+//\r
+// Driver Support Function Prototypes\r
+//\r
+STATIC\r
+EFI_STATUS \r
+CoreConnectSingleController (\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  EFI_HANDLE                *DriverImageHandle    OPTIONAL,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL  *RemainingDevicePath  OPTIONAL\r
+  );\r
+\r
+//\r
+// Driver Support Functions\r
+//\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreConnectController (\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  EFI_HANDLE                *DriverImageHandle    OPTIONAL,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL  *RemainingDevicePath  OPTIONAL,\r
+  IN  BOOLEAN                   Recursive\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Connects one or more drivers to a controller.\r
+\r
+Arguments:\r
+\r
+  ControllerHandle            - Handle of the controller to be connected.\r
+\r
+  DriverImageHandle           - DriverImageHandle A pointer to an ordered list of driver image handles.\r
+\r
+  RemainingDevicePath         - RemainingDevicePath A pointer to the device path that specifies a child of the\r
+                                controller specified by ControllerHandle.\r
+    \r
+  Recursive                   - Whether the function would be called recursively or not.\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                           Status;\r
+  EFI_STATUS                           ReturnStatus;\r
+  IHANDLE                              *Handle;\r
+  PROTOCOL_INTERFACE                   *Prot;\r
+  LIST_ENTRY                           *Link;\r
+  LIST_ENTRY                           *ProtLink;\r
+  OPEN_PROTOCOL_DATA                   *OpenData;\r
+  EFI_DEVICE_PATH_PROTOCOL             *AlignedRemainingDevicePath;\r
+  \r
+  //\r
+  // Make sure ControllerHandle is valid\r
+  //\r
+  Status = CoreValidateHandle (ControllerHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  Handle = ControllerHandle;\r
+\r
+  //\r
+  // Connect all drivers to ControllerHandle \r
+  //\r
+  AlignedRemainingDevicePath = NULL;\r
+  if (RemainingDevicePath != NULL) {\r
+    AlignedRemainingDevicePath = CoreDuplicateDevicePath (RemainingDevicePath);\r
+  }\r
+  ReturnStatus = CoreConnectSingleController (\r
+                   ControllerHandle,\r
+                   DriverImageHandle,\r
+                   AlignedRemainingDevicePath\r
+                   );\r
+  if (AlignedRemainingDevicePath != NULL) {\r
+    CoreFreePool (AlignedRemainingDevicePath);\r
+  }\r
+\r
+  //\r
+  // If not recursive, then just return after connecting drivers to ControllerHandle\r
+  //\r
+  if (!Recursive) {\r
+    return ReturnStatus;\r
+  }\r
+\r
+  //\r
+  // If recursive, then connect all drivers to all of ControllerHandle's children\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+  for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+    Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+    for (ProtLink = Prot->OpenList.ForwardLink; \r
+           ProtLink != &Prot->OpenList; \r
+           ProtLink = ProtLink->ForwardLink) {\r
+        OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+        if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) {\r
+          CoreReleaseProtocolLock ();\r
+          Status = CoreConnectController (\r
+                          OpenData->ControllerHandle,\r
+                          NULL,\r
+                          NULL,\r
+                          TRUE\r
+                          ); \r
+          CoreAcquireProtocolLock ();\r
+        }\r
+    }\r
+  }\r
+  CoreReleaseProtocolLock ();\r
+  \r
+  return ReturnStatus;\r
+}\r
+\r
+STATIC\r
+VOID\r
+AddSortedDriverBindingProtocol (\r
+  IN      EFI_HANDLE                   DriverBindingHandle,\r
+  IN OUT  UINTN                        *NumberOfSortedDriverBindingProtocols, \r
+  IN OUT  EFI_DRIVER_BINDING_PROTOCOL  **SortedDriverBindingProtocols,\r
+  IN      UINTN                        DriverBindingHandleCount,\r
+  IN OUT  EFI_HANDLE                   *DriverBindingHandleBuffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add Driver Binding Protocols from Context Driver Image Handles to sorted \r
+   Driver Binding Protocol list.\r
+\r
+Arguments:\r
+\r
+  DriverBindingHandle - Handle of the driver binding protocol.\r
+\r
+  NumberOfSortedDriverBindingProtocols - Number Of sorted driver binding protocols\r
+\r
+  SortedDriverBindingProtocols - The sorted protocol list.                        \r
+    \r
+  DriverBindingHandleCount - Driver Binding Handle Count.\r
+\r
+  DriverBindingHandleBuffer - The buffer of driver binding protocol to be modified.\r
+\r
+Returns:\r
+\r
+  None.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                   Status;\r
+  EFI_DRIVER_BINDING_PROTOCOL  *DriverBinding;\r
+  UINTN                        Index;\r
+\r
+  //\r
+  // Make sure the DriverBindingHandle is valid\r
+  //\r
+  Status = CoreValidateHandle (DriverBindingHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // Retrieve the Driver Binding Protocol from DriverBindingHandle\r
+  //\r
+  Status = CoreHandleProtocol(\r
+             DriverBindingHandle,\r
+             &gEfiDriverBindingProtocolGuid,\r
+             (VOID **)&DriverBinding\r
+             );\r
+  //\r
+  // If DriverBindingHandle does not support the Driver Binding Protocol then return\r
+  //\r
+  if (EFI_ERROR (Status) || DriverBinding == NULL) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // See if DriverBinding is already in the sorted list\r
+  //\r
+  for (Index = 0; Index < *NumberOfSortedDriverBindingProtocols; Index++) {\r
+    if (DriverBinding == SortedDriverBindingProtocols[Index]) {\r
+      return;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Add DriverBinding to the end of the list\r
+  //\r
+  SortedDriverBindingProtocols[*NumberOfSortedDriverBindingProtocols] = DriverBinding;\r
+  *NumberOfSortedDriverBindingProtocols = *NumberOfSortedDriverBindingProtocols + 1;\r
+\r
+  //\r
+  // Mark the cooresponding handle in DriverBindingHandleBuffer as used\r
+  //\r
+  for (Index = 0; Index < DriverBindingHandleCount; Index++) {\r
+    if (DriverBindingHandleBuffer[Index] == DriverBindingHandle) {\r
+      DriverBindingHandleBuffer[Index] = NULL;\r
+    }\r
+  }\r
+}\r
\r
+STATIC\r
+EFI_STATUS \r
+CoreConnectSingleController (\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  EFI_HANDLE                *ContextDriverImageHandles OPTIONAL,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL  *RemainingDevicePath       OPTIONAL     \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Connects a controller to a driver.\r
+\r
+Arguments:\r
+\r
+  ControllerHandle            - Handle of the controller to be connected.\r
+  ContextDriverImageHandles   - DriverImageHandle A pointer to an ordered list of driver image handles.\r
+  RemainingDevicePath         - RemainingDevicePath A pointer to the device path that specifies a child \r
+                                of the controller specified by ControllerHandle.\r
+    \r
+Returns:\r
+\r
+  EFI_SUCCESS           - One or more drivers were connected to ControllerHandle.\r
+  EFI_OUT_OF_RESOURCES  - No enough system resources to complete the request.\r
+  EFI_NOT_FOUND         - No drivers were connected to ControllerHandle.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                                 Status;\r
+  UINTN                                      Index;\r
+  EFI_HANDLE                                 DriverImageHandle;\r
+  EFI_PLATFORM_DRIVER_OVERRIDE_PROTOCOL      *PlatformDriverOverride;\r
+  EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL  *BusSpecificDriverOverride;\r
+  UINTN                                      DriverBindingHandleCount;\r
+  EFI_HANDLE                                 *DriverBindingHandleBuffer;\r
+  EFI_DRIVER_BINDING_PROTOCOL                *DriverBinding;\r
+  UINTN                                      NumberOfSortedDriverBindingProtocols;\r
+  EFI_DRIVER_BINDING_PROTOCOL                **SortedDriverBindingProtocols;\r
+  UINT32                                     HighestVersion;\r
+  UINTN                                      HighestIndex;\r
+  UINTN                                      SortIndex;\r
+  BOOLEAN                                    OneStarted;\r
+  BOOLEAN                                    DriverFound;\r
+  EFI_HANDLE                                 DriverBindingHandle;\r
+\r
+  //\r
+  // DriverBindingHandle is used for performance measurement, initialize it here just in case.\r
+  //\r
+  DriverBindingHandle                   = NULL;\r
+  //\r
+  // Initialize local variables\r
+  //\r
+  DriverBindingHandleCount              = 0;\r
+  DriverBindingHandleBuffer             = NULL;\r
+  NumberOfSortedDriverBindingProtocols  = 0;\r
+  SortedDriverBindingProtocols          = NULL;\r
+\r
+  //\r
+  // Get list of all Driver Binding Protocol Instances\r
+  //\r
+  Status = CoreLocateHandleBuffer (\r
+             ByProtocol,   \r
+             &gEfiDriverBindingProtocolGuid,  \r
+             NULL,\r
+             &DriverBindingHandleCount, \r
+             &DriverBindingHandleBuffer\r
+             );\r
+  if (EFI_ERROR (Status) || (DriverBindingHandleCount == 0)) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // Allocate a duplicate array for the sorted Driver Binding Protocol Instances\r
+  //\r
+  SortedDriverBindingProtocols = CoreAllocateBootServicesPool (sizeof (VOID *) * DriverBindingHandleCount);\r
+  if (SortedDriverBindingProtocols == NULL) {\r
+    CoreFreePool (DriverBindingHandleBuffer);\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Add Driver Binding Protocols from Context Driver Image Handles first\r
+  //\r
+  if (ContextDriverImageHandles != NULL) {\r
+    for (Index = 0; ContextDriverImageHandles[Index] != NULL; Index++) {\r
+      AddSortedDriverBindingProtocol (\r
+        ContextDriverImageHandles[Index],\r
+        &NumberOfSortedDriverBindingProtocols, \r
+        SortedDriverBindingProtocols,\r
+        DriverBindingHandleCount,\r
+        DriverBindingHandleBuffer\r
+        );\r
+    }\r
+  }\r
+\r
+  //\r
+  // Add the Platform Driver Override Protocol drivers for ControllerHandle next\r
+  //\r
+  Status = CoreLocateProtocol (\r
+             &gEfiPlatformDriverOverrideProtocolGuid, \r
+             NULL, \r
+             (VOID **)&PlatformDriverOverride\r
+             );\r
+  if (!EFI_ERROR (Status) && (PlatformDriverOverride != NULL)) {\r
+    DriverImageHandle = NULL;\r
+    do {\r
+      Status = PlatformDriverOverride->GetDriver (\r
+                                         PlatformDriverOverride,\r
+                                         ControllerHandle,\r
+                                         &DriverImageHandle\r
+                                         );\r
+      if (!EFI_ERROR (Status)) {\r
+        AddSortedDriverBindingProtocol (\r
+          DriverImageHandle,\r
+          &NumberOfSortedDriverBindingProtocols, \r
+          SortedDriverBindingProtocols,\r
+          DriverBindingHandleCount,\r
+          DriverBindingHandleBuffer\r
+          );\r
+      }\r
+    } while (!EFI_ERROR (Status));\r
+  }\r
+\r
+  //\r
+  // Get the Bus Specific Driver Override Protocol instance on the Controller Handle\r
+  //\r
+  Status = CoreHandleProtocol(\r
+             ControllerHandle,  \r
+             &gEfiBusSpecificDriverOverrideProtocolGuid, \r
+             (VOID **)&BusSpecificDriverOverride\r
+             );\r
+  if (!EFI_ERROR (Status) && (BusSpecificDriverOverride != NULL)) {\r
+    DriverImageHandle = NULL;\r
+    do {\r
+      Status = BusSpecificDriverOverride->GetDriver (\r
+                                            BusSpecificDriverOverride,\r
+                                            &DriverImageHandle\r
+                                            );\r
+      if (!EFI_ERROR (Status)) {\r
+        AddSortedDriverBindingProtocol (\r
+          DriverImageHandle,\r
+          &NumberOfSortedDriverBindingProtocols, \r
+          SortedDriverBindingProtocols,\r
+          DriverBindingHandleCount,\r
+          DriverBindingHandleBuffer\r
+          );\r
+      }\r
+    } while (!EFI_ERROR (Status));\r
+  }\r
+\r
+  //\r
+  // Then add all the remaining Driver Binding Protocols\r
+  //\r
+  SortIndex = NumberOfSortedDriverBindingProtocols;\r
+  for (Index = 0; Index < DriverBindingHandleCount; Index++) {\r
+    AddSortedDriverBindingProtocol (\r
+      DriverBindingHandleBuffer[Index],\r
+      &NumberOfSortedDriverBindingProtocols, \r
+      SortedDriverBindingProtocols,\r
+      DriverBindingHandleCount,\r
+      DriverBindingHandleBuffer\r
+      );\r
+  }\r
+\r
+  //\r
+  // Free the Driver Binding Handle Buffer\r
+  //\r
+  CoreFreePool (DriverBindingHandleBuffer);\r
+\r
+  //\r
+  // Sort the remaining DriverBinding Protocol based on their Version field from\r
+  // highest to lowest.\r
+  //\r
+  for ( ; SortIndex < NumberOfSortedDriverBindingProtocols; SortIndex++) {\r
+    HighestVersion = SortedDriverBindingProtocols[SortIndex]->Version;\r
+    HighestIndex   = SortIndex;\r
+    for (Index = SortIndex + 1; Index < NumberOfSortedDriverBindingProtocols; Index++) {\r
+      if (SortedDriverBindingProtocols[Index]->Version > HighestVersion) {\r
+        HighestVersion = SortedDriverBindingProtocols[Index]->Version;\r
+        HighestIndex   = Index;\r
+      }\r
+    }\r
+    if (SortIndex != HighestIndex) {\r
+      DriverBinding = SortedDriverBindingProtocols[SortIndex];\r
+      SortedDriverBindingProtocols[SortIndex] = SortedDriverBindingProtocols[HighestIndex];\r
+      SortedDriverBindingProtocols[HighestIndex] = DriverBinding;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Loop until no more drivers can be started on ControllerHandle\r
+  //\r
+  OneStarted = FALSE;\r
+  do {\r
+\r
+    //\r
+    // Loop through the sorted Driver Binding Protocol Instances in order, and see if\r
+    // any of the Driver Binding Protocols support the controller specified by \r
+    // ControllerHandle.\r
+    //\r
+    DriverBinding = NULL;\r
+    DriverFound = FALSE;\r
+    for (Index = 0; (Index < NumberOfSortedDriverBindingProtocols) && !DriverFound; Index++) {\r
+      if (SortedDriverBindingProtocols[Index] != NULL) {\r
+        DriverBinding = SortedDriverBindingProtocols[Index];\r
+        Status = DriverBinding->Supported(\r
+                                  DriverBinding, \r
+                                  ControllerHandle,\r
+                                  RemainingDevicePath\r
+                                  );\r
+        if (!EFI_ERROR (Status)) {\r
+          SortedDriverBindingProtocols[Index] = NULL;\r
+          DriverFound = TRUE;\r
+\r
+          //\r
+          // A driver was found that supports ControllerHandle, so attempt to start the driver\r
+          // on ControllerHandle.\r
+          //\r
+          PERF_CODE_BEGIN ();\r
+          GetHandleFromDriverBinding (DriverBinding, &DriverBindingHandle);\r
+          PERF_CODE_END ();\r
+\r
+          PERF_START (DriverBindingHandle, DRIVERBINDING_START_TOK, NULL, 0);\r
+          Status = DriverBinding->Start (\r
+                                    DriverBinding, \r
+                                    ControllerHandle,\r
+                                    RemainingDevicePath\r
+                                    );\r
+          PERF_END (DriverBindingHandle, DRIVERBINDING_START_TOK, NULL, 0);\r
+\r
+          if (!EFI_ERROR (Status)) {\r
+            //\r
+            // The driver was successfully started on ControllerHandle, so set a flag\r
+            //\r
+            OneStarted = TRUE;\r
+          }\r
+        }\r
+      }\r
+    }\r
+  } while (DriverFound);\r
+\r
+  //\r
+  // Free any buffers that were allocated with AllocatePool()\r
+  //\r
+  CoreFreePool (SortedDriverBindingProtocols);\r
+\r
+  //\r
+  // If at least one driver was started on ControllerHandle, then return EFI_SUCCESS.\r
+  //\r
+  if (OneStarted) {\r
+    return EFI_SUCCESS;\r
+  } \r
+\r
+  //\r
+  // If no drivers started and RemainingDevicePath is an End Device Path Node, then return EFI_SUCCESS\r
+  //\r
+  if (RemainingDevicePath != NULL) {\r
+    if (IsDevicePathEnd (RemainingDevicePath)) {\r
+      return EFI_SUCCESS;\r
+    }\r
+  } \r
+\r
+  //\r
+  // Otherwise, no drivers were started on ControllerHandle, so return EFI_NOT_FOUND\r
+  //\r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreDisconnectController (\r
+  IN  EFI_HANDLE  ControllerHandle,\r
+  IN  EFI_HANDLE  DriverImageHandle  OPTIONAL,\r
+  IN  EFI_HANDLE  ChildHandle        OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Disonnects a controller from a driver\r
+\r
+Arguments:\r
+\r
+  ControllerHandle  - ControllerHandle The handle of the controller from which driver(s) \r
+                        are to be disconnected.\r
+  DriverImageHandle - DriverImageHandle The driver to disconnect from ControllerHandle.\r
+  ChildHandle       - ChildHandle The handle of the child to destroy.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           -  One or more drivers were disconnected from the controller.\r
+  EFI_SUCCESS           -  On entry, no drivers are managing ControllerHandle.\r
+  EFI_SUCCESS           -  DriverImageHandle is not NULL, and on entry DriverImageHandle is not managing ControllerHandle.\r
+  EFI_INVALID_PARAMETER -  ControllerHandle is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER -  DriverImageHandle is not NULL, and it is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER -  ChildHandle is not NULL, and it is not a valid EFI_HANDLE.\r
+  EFI_OUT_OF_RESOURCES  -  There are not enough resources available to disconnect any drivers from ControllerHandle.\r
+  EFI_DEVICE_ERROR      -  The controller could not be disconnected because of a device error.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  IHANDLE                             *Handle;\r
+  EFI_HANDLE                          *DriverImageHandleBuffer;\r
+  EFI_HANDLE                          *ChildBuffer;\r
+  UINTN                               Index;\r
+  UINTN                               HandleIndex;\r
+  UINTN                               DriverImageHandleCount;\r
+  UINTN                               ChildrenToStop;\r
+  UINTN                               ChildBufferCount;\r
+  UINTN                               StopCount;\r
+  BOOLEAN                             Duplicate;\r
+  BOOLEAN                             ChildHandleValid;\r
+  BOOLEAN                             DriverImageHandleValid;\r
+  LIST_ENTRY                          *Link;\r
+  LIST_ENTRY                          *ProtLink;\r
+  OPEN_PROTOCOL_DATA                  *OpenData;\r
+  PROTOCOL_INTERFACE                  *Prot;\r
+  EFI_DRIVER_BINDING_PROTOCOL         *DriverBinding;\r
+\r
+  //\r
+  // Make sure ControllerHandle is valid\r
+  //\r
+  Status = CoreValidateHandle (ControllerHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Make sure ChildHandle is valid if it is not NULL\r
+  //\r
+  if (ChildHandle != NULL) {\r
+    Status = CoreValidateHandle (ChildHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+\r
+  Handle = ControllerHandle;\r
+\r
+  //\r
+  // Get list of drivers that are currently managing ControllerHandle\r
+  //\r
+  DriverImageHandleBuffer = NULL;\r
+  DriverImageHandleCount  = 1;  \r
+  \r
+  if (DriverImageHandle == NULL) {\r
+    //\r
+    // Look at each protocol interface for a match\r
+    //\r
+    DriverImageHandleCount = 0;\r
+\r
+    CoreAcquireProtocolLock ();\r
+    for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+      Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+      for (ProtLink = Prot->OpenList.ForwardLink; \r
+           ProtLink != &Prot->OpenList; \r
+           ProtLink = ProtLink->ForwardLink) {\r
+        OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+        if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {\r
+          DriverImageHandleCount++;\r
+        }\r
+      }\r
+    }\r
+    CoreReleaseProtocolLock ();\r
+    \r
+    //\r
+    // If there are no drivers managing this controller, then return EFI_SUCCESS\r
+    //\r
+    if (DriverImageHandleCount == 0) {\r
+      Status = EFI_SUCCESS;\r
+      goto Done;\r
+    }\r
+\r
+    DriverImageHandleBuffer = CoreAllocateBootServicesPool (sizeof (EFI_HANDLE) * DriverImageHandleCount);\r
+    if (DriverImageHandleBuffer == NULL) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto Done;\r
+    }\r
+\r
+    DriverImageHandleCount = 0;\r
+\r
+    CoreAcquireProtocolLock ();\r
+    for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+      Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+      for (ProtLink = Prot->OpenList.ForwardLink; \r
+           ProtLink != &Prot->OpenList; \r
+           ProtLink = ProtLink->ForwardLink) {\r
+        OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+        if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {\r
+          Duplicate = FALSE;\r
+          for (Index = 0; Index< DriverImageHandleCount; Index++) {\r
+            if (DriverImageHandleBuffer[Index] == OpenData->AgentHandle) {\r
+              Duplicate = TRUE;\r
+              break;\r
+            }\r
+          }\r
+          if (!Duplicate) {\r
+            DriverImageHandleBuffer[DriverImageHandleCount] = OpenData->AgentHandle;\r
+            DriverImageHandleCount++;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    CoreReleaseProtocolLock ();\r
+  }\r
+\r
+  StopCount = 0;\r
+  for (HandleIndex = 0; HandleIndex < DriverImageHandleCount; HandleIndex++) {\r
+\r
+    if (DriverImageHandleBuffer != NULL) {\r
+      DriverImageHandle = DriverImageHandleBuffer[HandleIndex];\r
+    }\r
+\r
+    //\r
+    // Get the Driver Binding Protocol of the driver that is managing this controller\r
+    //\r
+    Status = CoreHandleProtocol (\r
+               DriverImageHandle,  \r
+               &gEfiDriverBindingProtocolGuid,   \r
+               (VOID **)&DriverBinding\r
+               );\r
+    if (EFI_ERROR (Status)) {\r
+      Status = EFI_INVALID_PARAMETER;\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Look at each protocol interface for a match\r
+    //\r
+    DriverImageHandleValid = FALSE;\r
+    ChildBufferCount = 0;\r
+\r
+    CoreAcquireProtocolLock ();\r
+    for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+      Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+      for (ProtLink = Prot->OpenList.ForwardLink; \r
+           ProtLink != &Prot->OpenList; \r
+           ProtLink = ProtLink->ForwardLink) {\r
+        OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+        if (OpenData->AgentHandle == DriverImageHandle) {\r
+          if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) {\r
+            ChildBufferCount++;\r
+          } \r
+          if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {\r
+            DriverImageHandleValid = TRUE;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    CoreReleaseProtocolLock ();\r
+\r
+    if (DriverImageHandleValid) {\r
+      ChildHandleValid = FALSE;\r
+      ChildBuffer = NULL;\r
+      if (ChildBufferCount != 0) {\r
+        ChildBuffer = CoreAllocateBootServicesPool (sizeof (EFI_HANDLE) * ChildBufferCount);\r
+        if (ChildBuffer == NULL) {\r
+          Status = EFI_OUT_OF_RESOURCES;\r
+          goto Done;\r
+        }\r
+\r
+        ChildBufferCount = 0;\r
+\r
+        CoreAcquireProtocolLock ();\r
+        for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+          Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+          for (ProtLink = Prot->OpenList.ForwardLink; \r
+               ProtLink != &Prot->OpenList; \r
+               ProtLink = ProtLink->ForwardLink) {\r
+            OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+            if ((OpenData->AgentHandle == DriverImageHandle) &&\r
+                ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0)) {\r
+              Duplicate = FALSE;\r
+              for (Index = 0; Index < ChildBufferCount; Index++) {\r
+                if (ChildBuffer[Index] == OpenData->ControllerHandle) {\r
+                  Duplicate = TRUE;\r
+                  break;\r
+                }\r
+              }\r
+              if (!Duplicate) {\r
+                ChildBuffer[ChildBufferCount] = OpenData->ControllerHandle;\r
+                if (ChildHandle == ChildBuffer[ChildBufferCount]) {\r
+                  ChildHandleValid = TRUE;\r
+                }\r
+                ChildBufferCount++;\r
+              }\r
+            }\r
+          }\r
+        }\r
+        CoreReleaseProtocolLock ();\r
+      }\r
+\r
+      if (ChildHandle == NULL || ChildHandleValid) {\r
+        ChildrenToStop = 0;\r
+        Status = EFI_SUCCESS;\r
+        if (ChildBufferCount > 0) {\r
+          if (ChildHandle != NULL) {\r
+            ChildrenToStop = 1;\r
+            Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, &ChildHandle);\r
+          } else {\r
+            ChildrenToStop = ChildBufferCount;\r
+            Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, ChildBuffer);\r
+          }\r
+        }\r
+        if (!EFI_ERROR (Status) && ((ChildHandle == NULL) || (ChildBufferCount == ChildrenToStop))) {\r
+          Status = DriverBinding->Stop (DriverBinding, ControllerHandle, 0, NULL);\r
+        }\r
+        if (!EFI_ERROR (Status)) {\r
+          StopCount++;\r
+        }\r
+      }\r
+\r
+      if (ChildBuffer != NULL) {\r
+        CoreFreePool (ChildBuffer);\r
+      }\r
+    }\r
+  }\r
+\r
+  if (StopCount > 0) {\r
+    Status = EFI_SUCCESS;\r
+  } else {\r
+    Status = EFI_NOT_FOUND;\r
+  }\r
+  \r
+Done:  \r
+\r
+  if (DriverImageHandleBuffer != NULL) {\r
+    CoreFreePool (DriverImageHandleBuffer);\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+GetHandleFromDriverBinding (\r
+  IN   EFI_DRIVER_BINDING_PROTOCOL           *DriverBindingNeed,\r
+  OUT  EFI_HANDLE                            *Handle \r
+ )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locate the driver binding handle which a specified driver binding protocol installed on.\r
+\r
+Arguments:\r
+\r
+  DriverBindingNeed  - The specified driver binding protocol.\r
+  \r
+  Handle             - The driver binding handle which the protocol installed on.\r
+  \r
+\r
+Returns:\r
+\r
+  EFI_NOT_FOUND         - Could not find the handle.\r
+  \r
+  EFI_SUCCESS           - Successfully find the associated driver binding handle.\r
+  \r
+--*/ \r
+ {\r
+  EFI_STATUS                          Status ;\r
+  EFI_DRIVER_BINDING_PROTOCOL         *DriverBinding;\r
+  UINTN                               DriverBindingHandleCount;\r
+  EFI_HANDLE                          *DriverBindingHandleBuffer;\r
+  UINTN                               Index;\r
+  \r
+  DriverBindingHandleCount = 0;\r
+  DriverBindingHandleBuffer = NULL;\r
+  *Handle = NULL_HANDLE;\r
+  Status = CoreLocateHandleBuffer (\r
+              ByProtocol,   \r
+              &gEfiDriverBindingProtocolGuid,  \r
+              NULL,\r
+              &DriverBindingHandleCount, \r
+              &DriverBindingHandleBuffer\r
+              );\r
+  if (EFI_ERROR (Status) || DriverBindingHandleCount == 0) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  \r
+  for (Index = 0 ; Index < DriverBindingHandleCount; Index++ ) {\r
+    Status = CoreOpenProtocol(\r
+                      DriverBindingHandleBuffer[Index],\r
+                      &gEfiDriverBindingProtocolGuid,\r
+                      (VOID **)&DriverBinding,\r
+                      gDxeCoreImageHandle,\r
+                      NULL,\r
+                      EFI_OPEN_PROTOCOL_GET_PROTOCOL\r
+                      );\r
+                      \r
+   if (!EFI_ERROR (Status) && DriverBinding != NULL) {\r
+    \r
+    if ( DriverBinding == DriverBindingNeed ) {\r
+      *Handle = DriverBindingHandleBuffer[Index];\r
+      CoreFreePool (DriverBindingHandleBuffer);         \r
+      return EFI_SUCCESS ;\r
+    }\r
+   }\r
+ }\r
\r
+ CoreFreePool (DriverBindingHandleBuffer);\r
+ return EFI_NOT_FOUND ;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Hand/Notify.c b/MdeModulePkg/Core/Dxe/Hand/Notify.c
new file mode 100644 (file)
index 0000000..f48fee7
--- /dev/null
@@ -0,0 +1,333 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  notify.c\r
+\r
+Abstract:\r
+\r
+  EFI notify infrastructure\r
+\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+VOID\r
+CoreNotifyProtocolEntry (\r
+  IN PROTOCOL_ENTRY   *ProtEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Signal event for every protocol in protocol entry.\r
+\r
+Arguments:\r
+\r
+  ProtEntry     - Protocol entry\r
+\r
+Returns:\r
+\r
+--*/\r
+{\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  LIST_ENTRY          *Link;\r
+\r
+  ASSERT_LOCKED (&gProtocolDatabaseLock);\r
+\r
+  for (Link=ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) {\r
+    ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);\r
+    CoreSignalEvent (ProtNotify->Event);\r
+  }\r
+}\r
+\r
+\r
+PROTOCOL_INTERFACE *\r
+CoreRemoveInterfaceFromProtocol (\r
+  IN IHANDLE        *Handle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes Protocol from the protocol list (but not the handle list).\r
+\r
+Arguments:\r
+\r
+  Handle -  The handle to remove protocol on.\r
+\r
+  Protocol  -  GUID of the protocol to be moved\r
+\r
+  Interface - The interface of the protocol\r
+\r
+Returns:\r
+\r
+  Protocol Entry\r
+\r
+--*/\r
+{\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  LIST_ENTRY          *Link;\r
+\r
+  ASSERT_LOCKED (&gProtocolDatabaseLock);\r
+\r
+  Prot = CoreFindProtocolInterface (Handle, Protocol, Interface);\r
+  if (Prot != NULL) {\r
+\r
+    ProtEntry = Prot->Protocol;\r
+\r
+    //\r
+    // If there's a protocol notify location pointing to this entry, back it up one\r
+    //\r
+\r
+    for(Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) {\r
+      ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);\r
+\r
+      if (ProtNotify->Position == &Prot->ByProtocol) {\r
+        ProtNotify->Position = Prot->ByProtocol.BackLink;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Remove the protocol interface entry\r
+    //\r
+\r
+    RemoveEntryList (&Prot->ByProtocol);\r
+  }\r
+\r
+  return Prot;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreRegisterProtocolNotify (\r
+  IN EFI_GUID       *Protocol,\r
+  IN EFI_EVENT      Event,\r
+  OUT  VOID           **Registration\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add a new protocol notification record for the request protocol.\r
+\r
+Arguments:\r
+\r
+  Protocol      - The requested protocol to add the notify registration\r
+\r
+  Event         - The event to signal \r
+\r
+  Registration  - Returns the registration record\r
+\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+\r
+  EFI_SUCCESS                 - Successfully returned the registration record that has been added\r
+  \r
+--*/\r
+{\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  EFI_STATUS        Status;\r
+  \r
+  if ((Protocol == NULL) || (Event == NULL) || (Registration == NULL))  {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireProtocolLock ();\r
+\r
+  ProtNotify = NULL;\r
+  \r
+  //\r
+  // Get the protocol entry to add the notification too\r
+  //\r
+\r
+  ProtEntry = CoreFindProtocolEntry (Protocol, TRUE);\r
+  if (ProtEntry != NULL) {\r
+\r
+    //\r
+    // Allocate a new notification record\r
+    //\r
+\r
+    ProtNotify = CoreAllocateBootServicesPool (sizeof(PROTOCOL_NOTIFY));\r
+\r
+    if (ProtNotify != NULL) {\r
+      \r
+      ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE;\r
+      ProtNotify->Protocol = ProtEntry;\r
+      ProtNotify->Event = Event;\r
+      //\r
+      // start at the begining\r
+      //\r
+      ProtNotify->Position = &ProtEntry->Protocols; \r
+\r
+      InsertTailList (&ProtEntry->Notify, &ProtNotify->Link);\r
+    }\r
+  }\r
+\r
+  CoreReleaseProtocolLock ();\r
+\r
+  //\r
+  // Done.  If we have a protocol notify entry, then return it.\r
+  // Otherwise, we must have run out of resources trying to add one\r
+  //\r
+\r
+  Status = EFI_OUT_OF_RESOURCES;\r
+  if (ProtNotify != NULL) {\r
+    *Registration = ProtNotify;\r
+    Status = EFI_SUCCESS;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreReinstallProtocolInterface (\r
+  IN EFI_HANDLE     UserHandle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *OldInterface,\r
+  IN VOID           *NewInterface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Reinstall a protocol interface on a device handle.  The OldInterface for Protocol is replaced by the NewInterface.\r
+\r
+Arguments:\r
+\r
+  UserHandle    - Handle on which the interface is to be reinstalled\r
+  Protocol      - The numeric ID of the interface\r
+  OldInterface  - A pointer to the old interface\r
+  NewInterface  - A pointer to the new interface \r
+\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+  On EFI_SUCCESS            The protocol interface was installed\r
+  On EFI_NOT_FOUND          The OldInterface on the handle was not found\r
+  On EFI_INVALID_PARAMETER  One of the parameters has an invalid value\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS                Status;\r
+  IHANDLE                   *Handle;\r
+  PROTOCOL_INTERFACE        *Prot;\r
+  PROTOCOL_ENTRY            *ProtEntry;\r
+\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  if (Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Handle = (IHANDLE *) UserHandle;\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Check that Protocol exists on UserHandle, and Interface matches the interface in the database\r
+  //\r
+  Prot = CoreFindProtocolInterface (UserHandle, Protocol, OldInterface);\r
+  if (Prot == NULL) {\r
+    CoreReleaseProtocolLock ();\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // Attempt to disconnect all drivers that are using the protocol interface that is about to be reinstalled\r
+  //\r
+  Status = CoreDisconnectControllersUsingProtocolInterface (\r
+             UserHandle,\r
+             Prot\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // One or more drivers refused to release, so return the error\r
+    //\r
+    CoreReleaseProtocolLock ();\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Remove the protocol interface from the protocol\r
+  //\r
+  Prot = CoreRemoveInterfaceFromProtocol (Handle, Protocol, OldInterface);\r
+\r
+  if (Prot == NULL) {\r
+    CoreReleaseProtocolLock ();\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  ProtEntry = Prot->Protocol;\r
+\r
+  //\r
+  // Update the interface on the protocol\r
+  //\r
+  Prot->Interface = NewInterface;\r
+\r
+  //\r
+  // Add this protocol interface to the tail of the\r
+  // protocol entry\r
+  //\r
+  InsertTailList (&ProtEntry->Protocols, &Prot->ByProtocol);\r
+\r
+  //\r
+  // Update the Key to show that the handle has been created/modified\r
+  //\r
+  gHandleDatabaseKey++;\r
+  Handle->Key = gHandleDatabaseKey;\r
+\r
+  //\r
+  // Release the lock and connect all drivers to UserHandle\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  Status = CoreConnectController (\r
+                  UserHandle, \r
+                  NULL, \r
+                  NULL, \r
+                  TRUE\r
+                  );\r
+  CoreAcquireProtocolLock ();\r
+  \r
+  //\r
+  // Notify the notification list for this protocol\r
+  //\r
+  CoreNotifyProtocolEntry (ProtEntry);\r
+\r
+  CoreReleaseProtocolLock ();\r
+  \r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Hand/handle.c b/MdeModulePkg/Core/Dxe/Hand/handle.c
new file mode 100644 (file)
index 0000000..42d96ff
--- /dev/null
@@ -0,0 +1,1700 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  handle.c\r
+\r
+Abstract:\r
+\r
+  EFI handle & protocol handling\r
+\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+//\r
+// mProtocolDatabase     - A list of all protocols in the system.  (simple list for now)\r
+// gHandleList           - A list of all the handles in the system\r
+// gProtocolDatabaseLock - Lock to protect the mProtocolDatabase\r
+// gHandleDatabaseKey    -  The Key to show that the handle has been created/modified\r
+//\r
+static LIST_ENTRY      mProtocolDatabase     = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase);\r
+LIST_ENTRY             gHandleList           = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList);\r
+EFI_LOCK               gProtocolDatabaseLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
+UINT64                 gHandleDatabaseKey    = 0;\r
+\r
+\r
+VOID\r
+CoreAcquireProtocolLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Acquire lock on gProtocolDatabaseLock.\r
+  \r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreAcquireLock (&gProtocolDatabaseLock);\r
+}\r
+\r
+\r
+VOID\r
+CoreReleaseProtocolLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Release lock on gProtocolDatabaseLock.\r
+  \r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&gProtocolDatabaseLock);\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreValidateHandle (\r
+  IN  EFI_HANDLE                UserHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check whether a handle is a valid EFI_HANDLE\r
+  \r
+Arguments:\r
+\r
+  UserHandle    - The handle to check\r
+  \r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER   - The handle is NULL or not a valid EFI_HANDLE.\r
+\r
+  EFI_SUCCESS             - The handle is valid EFI_HANDLE.\r
+\r
+--*/\r
+{\r
+  IHANDLE             *Handle;\r
+\r
+  Handle = (IHANDLE *)UserHandle;\r
+  if (Handle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  if (Handle->Signature != EFI_HANDLE_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+PROTOCOL_ENTRY  *\r
+CoreFindProtocolEntry (\r
+  IN EFI_GUID   *Protocol,\r
+  IN BOOLEAN    Create\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Finds the protocol entry for the requested protocol.\r
+  \r
+  The gProtocolDatabaseLock must be owned\r
+\r
+Arguments:\r
+  \r
+  Protocol  - The ID of the protocol \r
+\r
+  Create    - Create a new entry if not found\r
+\r
+Returns:\r
+\r
+  Protocol entry\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY          *Link;\r
+  PROTOCOL_ENTRY      *Item;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+\r
+  ASSERT_LOCKED(&gProtocolDatabaseLock);\r
+\r
+  //\r
+  // Search the database for the matching GUID\r
+  //\r
+\r
+  ProtEntry = NULL;\r
+  for (Link = mProtocolDatabase.ForwardLink; \r
+       Link != &mProtocolDatabase; \r
+       Link = Link->ForwardLink) {\r
+\r
+    Item = CR(Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE);\r
+    if (CompareGuid (&Item->ProtocolID, Protocol)) {\r
+\r
+      //\r
+      // This is the protocol entry\r
+      //\r
+\r
+      ProtEntry = Item;\r
+      break;\r
+    }\r
+  }\r
+\r
+  //\r
+  // If the protocol entry was not found and Create is TRUE, then \r
+  // allocate a new entry\r
+  //     \r
+  if ((ProtEntry == NULL) && Create) {\r
+    ProtEntry = CoreAllocateBootServicesPool (sizeof(PROTOCOL_ENTRY));\r
+    \r
+    if (ProtEntry != NULL) {\r
+      //\r
+      // Initialize new protocol entry structure\r
+      //\r
+      ProtEntry->Signature = PROTOCOL_ENTRY_SIGNATURE;\r
+      CopyMem ((VOID *)&ProtEntry->ProtocolID, Protocol, sizeof (EFI_GUID));\r
+      InitializeListHead (&ProtEntry->Protocols);\r
+      InitializeListHead (&ProtEntry->Notify);\r
+\r
+      //\r
+      // Add it to protocol database\r
+      //\r
+      InsertTailList (&mProtocolDatabase, &ProtEntry->AllEntries);\r
+    }\r
+  }\r
+\r
+  return ProtEntry;\r
+}\r
+\r
+\r
+PROTOCOL_INTERFACE *\r
+CoreFindProtocolInterface (\r
+  IN IHANDLE        *Handle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Finds the protocol instance for the requested handle and protocol.\r
+  \r
+  Note: This function doesn't do parameters checking, it's caller's responsibility \r
+        to pass in valid parameters.\r
+  \r
+Arguments:\r
+  \r
+  Handle    - The handle to search the protocol on\r
+  \r
+  Protocol  - GUID of the protocol\r
+\r
+  Interface - The interface for the protocol being searched\r
+\r
+Returns:\r
+\r
+  Protocol instance (NULL: Not found)\r
+\r
+--*/  \r
+{\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  LIST_ENTRY          *Link;\r
+\r
+  ASSERT_LOCKED(&gProtocolDatabaseLock);\r
+  Prot = NULL;\r
+\r
+  //\r
+  // Lookup the protocol entry for this protocol ID\r
+  //\r
+\r
+  ProtEntry = CoreFindProtocolEntry (Protocol, FALSE);\r
+  if (ProtEntry != NULL) {\r
+\r
+    //\r
+    // Look at each protocol interface for any matches\r
+    //\r
+    for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link=Link->ForwardLink) {\r
+\r
+      //\r
+      // If this protocol interface matches, remove it\r
+      //\r
+      Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+      if (Prot->Interface == Interface && Prot->Protocol == ProtEntry) {\r
+        break;\r
+      }\r
+\r
+      Prot = NULL;\r
+    }\r
+  }\r
+\r
+  return Prot;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreUnregisterProtocolNotifyEvent (\r
+  IN EFI_EVENT      Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes an event from a register protocol notify list on a protocol.\r
+\r
+Arguments:\r
+  \r
+  Event   - The event to search for in the protocol database.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS   if the event was found and removed.\r
+  EFI_NOT_FOUND if the event was not found in the protocl database.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY         *Link;\r
+  PROTOCOL_ENTRY     *ProtEntry;\r
+  LIST_ENTRY         *NotifyLink;\r
+  PROTOCOL_NOTIFY    *ProtNotify;\r
+\r
+  CoreAcquireProtocolLock ();\r
+\r
+  for ( Link =  mProtocolDatabase.ForwardLink; \r
+        Link != &mProtocolDatabase; \r
+        Link =  Link->ForwardLink) {\r
+\r
+    ProtEntry = CR(Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE);\r
+\r
+    for ( NotifyLink =  ProtEntry->Notify.ForwardLink; \r
+          NotifyLink != &ProtEntry->Notify; \r
+          NotifyLink =  NotifyLink->ForwardLink) {\r
+\r
+      ProtNotify = CR(NotifyLink, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);\r
+\r
+      if (ProtNotify->Event == Event) {\r
+        RemoveEntryList(&ProtNotify->Link);\r
+        CoreFreePool(ProtNotify);\r
+        CoreReleaseProtocolLock ();\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+  }\r
+\r
+  CoreReleaseProtocolLock ();\r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreUnregisterProtocolNotify (\r
+  IN EFI_EVENT      Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes all the events in the protocol database that match Event.\r
+\r
+Arguments:\r
+  \r
+  Event   - The event to search for in the protocol database.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS when done searching the entire database.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS       Status;\r
+\r
+  do {\r
+    Status = CoreUnregisterProtocolNotifyEvent (Event);\r
+  } while (!EFI_ERROR (Status));\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallProtocolInterface (\r
+  IN OUT EFI_HANDLE     *UserHandle,\r
+  IN EFI_GUID           *Protocol,\r
+  IN EFI_INTERFACE_TYPE InterfaceType,\r
+  IN VOID               *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Wrapper function to CoreInstallProtocolInterfaceNotify.  This is the public API which\r
+  Calls the private one which contains a BOOLEAN parameter for notifications\r
+\r
+Arguments:\r
+\r
+  UserHandle     - The handle to install the protocol handler on,\r
+                    or NULL if a new handle is to be allocated\r
+\r
+  Protocol       - The protocol to add to the handle\r
+\r
+  InterfaceType  - Indicates whether Interface is supplied in native form.\r
+\r
+  Interface      - The interface for the protocol being added\r
+\r
+Returns:\r
+\r
+  Status code    \r
+\r
+--*/\r
+{\r
+  return CoreInstallProtocolInterfaceNotify (\r
+            UserHandle, \r
+            Protocol, \r
+            InterfaceType, \r
+            Interface, \r
+            TRUE\r
+            );\r
+}\r
+\r
+EFI_STATUS\r
+CoreInstallProtocolInterfaceNotify (\r
+  IN OUT EFI_HANDLE     *UserHandle,\r
+  IN EFI_GUID           *Protocol,\r
+  IN EFI_INTERFACE_TYPE InterfaceType,\r
+  IN VOID               *Interface,\r
+  IN BOOLEAN            Notify\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Installs a protocol interface into the boot services environment.\r
+\r
+Arguments:\r
+\r
+  UserHandle     - The handle to install the protocol handler on,\r
+                   or NULL if a new handle is to be allocated\r
+\r
+  Protocol       - The protocol to add to the handle\r
+\r
+  InterfaceType  - Indicates whether Interface is supplied in native form.\r
+\r
+  Interface      - The interface for the protocol being added\r
+\r
+  Notify         - indicates whether notify the notification list \r
+                   for this protocol\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_OUT_OF_RESOURCES       - No enough buffer to allocate\r
+  \r
+  EFI_SUCCESS               - Protocol interface successfully installed\r
+\r
+--*/\r
+{\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  IHANDLE             *Handle;\r
+  EFI_STATUS          Status;\r
+  VOID                *ExistingInterface;\r
+\r
+  //\r
+  // returns EFI_INVALID_PARAMETER if InterfaceType is invalid.\r
+  // Also added check for invalid UserHandle and Protocol pointers.\r
+  //\r
+  if (UserHandle == NULL || Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (InterfaceType != EFI_NATIVE_INTERFACE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Print debug message\r
+  //\r
+  DEBUG((EFI_D_ERROR | EFI_D_INFO, "InstallProtocolInterface: %g %p\n", Protocol, Interface));\r
+\r
+  Status = EFI_OUT_OF_RESOURCES;\r
+  Prot = NULL;\r
+  Handle = NULL;\r
+\r
+  ASSERT (NULL != gDxeCoreBS);\r
+\r
+  if (*UserHandle != NULL_HANDLE) {\r
+    Status = CoreHandleProtocol (*UserHandle, Protocol, (VOID **)&ExistingInterface);\r
+    if (!EFI_ERROR (Status)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Lock the protocol database \r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Lookup the Protocol Entry for the requested protocol\r
+  //\r
+  ProtEntry = CoreFindProtocolEntry (Protocol, TRUE);\r
+  if (ProtEntry == NULL) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Allocate a new protocol interface structure\r
+  //\r
+  Prot = CoreAllocateZeroBootServicesPool (sizeof(PROTOCOL_INTERFACE));\r
+  if (Prot == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // If caller didn't supply a handle, allocate a new one\r
+  //\r
+  Handle = (IHANDLE *)*UserHandle;\r
+  if (Handle == NULL) {\r
+    Handle = CoreAllocateZeroBootServicesPool (sizeof(IHANDLE));\r
+    if (Handle == NULL) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Initialize new handler structure\r
+    //\r
+    Handle->Signature = EFI_HANDLE_SIGNATURE;\r
+    InitializeListHead (&Handle->Protocols);\r
+\r
+    //\r
+    // Initialize the Key to show that the handle has been created/modified\r
+    //\r
+    gHandleDatabaseKey++;\r
+    Handle->Key = gHandleDatabaseKey;\r
+\r
+    //\r
+    // Add this handle to the list global list of all handles\r
+    // in the system\r
+    //\r
+    InsertTailList (&gHandleList, &Handle->AllHandles);\r
+  } \r
+\r
+  Status = CoreValidateHandle (Handle);\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Each interface that is added must be unique\r
+  //\r
+  ASSERT (CoreFindProtocolInterface (Handle, Protocol, Interface) == NULL);\r
+\r
+  //\r
+  // Initialize the protocol interface structure\r
+  //\r
+  Prot->Signature = PROTOCOL_INTERFACE_SIGNATURE;\r
+  Prot->Handle = Handle;\r
+  Prot->Protocol = ProtEntry;\r
+  Prot->Interface = Interface;\r
+\r
+  //\r
+  // Initalize OpenProtocol Data base\r
+  //\r
+  InitializeListHead (&Prot->OpenList);\r
+  Prot->OpenListCount = 0;\r
+\r
+  //\r
+  // Add this protocol interface to the head of the supported \r
+  // protocol list for this handle\r
+  //\r
+  InsertHeadList (&Handle->Protocols, &Prot->Link);\r
+\r
+  //\r
+  // Add this protocol interface to the tail of the \r
+  // protocol entry\r
+  // \r
+  InsertTailList (&ProtEntry->Protocols, &Prot->ByProtocol);\r
+\r
+  //\r
+  // Notify the notification list for this protocol \r
+  //\r
+  if (Notify) {\r
+    CoreNotifyProtocolEntry (ProtEntry);\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\r
+  //\r
+  // Done, unlock the database and return\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Return the new handle back to the caller\r
+    //\r
+    *UserHandle = Handle;\r
+  } else {\r
+    //\r
+    // There was an error, clean up\r
+    //\r
+    if (Prot != NULL) {\r
+      CoreFreePool (Prot);\r
+    }\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallMultipleProtocolInterfaces (\r
+  IN OUT EFI_HANDLE           *Handle,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Installs a list of protocol interface into the boot services environment.\r
+  This function calls InstallProtocolInterface() in a loop. If any error\r
+  occures all the protocols added by this function are removed. This is \r
+  basically a lib function to save space.\r
+\r
+Arguments:\r
+\r
+  Handle      - The handle to install the protocol handlers on,\r
+                or NULL if a new handle is to be allocated\r
+  ...         - EFI_GUID followed by protocol instance. A NULL terminates the \r
+                list. The pairs are the arguments to InstallProtocolInterface().\r
+                All the protocols are added to Handle.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Handle is NULL.\r
+  \r
+  EFI_SUCCESS                 - Protocol interfaces successfully installed.\r
+\r
+--*/\r
+{\r
+  VA_LIST                   args;\r
+  EFI_STATUS                Status;\r
+  EFI_GUID                  *Protocol;\r
+  VOID                      *Interface;\r
+  EFI_TPL                   OldTpl;\r
+  UINTN                     Index;\r
+  EFI_HANDLE                OldHandle;\r
+  EFI_HANDLE                DeviceHandle;\r
+  EFI_DEVICE_PATH_PROTOCOL  *DevicePath;\r
+  \r
+  if (Handle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  //\r
+  // Syncronize with notifcations. \r
+  // \r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY);\r
+  OldHandle = *Handle;\r
+\r
+  //\r
+  // Check for duplicate device path and install the protocol interfaces\r
+  //\r
+  VA_START (args, Handle);\r
+  for (Index = 0, Status = EFI_SUCCESS; !EFI_ERROR (Status); Index++) {\r
+    //\r
+    // If protocol is NULL, then it's the end of the list\r
+    //\r
+    Protocol = VA_ARG (args, EFI_GUID *);\r
+    if (Protocol == NULL) {\r
+      break;\r
+    }\r
+\r
+    Interface = VA_ARG (args, VOID *);\r
+\r
+    //\r
+    // Make sure you are installing on top a device path that has already been added.\r
+    //\r
+    if (CompareGuid (Protocol, &gEfiDevicePathProtocolGuid)) {\r
+      DeviceHandle = NULL;\r
+      DevicePath   = Interface;\r
+      Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &DevicePath, &DeviceHandle);\r
+      if (!EFI_ERROR (Status) && (DeviceHandle != NULL_HANDLE) && IsDevicePathEnd(DevicePath)) {\r
+        Status = EFI_ALREADY_STARTED;\r
+        continue;\r
+      }\r
+    }\r
+  \r
+    //\r
+    // Install it\r
+    //\r
+    Status = CoreInstallProtocolInterface (Handle, Protocol, EFI_NATIVE_INTERFACE, Interface);\r
+  }\r
+  \r
+  //\r
+  // If there was an error, remove all the interfaces that were installed without any errors\r
+  //\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // Reset the va_arg back to the first argument.\r
+    //\r
+    VA_START (args, Handle);\r
+    for (; Index > 1; Index--) {\r
+      Protocol = VA_ARG (args, EFI_GUID *);\r
+      Interface = VA_ARG (args, VOID *);\r
+      CoreUninstallProtocolInterface (*Handle, Protocol, Interface);\r
+    }        \r
+    *Handle = OldHandle;\r
+  }\r
+\r
+  //\r
+  // Done\r
+  //\r
+  CoreRestoreTpl (OldTpl);\r
+  return Status;\r
+}\r
+\r
+EFI_STATUS\r
+CoreDisconnectControllersUsingProtocolInterface (\r
+  IN EFI_HANDLE           UserHandle,\r
+  IN PROTOCOL_INTERFACE   *Prot\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Attempts to disconnect all drivers that are using the protocol interface being queried.\r
+  If failed, reconnect all drivers disconnected.\r
+  \r
+  Note: This function doesn't do parameters checking, it's caller's responsibility \r
+        to pass in valid parameters.\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle on which the protocol is installed \r
+  Prot        - The protocol to disconnect drivers from\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Drivers using the protocol interface are all disconnected\r
+  EFI_ACCESS_DENIED - Failed to disconnect one or all of the drivers\r
+\r
+--*/\r
+{\r
+  EFI_STATUS            Status;\r
+  BOOLEAN               ItemFound;\r
+  LIST_ENTRY            *Link;\r
+  OPEN_PROTOCOL_DATA    *OpenData;\r
+\r
+  Status = EFI_SUCCESS;\r
+  \r
+  //\r
+  // Attempt to disconnect all drivers from this protocol interface\r
+  //\r
+  do {\r
+    ItemFound = FALSE;\r
+    for ( Link = Prot->OpenList.ForwardLink;\r
+          (Link != &Prot->OpenList) && !ItemFound;\r
+          Link = Link->ForwardLink ) {\r
+      OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+      if (OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) {\r
+        ItemFound = TRUE;\r
+        CoreReleaseProtocolLock ();\r
+        Status = CoreDisconnectController (UserHandle, OpenData->AgentHandle, NULL);\r
+        CoreAcquireProtocolLock ();\r
+        if (EFI_ERROR (Status)) {\r
+           ItemFound = FALSE;\r
+           break;\r
+        }\r
+      }\r
+    }\r
+  } while (ItemFound);\r
+\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Attempt to remove BY_HANDLE_PROTOOCL and GET_PROTOCOL and TEST_PROTOCOL Open List items\r
+    //\r
+    do {\r
+      ItemFound = FALSE;\r
+      for ( Link = Prot->OpenList.ForwardLink;\r
+            (Link != &Prot->OpenList) && !ItemFound;\r
+            Link = Link->ForwardLink ) {\r
+        OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+        if (OpenData->Attributes & \r
+            (EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL | EFI_OPEN_PROTOCOL_GET_PROTOCOL | EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) {\r
+          ItemFound = TRUE;\r
+          RemoveEntryList (&OpenData->Link);  \r
+          Prot->OpenListCount--;\r
+          CoreFreePool (OpenData);\r
+        }\r
+      }\r
+    } while (ItemFound);\r
+  }\r
+\r
+  //\r
+  // If there are errors or still has open items in the list, then reconnect all the drivers and return an error\r
+  //\r
+  if (EFI_ERROR (Status) || (Prot->OpenListCount > 0)) {\r
+    CoreReleaseProtocolLock ();\r
+    CoreConnectController (UserHandle, NULL, NULL, TRUE);\r
+    CoreAcquireProtocolLock ();\r
+    Status = EFI_ACCESS_DENIED;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUninstallProtocolInterface (\r
+  IN EFI_HANDLE       UserHandle,\r
+  IN EFI_GUID         *Protocol,\r
+  IN VOID             *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Uninstalls all instances of a protocol:interfacer from a handle. \r
+  If the last protocol interface is remove from the handle, the \r
+  handle is freed.\r
+\r
+Arguments:\r
+\r
+  UserHandle      - The handle to remove the protocol handler from\r
+\r
+  Protocol        - The protocol, of protocol:interface, to remove\r
+\r
+  Interface       - The interface, of protocol:interface, to remove\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Protocol is NULL.\r
+  \r
+  EFI_SUCCESS                 - Protocol interface successfully uninstalled.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS            Status;\r
+  IHANDLE               *Handle;\r
+  PROTOCOL_INTERFACE    *Prot;\r
+\r
+  //\r
+  // Check that Protocol is valid\r
+  //\r
+  if (Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Check that UserHandle is a valid handle\r
+  //\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Check that Protocol exists on UserHandle, and Interface matches the interface in the database\r
+  //\r
+  Prot = CoreFindProtocolInterface (UserHandle, Protocol, Interface);\r
+  if (Prot == NULL) {\r
+    Status = EFI_NOT_FOUND;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Attempt to disconnect all drivers that are using the protocol interface that is about to be removed\r
+  //\r
+  Status = CoreDisconnectControllersUsingProtocolInterface (\r
+             UserHandle,\r
+             Prot\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // One or more drivers refused to release, so return the error\r
+    //\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Remove the protocol interface from the protocol\r
+  //\r
+  Status = EFI_NOT_FOUND;\r
+  Handle = (IHANDLE *)UserHandle;\r
+  Prot   = CoreRemoveInterfaceFromProtocol (Handle, Protocol, Interface);\r
+\r
+  if (Prot != NULL) {\r
+    //\r
+    // Update the Key to show that the handle has been created/modified\r
+    //\r
+    gHandleDatabaseKey++;\r
+    Handle->Key = gHandleDatabaseKey;\r
+    \r
+    //\r
+    // Remove the protocol interface from the handle\r
+    //\r
+    RemoveEntryList (&Prot->Link);\r
+\r
+    //\r
+    // Free the memory\r
+    //\r
+    Prot->Signature = 0;\r
+    CoreFreePool (Prot);\r
+    Status = EFI_SUCCESS;\r
+  }\r
+\r
+  //\r
+  // If there are no more handlers for the handle, free the handle\r
+  //\r
+  if (IsListEmpty (&Handle->Protocols)) {\r
+    Handle->Signature = 0;\r
+    RemoveEntryList (&Handle->AllHandles);\r
+    CoreFreePool (Handle);\r
+  }\r
+\r
+Done:  \r
+  //\r
+  // Done, unlock the database and return\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUninstallMultipleProtocolInterfaces (\r
+  IN EFI_HANDLE           Handle,\r
+  ...\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Uninstalls a list of protocol interface in the boot services environment. \r
+  This function calls UnisatllProtocolInterface() in a loop. This is \r
+  basically a lib function to save space.\r
+\r
+Arguments:\r
+\r
+  Handle      - The handle to uninstall the protocol\r
+\r
+  ...         - EFI_GUID followed by protocol instance. A NULL terminates the \r
+                list. The pairs are the arguments to UninstallProtocolInterface().\r
+                All the protocols are added to Handle.\r
+\r
+Returns:\r
+\r
+  Status code    \r
+\r
+--*/\r
+{\r
+  EFI_STATUS      Status;\r
+  VA_LIST         args;\r
+  EFI_GUID        *Protocol;\r
+  VOID            *Interface;\r
+  UINTN           Index;\r
+\r
+  VA_START (args, Handle);\r
+  for (Index = 0, Status = EFI_SUCCESS; !EFI_ERROR (Status); Index++) {\r
+    //\r
+    // If protocol is NULL, then it's the end of the list\r
+    //\r
+    Protocol = VA_ARG (args, EFI_GUID *);\r
+    if (Protocol == NULL) {\r
+      break;\r
+    }\r
+\r
+    Interface = VA_ARG (args, VOID *);\r
+\r
+    //\r
+    // Uninstall it\r
+    //\r
+    Status = CoreUninstallProtocolInterface (Handle, Protocol, Interface);\r
+  }\r
+\r
+  //\r
+  // If there was an error, add all the interfaces that were\r
+  // uninstalled without any errors\r
+  //\r
+  if (EFI_ERROR (Status)) {\r
+    //\r
+    // Reset the va_arg back to the first argument.\r
+    //\r
+    VA_START (args, Handle);\r
+    for (; Index > 1; Index--) {\r
+      Protocol = VA_ARG(args, EFI_GUID *);\r
+      Interface = VA_ARG(args, VOID *);\r
+      CoreInstallProtocolInterface (&Handle, Protocol, EFI_NATIVE_INTERFACE, Interface);\r
+    }        \r
+  }\r
+\r
+  return Status;\r
+}    \r
+\r
+STATIC\r
+PROTOCOL_INTERFACE  *\r
+CoreGetProtocolInterface (\r
+  IN  EFI_HANDLE                UserHandle,\r
+  IN  EFI_GUID                  *Protocol\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locate a certain GUID protocol interface in a Handle's protocols.\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle to obtain the protocol interface on\r
+\r
+  Protocol    - The GUID of the protocol \r
+\r
+Returns:\r
+\r
+  The requested protocol interface for the handle\r
+  \r
+--*/  \r
+{\r
+  EFI_STATUS          Status;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  IHANDLE             *Handle;\r
+  LIST_ENTRY          *Link;\r
+\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return NULL;\r
+  }\r
+  \r
+  Handle = (IHANDLE *)UserHandle;\r
+\r
+  //\r
+  // Look at each protocol interface for a match\r
+  //\r
+  for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+    Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+    ProtEntry = Prot->Protocol;\r
+    if (CompareGuid (&ProtEntry->ProtocolID, Protocol)) {\r
+      return Prot;\r
+    }\r
+  }\r
+  return NULL;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreHandleProtocol (\r
+  IN EFI_HANDLE       UserHandle,\r
+  IN EFI_GUID         *Protocol,\r
+  OUT VOID            **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Queries a handle to determine if it supports a specified protocol.\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle being queried.\r
+\r
+  Protocol    - The published unique identifier of the protocol.\r
+\r
+  Interface   - Supplies the address where a pointer to the corresponding Protocol\r
+               Interface is returned.\r
+\r
+Returns:\r
+\r
+  The requested protocol interface for the handle\r
+  \r
+--*/  \r
+{\r
+  return CoreOpenProtocol (\r
+          UserHandle,     \r
+          Protocol, \r
+          Interface, \r
+          gDxeCoreImageHandle, \r
+          NULL,     \r
+          EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL\r
+          );\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreOpenProtocol (\r
+  IN  EFI_HANDLE                UserHandle,\r
+  IN  EFI_GUID                  *Protocol,\r
+  OUT VOID                      **Interface OPTIONAL,\r
+  IN  EFI_HANDLE                ImageHandle,\r
+  IN  EFI_HANDLE                ControllerHandle,\r
+  IN  UINT32                    Attributes\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the installed protocol handler for the handle, and\r
+  invokes it to obtain the protocol interface. Usage information\r
+  is registered in the protocol data base.\r
+\r
+Arguments:\r
+\r
+  UserHandle     - The handle to obtain the protocol interface on\r
+\r
+  Protocol       - The ID of the protocol \r
+\r
+  Interface      - The location to return the protocol interface\r
+\r
+  ImageHandle       - The handle of the Image that is opening the protocol interface\r
+                    specified by Protocol and Interface.\r
+  \r
+  ControllerHandle  - The controller handle that is requiring this interface.\r
+\r
+  Attributes     - The open mode of the protocol interface specified by Handle\r
+                    and Protocol.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Protocol is NULL.\r
+  \r
+  EFI_SUCCESS                 - Get the protocol interface.\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS          Status;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  LIST_ENTRY          *Link;\r
+  OPEN_PROTOCOL_DATA  *OpenData;\r
+  BOOLEAN             ByDriver;\r
+  BOOLEAN             Exclusive;\r
+  BOOLEAN             Disconnect;\r
+  BOOLEAN             ExactMatch;\r
+\r
+  //\r
+  // Check for invalid Protocol\r
+  //\r
+  if (Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Check for invalid Interface\r
+  //\r
+  if (Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) {\r
+    if (Interface == NULL) {\r
+      return EFI_INVALID_PARAMETER;\r
+    } else {\r
+      *Interface = NULL;\r
+    }\r
+  }\r
+  \r
+  //\r
+  // Check for invalid UserHandle\r
+  //\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Check for invalid Attributes\r
+  //\r
+  switch (Attributes) {\r
+  case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER :\r
+    Status = CoreValidateHandle (ImageHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    Status = CoreValidateHandle (ControllerHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    if (UserHandle == ControllerHandle) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+    break;\r
+  case EFI_OPEN_PROTOCOL_BY_DRIVER :\r
+  case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE :\r
+    Status = CoreValidateHandle (ImageHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    Status = CoreValidateHandle (ControllerHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    break;\r
+  case EFI_OPEN_PROTOCOL_EXCLUSIVE :\r
+    Status = CoreValidateHandle (ImageHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    break;\r
+  case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL :\r
+  case EFI_OPEN_PROTOCOL_GET_PROTOCOL :\r
+  case EFI_OPEN_PROTOCOL_TEST_PROTOCOL :\r
+    break;\r
+  default:\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Look at each protocol interface for a match\r
+  //\r
+  Prot = CoreGetProtocolInterface (UserHandle, Protocol);\r
+  if (Prot == NULL) {\r
+    Status = EFI_UNSUPPORTED;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // This is the protocol interface entry for this protocol\r
+  //    \r
+  if (Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) {\r
+    *Interface = Prot->Interface;\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+  ByDriver        = FALSE;\r
+  Exclusive       = FALSE;\r
+  for ( Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) {\r
+    OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+    ExactMatch =  (BOOLEAN)((OpenData->AgentHandle == ImageHandle) && \r
+                            (OpenData->Attributes == Attributes)  &&\r
+                            (OpenData->ControllerHandle == ControllerHandle));\r
+    if (OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) {\r
+      ByDriver = TRUE;\r
+      if (ExactMatch) {\r
+        Status = EFI_ALREADY_STARTED;\r
+        goto Done;\r
+      }\r
+    }\r
+    if (OpenData->Attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) {\r
+      Exclusive = TRUE;\r
+    } else if (ExactMatch) {\r
+      OpenData->OpenCount++;\r
+      Status = EFI_SUCCESS;\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  //\r
+  // ByDriver  TRUE  -> A driver is managing (UserHandle, Protocol)\r
+  // ByDriver  FALSE -> There are no drivers managing (UserHandle, Protocol)\r
+  // Exclusive TRUE  -> Something has exclusive access to (UserHandle, Protocol)\r
+  // Exclusive FALSE -> Nothing has exclusive access to (UserHandle, Protocol)\r
+  //\r
+\r
+  switch (Attributes) {\r
+  case EFI_OPEN_PROTOCOL_BY_DRIVER :\r
+    if (Exclusive || ByDriver) {\r
+      Status = EFI_ACCESS_DENIED;\r
+      goto Done;\r
+    }\r
+    break;\r
+  case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE :\r
+  case EFI_OPEN_PROTOCOL_EXCLUSIVE :\r
+    if (Exclusive) {\r
+      Status = EFI_ACCESS_DENIED;\r
+      goto Done;\r
+    }\r
+    if (ByDriver) {\r
+      do {\r
+        Disconnect = FALSE;\r
+        for ( Link = Prot->OpenList.ForwardLink; (Link != &Prot->OpenList) && (!Disconnect); Link = Link->ForwardLink) {\r
+          OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+          if (OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) {\r
+            Disconnect = TRUE;\r
+            CoreReleaseProtocolLock ();\r
+            Status = CoreDisconnectController (UserHandle, OpenData->AgentHandle, NULL);\r
+            CoreAcquireProtocolLock ();\r
+            if (EFI_ERROR (Status)) {\r
+              Status = EFI_ACCESS_DENIED;\r
+              goto Done;\r
+            }\r
+          }\r
+        }\r
+      } while (Disconnect);\r
+    } \r
+    break;\r
+  case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER :\r
+  case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL :\r
+  case EFI_OPEN_PROTOCOL_GET_PROTOCOL :\r
+  case EFI_OPEN_PROTOCOL_TEST_PROTOCOL :\r
+    break;\r
+  }\r
+\r
+  if (ImageHandle == NULL) {\r
+    Status = EFI_SUCCESS;\r
+    goto Done;\r
+  }\r
+  //\r
+  // Create new entry\r
+  //\r
+  OpenData = CoreAllocateBootServicesPool (sizeof(OPEN_PROTOCOL_DATA));\r
+  if (OpenData == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+  } else {\r
+    OpenData->Signature         = OPEN_PROTOCOL_DATA_SIGNATURE;\r
+    OpenData->AgentHandle       = ImageHandle;\r
+    OpenData->ControllerHandle  = ControllerHandle;\r
+    OpenData->Attributes        = Attributes;\r
+    OpenData->OpenCount         = 1;\r
+    InsertTailList (&Prot->OpenList, &OpenData->Link);\r
+    Prot->OpenListCount++;\r
+    Status = EFI_SUCCESS;\r
+  }\r
+\r
+Done:\r
+  //\r
+  // Done. Release the database lock are return\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreCloseProtocol (\r
+  IN  EFI_HANDLE                UserHandle,\r
+  IN  EFI_GUID                  *Protocol,\r
+  IN  EFI_HANDLE                AgentHandle,\r
+  IN  EFI_HANDLE                ControllerHandle  \r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Closes a protocol on a handle that was opened using OpenProtocol().\r
+\r
+Arguments:\r
+\r
+  UserHandle       -  The handle for the protocol interface that was previously opened\r
+                      with OpenProtocol(), and is now being closed.\r
+  Protocol         -  The published unique identifier of the protocol. It is the caller's\r
+                      responsibility to pass in a valid GUID.\r
+  AgentHandle      -  The handle of the agent that is closing the protocol interface.\r
+  ControllerHandle -  If the agent that opened a protocol is a driver that follows the\r
+                      EFI Driver Model, then this parameter is the controller handle\r
+                      that required the protocol interface. If the agent does not follow\r
+                      the EFI Driver Model, then this parameter is optional and may be NULL.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS             - The protocol instance was closed.\r
+  EFI_INVALID_PARAMETER   - Handle, AgentHandle or ControllerHandle is not a valid EFI_HANDLE. \r
+  EFI_NOT_FOUND           - Can not find the specified protocol or AgentHandle.\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS          Status;\r
+  PROTOCOL_INTERFACE  *ProtocolInterface;\r
+  LIST_ENTRY          *Link;\r
+  OPEN_PROTOCOL_DATA  *OpenData;\r
+\r
+  //\r
+  // Check for invalid parameters\r
+  //\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+  Status = CoreValidateHandle (AgentHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+  if (ControllerHandle != NULL_HANDLE) {\r
+    Status = CoreValidateHandle (ControllerHandle);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+  if (Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Look at each protocol interface for a match\r
+  //\r
+  Status = EFI_NOT_FOUND;\r
+  ProtocolInterface = CoreGetProtocolInterface (UserHandle, Protocol);\r
+  if (ProtocolInterface == NULL) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Walk the Open data base looking for AgentHandle\r
+  //\r
+  Link = ProtocolInterface->OpenList.ForwardLink;\r
+  while (Link != &ProtocolInterface->OpenList) {\r
+    OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+    Link = Link->ForwardLink;\r
+    if ((OpenData->AgentHandle == AgentHandle) && (OpenData->ControllerHandle == ControllerHandle)) {\r
+        RemoveEntryList (&OpenData->Link);  \r
+        ProtocolInterface->OpenListCount--;\r
+        CoreFreePool (OpenData);\r
+        Status = EFI_SUCCESS;\r
+    }\r
+  }\r
+\r
+Done:\r
+  //\r
+  // Done. Release the database lock and return.\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreOpenProtocolInformation (\r
+  IN  EFI_HANDLE                          UserHandle,\r
+  IN  EFI_GUID                            *Protocol,\r
+  OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer,\r
+  OUT UINTN                               *EntryCount\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return information about Opened protocols in the system\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle to close the protocol interface on\r
+\r
+  Protocol    - The ID of the protocol \r
+\r
+  EntryBuffer - A pointer to a buffer of open protocol information in the form of\r
+                EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures.\r
+\r
+  EntryCount  - Number of EntryBuffer entries\r
+\r
+Returns:\r
+\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  PROTOCOL_INTERFACE                  *ProtocolInterface;\r
+  LIST_ENTRY                          *Link;\r
+  OPEN_PROTOCOL_DATA                  *OpenData;\r
+  EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *Buffer;\r
+  UINTN                               Count;\r
+  UINTN                               Size;\r
+\r
+  *EntryBuffer = NULL;\r
+  *EntryCount = 0;\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Look at each protocol interface for a match\r
+  //\r
+  Status = EFI_NOT_FOUND;\r
+  ProtocolInterface = CoreGetProtocolInterface (UserHandle, Protocol);\r
+  if (ProtocolInterface == NULL) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Count the number of Open Entries\r
+  //\r
+  for ( Link = ProtocolInterface->OpenList.ForwardLink, Count = 0; \r
+        (Link != &ProtocolInterface->OpenList) ;\r
+        Link = Link->ForwardLink  ) {\r
+    Count++;\r
+  } \r
+\r
+  ASSERT (Count == ProtocolInterface->OpenListCount);\r
+\r
+  if (Count == 0) {\r
+    Size = sizeof(EFI_OPEN_PROTOCOL_INFORMATION_ENTRY);\r
+  } else {\r
+    Size = Count * sizeof(EFI_OPEN_PROTOCOL_INFORMATION_ENTRY);\r
+  }\r
+\r
+  Buffer = CoreAllocateBootServicesPool (Size);\r
+  if (Buffer == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  Status = EFI_SUCCESS;\r
+  for ( Link = ProtocolInterface->OpenList.ForwardLink, Count = 0; \r
+        (Link != &ProtocolInterface->OpenList);\r
+        Link = Link->ForwardLink, Count++  ) {\r
+    OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE);\r
+\r
+    Buffer[Count].AgentHandle      = OpenData->AgentHandle;\r
+    Buffer[Count].ControllerHandle = OpenData->ControllerHandle;\r
+    Buffer[Count].Attributes       = OpenData->Attributes;\r
+    Buffer[Count].OpenCount        = OpenData->OpenCount;\r
+  } \r
+\r
+  *EntryBuffer = Buffer;\r
+  *EntryCount = Count;\r
+        \r
+Done:\r
+  //\r
+  // Done. Release the database lock are return\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreProtocolsPerHandle (\r
+  IN EFI_HANDLE       UserHandle,\r
+  OUT EFI_GUID        ***ProtocolBuffer,\r
+  OUT UINTN           *ProtocolBufferCount\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated\r
+ from pool.\r
+\r
+Arguments:\r
+\r
+  UserHandle           - The handle from which to retrieve the list of protocol interface\r
+                          GUIDs.\r
+\r
+  ProtocolBuffer       - A pointer to the list of protocol interface GUID pointers that are\r
+                          installed on Handle.\r
+\r
+  ProtocolBufferCount  - A pointer to the number of GUID pointers present in\r
+                          ProtocolBuffer.\r
+\r
+Returns:\r
+  EFI_SUCCESS   -  The list of protocol interface GUIDs installed on Handle was returned in\r
+                   ProtocolBuffer. The number of protocol interface GUIDs was\r
+                   returned in ProtocolBufferCount.\r
+  EFI_INVALID_PARAMETER   -  Handle is NULL.\r
+  EFI_INVALID_PARAMETER   -  Handle is not a valid EFI_HANDLE.\r
+  EFI_INVALID_PARAMETER   -  ProtocolBuffer is NULL.\r
+  EFI_INVALID_PARAMETER   -  ProtocolBufferCount is NULL.\r
+  EFI_OUT_OF_RESOURCES    -  There is not enough pool memory to store the results.\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  IHANDLE                             *Handle;\r
+  PROTOCOL_INTERFACE                  *Prot;\r
+  LIST_ENTRY                          *Link;\r
+  UINTN                               ProtocolCount;\r
+  EFI_GUID                            **Buffer;\r
+\r
+  Status = CoreValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  Handle = (IHANDLE *)UserHandle;\r
+\r
+  if (ProtocolBuffer == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (ProtocolBufferCount == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  *ProtocolBufferCount = 0;\r
+\r
+  ProtocolCount = 0;\r
+\r
+  CoreAcquireProtocolLock ();\r
+  \r
+  for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) {\r
+    ProtocolCount++;\r
+  }\r
+\r
+  //\r
+  // If there are no protocol interfaces installed on Handle, then Handle is not a valid EFI_HANDLE\r
+  //\r
+  if (ProtocolCount == 0) {\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
+  }\r
+\r
+  Buffer = CoreAllocateBootServicesPool (sizeof (EFI_GUID *) * ProtocolCount);\r
+  if (Buffer == NULL) {\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    goto Done;\r
+  }\r
+\r
+  *ProtocolBuffer = Buffer;\r
+  *ProtocolBufferCount = ProtocolCount;\r
+\r
+  for ( Link = Handle->Protocols.ForwardLink, ProtocolCount = 0;\r
+        Link != &Handle->Protocols; \r
+        Link = Link->ForwardLink, ProtocolCount++) {\r
+    Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE);\r
+    Buffer[ProtocolCount] = &(Prot->Protocol->ProtocolID);\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+UINT64\r
+CoreGetHandleDatabaseKey (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  return handle database key.\r
+\r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+  \r
+  Handle database key.\r
+  \r
+--*/\r
+{\r
+  return gHandleDatabaseKey;\r
+}\r
+\r
+\r
+VOID\r
+CoreConnectHandlesByKey (\r
+  UINT64  Key\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Go connect any handles that were created or modified while a image executed.\r
+\r
+Arguments:\r
+\r
+  Key  -  The Key to show that the handle has been created/modified\r
+\r
+Returns:\r
+  \r
+  None\r
+--*/\r
+{\r
+  UINTN           Count;\r
+  LIST_ENTRY      *Link;\r
+  EFI_HANDLE      *HandleBuffer;\r
+  IHANDLE         *Handle;\r
+  UINTN           Index;\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  for (Link = gHandleList.ForwardLink, Count = 0; Link != &gHandleList; Link = Link->ForwardLink) {\r
+    Handle = CR (Link, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE);\r
+    if (Handle->Key > Key) {\r
+      Count++;\r
+    }\r
+  }\r
+\r
+  HandleBuffer = CoreAllocateBootServicesPool (Count * sizeof (EFI_HANDLE));\r
+  if (HandleBuffer == NULL) {\r
+    CoreReleaseProtocolLock ();\r
+    return;\r
+  }\r
+  \r
+  for (Link = gHandleList.ForwardLink, Count = 0; Link != &gHandleList; Link = Link->ForwardLink) {\r
+    Handle = CR (Link, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE);\r
+    if (Handle->Key > Key) {\r
+      HandleBuffer[Count++] = Handle;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Unlock the protocol database\r
+  //\r
+  CoreReleaseProtocolLock ();\r
+\r
+  //\r
+  // Connect all handles whose Key value is greater than Key\r
+  //\r
+  for (Index = 0; Index < Count; Index++) {\r
+    CoreConnectController (HandleBuffer[Index], NULL, NULL, TRUE);\r
+  }\r
+  \r
+  CoreFreePool(HandleBuffer);\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Hand/locate.c b/MdeModulePkg/Core/Dxe/Hand/locate.c
new file mode 100644 (file)
index 0000000..54d72c3
--- /dev/null
@@ -0,0 +1,733 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  locate.c\r
+\r
+Abstract:\r
+\r
+  Locate handle functions    \r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// ProtocolRequest - Last LocateHandle request ID\r
+//\r
+UINTN mEfiLocateHandleRequest = 0;\r
+\r
+//\r
+// Internal prototypes\r
+//\r
+\r
+typedef struct {\r
+  EFI_GUID        *Protocol;\r
+  VOID            *SearchKey;\r
+  LIST_ENTRY      *Position;\r
+  PROTOCOL_ENTRY  *ProtEntry;\r
+} LOCATE_POSITION;\r
+\r
+typedef \r
+IHANDLE *\r
+(* CORE_GET_NEXT) (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  );\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateAllHandles (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  );\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateByRegisterNotify (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  );\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateByProtocol (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  );\r
+\r
+//\r
+//\r
+//\r
+\r
+\r
+\r
\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateHandle (\r
+  IN EFI_LOCATE_SEARCH_TYPE   SearchType,\r
+  IN EFI_GUID                 *Protocol   OPTIONAL,\r
+  IN VOID                     *SearchKey  OPTIONAL,\r
+  IN OUT UINTN                *BufferSize,\r
+  OUT EFI_HANDLE              *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the requested handle(s) and returns them in Buffer.\r
+\r
+Arguments:\r
+\r
+  SearchType  - The type of search to perform to locate the handles\r
+\r
+  Protocol    - The protocol to search for\r
+  \r
+  SearchKey   - Dependant on SearchType\r
+\r
+  BufferSize  - On input the size of Buffer.  On output the \r
+                size of data returned.  \r
+\r
+  Buffer      - The buffer to return the results in\r
+\r
+\r
+Returns:\r
+\r
+  EFI_BUFFER_TOO_SMALL      - Buffer too small, required buffer size is returned in BufferSize.\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+  \r
+  EFI_SUCCESS               - Successfully found the requested handle(s) and returns them in Buffer.\r
+  \r
+--*/\r
+{\r
+  EFI_STATUS          Status;\r
+  LOCATE_POSITION     Position;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  CORE_GET_NEXT       GetNext;\r
+  UINTN               ResultSize;\r
+  IHANDLE             *Handle;\r
+  IHANDLE             **ResultBuffer;\r
+  VOID                *Interface;\r
\r
+  if (BufferSize == NULL) {\r
+    Status = EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  if ((*BufferSize > 0) && (Buffer == NULL)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  GetNext = NULL;\r
+  //\r
+  // Set initial position\r
+  //\r
+\r
+  Position.Protocol  = Protocol;\r
+  Position.SearchKey = SearchKey;\r
+  Position.Position  = &gHandleList;\r
+\r
+  ResultSize = 0;\r
+  ResultBuffer = (IHANDLE **) Buffer;\r
+  Status = EFI_SUCCESS;\r
+\r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  \r
+  CoreAcquireProtocolLock ();\r
+\r
+  //\r
+  // Get the search function based on type\r
+  //\r
+  switch (SearchType) {\r
+  case AllHandles:      \r
+    GetNext = CoreGetNextLocateAllHandles;       \r
+    break;\r
+\r
+  case ByRegisterNotify:    \r
+    //\r
+    // Must have SearchKey for locate ByRegisterNotify\r
+    //\r
+    if (SearchKey == NULL) {\r
+      Status = EFI_INVALID_PARAMETER;\r
+      break;\r
+    }\r
+    GetNext = CoreGetNextLocateByRegisterNotify;   \r
+    break;\r
+\r
+  case ByProtocol:      \r
+    GetNext = CoreGetNextLocateByProtocol;\r
+    if (Protocol == NULL) {\r
+      Status = EFI_INVALID_PARAMETER;\r
+      break;\r
+    }\r
+    //\r
+    // Look up the protocol entry and set the head pointer\r
+    //\r
+    Position.ProtEntry = CoreFindProtocolEntry (Protocol, FALSE);\r
+    if (Position.ProtEntry == NULL) {\r
+      Status = EFI_NOT_FOUND;\r
+      break;\r
+    }\r
+    Position.Position = &Position.ProtEntry->Protocols;\r
+    break;\r
+\r
+  default:\r
+    Status = EFI_INVALID_PARAMETER;\r
+    break;\r
+  }\r
+\r
+  if (EFI_ERROR(Status)) {\r
+    CoreReleaseProtocolLock ();\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Enumerate out the matching handles\r
+  //\r
+  mEfiLocateHandleRequest += 1;\r
+  for (; ;) {\r
+    //\r
+    // Get the next handle.  If no more handles, stop\r
+    //\r
+    Handle = GetNext (&Position, &Interface);\r
+    if (NULL == Handle) {\r
+      break;\r
+    }\r
+\r
+    //\r
+    // Increase the resulting buffer size, and if this handle\r
+    // fits return it\r
+    //\r
+    ResultSize += sizeof(Handle);\r
+    if (ResultSize <= *BufferSize) {\r
+        *ResultBuffer = Handle;\r
+        ResultBuffer += 1;\r
+    }\r
+  }\r
+\r
+  //\r
+  // If the result is a zero length buffer, then there were no\r
+  // matching handles\r
+  //\r
+  if (ResultSize == 0) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else {\r
+    //\r
+    // Return the resulting buffer size.  If it's larger than what\r
+    // was passed, then set the error code\r
+    //\r
+    if (ResultSize > *BufferSize) {\r
+      Status = EFI_BUFFER_TOO_SMALL;\r
+    } \r
+    \r
+    *BufferSize = ResultSize;\r
+\r
+    if (SearchType == ByRegisterNotify && !EFI_ERROR(Status)) {\r
+      //\r
+      // If this is a search by register notify and a handle was\r
+      // returned, update the register notification position\r
+      // \r
+      ProtNotify = SearchKey;\r
+      ProtNotify->Position = ProtNotify->Position->ForwardLink;\r
+    }\r
+  }\r
+\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateAllHandles (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Routine to get the next Handle, when you are searching for all handles.\r
+\r
+Arguments:\r
+\r
+  Position  - Information about which Handle to seach for.\r
+\r
+  Interface - Return the interface structure for the matching protocol.\r
+  \r
+Returns:\r
+  IHANDLE - An IHANDLE is returned if the next Position is not the end of the\r
+            list. A NULL_HANDLE is returned if it's the end of the list.\r
+  \r
+--*/\r
+{\r
+  IHANDLE     *Handle;\r
+\r
+  //\r
+  // Next handle\r
+  //\r
+  Position->Position = Position->Position->ForwardLink;\r
+\r
+  //\r
+  // If not at the end of the list, get the handle\r
+  //\r
+  Handle      = NULL_HANDLE;\r
+  *Interface  = NULL;\r
+  if (Position->Position != &gHandleList) {\r
+    Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE);\r
+  }\r
+\r
+  return Handle;\r
+}\r
+\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateByRegisterNotify (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Routine to get the next Handle, when you are searching for register protocol \r
+  notifies.\r
+\r
+Arguments:\r
+\r
+  Position  - Information about which Handle to seach for.\r
+\r
+  Interface - Return the interface structure for the matching protocol.\r
+  \r
+Returns:\r
+  IHANDLE - An IHANDLE is returned if the next Position is not the end of the\r
+            list. A NULL_HANDLE is returned if it's the end of the list.\r
+  \r
+--*/\r
+{\r
+  IHANDLE             *Handle;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  LIST_ENTRY          *Link;    \r
+\r
+  Handle      = NULL_HANDLE;\r
+  *Interface  = NULL;\r
+  ProtNotify = Position->SearchKey;\r
+\r
+  //\r
+  // If this is the first request, get the next handle\r
+  //\r
+  if (ProtNotify != NULL) {\r
+    ASSERT(ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE);\r
+    Position->SearchKey = NULL;\r
+\r
+    //\r
+    // If not at the end of the list, get the next handle\r
+    //\r
+    Link = ProtNotify->Position->ForwardLink;\r
+    if (Link != &ProtNotify->Protocol->Protocols) {\r
+      Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE);\r
+      Handle = (IHANDLE *) Prot->Handle;\r
+      *Interface = Prot->Interface;\r
+    }  \r
+  }\r
+\r
+  return Handle;\r
+}\r
+\r
+\r
+STATIC\r
+IHANDLE *\r
+CoreGetNextLocateByProtocol (\r
+  IN OUT LOCATE_POSITION    *Position,\r
+  OUT VOID                  **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Routine to get the next Handle, when you are searching for a given protocol.\r
+\r
+Arguments:\r
+\r
+  Position  - Information about which Handle to seach for.\r
+\r
+  Interface - Return the interface structure for the matching protocol.\r
+  \r
+Returns:\r
+  IHANDLE - An IHANDLE is returned if the next Position is not the end of the\r
+            list. A NULL_HANDLE is returned if it's the end of the list.\r
+  \r
+--*/\r
+{\r
+  IHANDLE             *Handle;\r
+  LIST_ENTRY          *Link;\r
+  PROTOCOL_INTERFACE  *Prot;\r
\r
+  Handle      = NULL_HANDLE;\r
+  *Interface  = NULL;\r
+  for (; ;) {\r
+    //\r
+    // Next entry\r
+    //\r
+    Link = Position->Position->ForwardLink;\r
+    Position->Position = Link;\r
+\r
+    //\r
+    // If not at the end, return the handle\r
+    //\r
+    if (Link == &Position->ProtEntry->Protocols) {\r
+      Handle = NULL_HANDLE;\r
+      break;\r
+    }\r
+\r
+    //\r
+    // Get the handle\r
+    //\r
+    Prot = CR(Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE);\r
+    Handle = (IHANDLE *) Prot->Handle;\r
+    *Interface = Prot->Interface;\r
+\r
+    //\r
+    // If this handle has not been returned this request, then \r
+    // return it now\r
+    //\r
+    if (Handle->LocateRequest != mEfiLocateHandleRequest) {\r
+      Handle->LocateRequest = mEfiLocateHandleRequest;\r
+      break;\r
+    }\r
+  }\r
+\r
+  return Handle;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateDevicePath (\r
+  IN EFI_GUID                       *Protocol,\r
+  IN OUT EFI_DEVICE_PATH_PROTOCOL   **DevicePath,\r
+  OUT EFI_HANDLE                    *Device\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Locates the handle to a device on the device path that best matches the specified protocol.\r
+\r
+Arguments:\r
+\r
+  Protocol    - The protocol to search for.\r
+  DevicePath  - On input, a pointer to a pointer to the device path. On output, the device\r
+                  path pointer is modified to point to the remaining part of the devicepath.\r
+  Device      - A pointer to the returned device handle.              \r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The resulting handle was returned.\r
+  EFI_NOT_FOUND         - No handles matched the search.\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value.\r
+\r
+--*/\r
+{\r
+  INTN                        SourceSize;\r
+  INTN                        Size;\r
+  INTN                        BestMatch;\r
+  UINTN                       HandleCount;\r
+  UINTN                       Index;\r
+  EFI_STATUS                  Status;\r
+  EFI_HANDLE                  *Handles;\r
+  EFI_HANDLE                  Handle;\r
+  EFI_DEVICE_PATH_PROTOCOL    *SourcePath;\r
+  EFI_DEVICE_PATH_PROTOCOL    *TmpDevicePath;\r
+  \r
+  if (Protocol == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  if ((DevicePath == NULL) || (*DevicePath == NULL)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  if (Device == NULL) {\r
+    return  EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  *Device = NULL_HANDLE;\r
+  SourcePath = *DevicePath;\r
+  SourceSize = CoreDevicePathSize (SourcePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);\r
+  \r
+  //\r
+  // The source path can only have 1 instance\r
+  //\r
+  if (CoreIsDevicePathMultiInstance (SourcePath)) {\r
+    DEBUG((EFI_D_ERROR, "LocateDevicePath: Device path has too many instances\n"));\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Get a list of all handles that support the requested protocol\r
+  //\r
+  Status = CoreLocateHandleBuffer (ByProtocol, Protocol, NULL, &HandleCount, &Handles);\r
+  if (EFI_ERROR (Status) || HandleCount == 0) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  BestMatch = -1;\r
+  for(Index = 0; Index < HandleCount; Index += 1) {\r
+    Handle = Handles[Index];\r
+    Status = CoreHandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&TmpDevicePath);\r
+    if (EFI_ERROR (Status)) {\r
+      //\r
+      // If this handle doesn't support device path, then skip it\r
+      //\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // Check if DevicePath is first part of SourcePath\r
+    //\r
+    Size = CoreDevicePathSize (TmpDevicePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);\r
+    if ((Size <= SourceSize) && CompareMem (SourcePath, TmpDevicePath, Size) == 0) {\r
+      //\r
+      // If the size is equal to the best match, then we\r
+      // have a duplice device path for 2 different device\r
+      // handles\r
+      //\r
+      ASSERT (Size != BestMatch);\r
+      \r
+      //\r
+      // We've got a match, see if it's the best match so far\r
+      //\r
+      if (Size > BestMatch) {\r
+        BestMatch = Size;\r
+        *Device = Handle;\r
+      }\r
+    }\r
+  }\r
+\r
+  CoreFreePool (Handles);\r
+   \r
+  //\r
+  // If there wasn't any match, then no parts of the device path was found.  \r
+  // Which is strange since there is likely a "root level" device path in the system.\r
+  //\r
+  if (BestMatch == -1) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // Return the remaining part of the device path\r
+  //\r
+  *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *) SourcePath) + BestMatch);\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateProtocol (\r
+  IN  EFI_GUID  *Protocol,\r
+  IN  VOID      *Registration OPTIONAL,\r
+  OUT VOID      **Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Return the first Protocol Interface that matches the Protocol GUID. If\r
+  Registration is pasased in return a Protocol Instance that was just add\r
+  to the system. If Retistration is NULL return the first Protocol Interface\r
+  you find.\r
+\r
+Arguments:\r
+\r
+  Protocol     - The protocol to search for\r
+  \r
+  Registration - Optional Registration Key returned from RegisterProtocolNotify() \r
+\r
+  Interface    - Return the Protocol interface (instance).\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS - If a valid Interface is returned\r
+  \r
+  EFI_INVALID_PARAMETER       - Invalid parameter\r
+  \r
+  EFI_NOT_FOUND               - Protocol interface not found\r
+\r
+--*/\r
+{\r
+  EFI_STATUS              Status;\r
+  LOCATE_POSITION         Position;\r
+  PROTOCOL_NOTIFY         *ProtNotify;\r
+  IHANDLE                 *Handle;\r
+\r
+  if (Interface == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  if (Protocol == NULL) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  \r
+  *Interface = NULL;\r
+  Status = EFI_SUCCESS;\r
+\r
+  //\r
+  // Set initial position\r
+  //\r
+  Position.Protocol  = Protocol;\r
+  Position.SearchKey = Registration;\r
+  Position.Position  = &gHandleList;\r
+  \r
+  //\r
+  // Lock the protocol database\r
+  //\r
+  CoreAcquireProtocolLock ();\r
+\r
+  mEfiLocateHandleRequest += 1;\r
+\r
+  if (NULL == Registration) {\r
+    //\r
+    // Look up the protocol entry and set the head pointer\r
+    //\r
+    Position.ProtEntry = CoreFindProtocolEntry (Protocol, FALSE);\r
+    if (Position.ProtEntry == NULL) {\r
+      Status = EFI_NOT_FOUND;\r
+      goto Done;\r
+    }\r
+    Position.Position = &Position.ProtEntry->Protocols;\r
+\r
+    Handle = CoreGetNextLocateByProtocol (&Position, Interface);\r
+  } else {\r
+    Handle = CoreGetNextLocateByRegisterNotify (&Position, Interface);   \r
+  }\r
+\r
+  if (NULL == Handle) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else if (NULL != Registration) {\r
+    //\r
+    // If this is a search by register notify and a handle was\r
+    // returned, update the register notification position\r
+    // \r
+    ProtNotify = Registration;\r
+    ProtNotify->Position = ProtNotify->Position->ForwardLink;\r
+  }\r
+\r
+Done:\r
+  CoreReleaseProtocolLock ();\r
+  return Status;\r
+}\r
+\r
+\r
\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLocateHandleBuffer (\r
+  IN EFI_LOCATE_SEARCH_TYPE       SearchType,\r
+  IN EFI_GUID                     *Protocol OPTIONAL,\r
+  IN VOID                         *SearchKey OPTIONAL,\r
+  IN OUT UINTN                    *NumberHandles,\r
+  OUT EFI_HANDLE                  **Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Function returns an array of handles that support the requested protocol \r
+  in a buffer allocated from pool. This is a version of CoreLocateHandle()\r
+  that allocates a buffer for the caller.\r
+\r
+Arguments:\r
+\r
+  SearchType           - Specifies which handle(s) are to be returned.\r
+  Protocol             - Provides the protocol to search by.   \r
+                         This parameter is only valid for SearchType ByProtocol.\r
+  SearchKey            - Supplies the search key depending on the SearchType.\r
+  NumberHandles      - The number of handles returned in Buffer.\r
+  Buffer               - A pointer to the buffer to return the requested array of \r
+                         handles that support Protocol.\r
+\r
+Returns:\r
+  \r
+  EFI_SUCCESS          - The result array of handles was returned.\r
+  EFI_NOT_FOUND        - No handles match the search. \r
+  EFI_OUT_OF_RESOURCES - There is not enough pool memory to store the matching results.\r
+  EFI_INVALID_PARAMETER   - Invalid parameter\r
+\r
+--*/\r
+{\r
+  EFI_STATUS          Status;\r
+  UINTN               BufferSize;\r
+\r
+  if (NumberHandles == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Buffer == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  BufferSize = 0;\r
+  *NumberHandles = 0;\r
+  *Buffer = NULL;\r
+  Status = CoreLocateHandle (\r
+             SearchType,\r
+             Protocol,\r
+             SearchKey,\r
+             &BufferSize,\r
+             *Buffer\r
+             );\r
+  //\r
+  // LocateHandleBuffer() returns incorrect status code if SearchType is\r
+  // invalid.\r
+  //\r
+  // Add code to correctly handle expected errors from CoreLocateHandle().\r
+  //\r
+  if (EFI_ERROR(Status) && Status != EFI_BUFFER_TOO_SMALL) {\r
+    if (Status != EFI_INVALID_PARAMETER) {\r
+      Status = EFI_NOT_FOUND;\r
+    }\r
+    return Status;\r
+  }\r
+\r
+  *Buffer = CoreAllocateBootServicesPool (BufferSize);\r
+  if (*Buffer == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  Status = CoreLocateHandle (\r
+             SearchType,\r
+             Protocol,\r
+             SearchKey,\r
+             &BufferSize,\r
+             *Buffer\r
+             );\r
+\r
+  *NumberHandles = BufferSize/sizeof(EFI_HANDLE);\r
+  if (EFI_ERROR(Status)) {\r
+    *NumberHandles = 0;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Image.h b/MdeModulePkg/Core/Dxe/Image.h
new file mode 100644 (file)
index 0000000..87214d3
--- /dev/null
@@ -0,0 +1,379 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  Image.h\r
+\r
+Abstract:\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+\r
+#ifndef _IMAGE_H_\r
+#define _IMAGE_H_\r
+\r
+\r
+\r
+#define LOADED_IMAGE_PRIVATE_DATA_SIGNATURE   EFI_SIGNATURE_32('l','d','r','i')\r
+\r
+typedef struct {\r
+    UINTN                       Signature;\r
+    EFI_HANDLE                  Handle;         // Image handle\r
+    UINTN                       Type;           // Image type\r
+\r
+    BOOLEAN                     Started;        // If entrypoint has been called\r
+\r
+    EFI_IMAGE_ENTRY_POINT       EntryPoint;     // The image's entry point\r
+    EFI_LOADED_IMAGE_PROTOCOL   Info;           // loaded image protocol\r
+\r
+    EFI_PHYSICAL_ADDRESS        ImageBasePage;  // Location in memory\r
+    UINTN                       NumberOfPages;  // Number of pages\r
+\r
+    CHAR8                       *FixupData;     // Original fixup data\r
+\r
+    EFI_TPL                     Tpl;            // Tpl of started image\r
+    EFI_STATUS                  Status;         // Status returned by started image\r
+\r
+    UINTN                       ExitDataSize;   // Size of ExitData from started image\r
+    VOID                        *ExitData;      // Pointer to exit data from started image\r
+    VOID                        *JumpBuffer;    // Pointer to pool allocation for context save/retore\r
+    BASE_LIBRARY_JUMP_BUFFER    *JumpContext;   // Pointer to buffer for context save/retore\r
+    UINT16                      Machine;        // Machine type from PE image\r
+\r
+    EFI_EBC_PROTOCOL            *Ebc;           // EBC Protocol pointer\r
+\r
+    EFI_RUNTIME_IMAGE_ENTRY     *RuntimeData;   // Runtime image list\r
+\r
+    PE_COFF_LOADER_IMAGE_CONTEXT  ImageContext; // PeCoffLoader ImageContext\r
+\r
+} LOADED_IMAGE_PRIVATE_DATA;\r
+\r
+#define LOADED_IMAGE_PRIVATE_DATA_FROM_THIS(a) \\r
+          CR(a, LOADED_IMAGE_PRIVATE_DATA, Info, LOADED_IMAGE_PRIVATE_DATA_SIGNATURE)\r
+\r
+\r
+\r
+#define LOAD_PE32_IMAGE_PRIVATE_DATA_SIGNATURE  EFI_SIGNATURE_32('l','p','e','i')\r
+\r
+typedef struct {\r
+    UINTN                       Signature;\r
+    EFI_HANDLE                  Handle;         // Image handle\r
+    EFI_PE32_IMAGE_PROTOCOL     Pe32Image;\r
+} LOAD_PE32_IMAGE_PRIVATE_DATA;\r
+\r
+#define LOAD_PE32_IMAGE_PRIVATE_DATA_FROM_THIS(a) \\r
+          CR(a, LOAD_PE32_IMAGE_PRIVATE_DATA, Pe32Image, LOAD_PE32_IMAGE_PRIVATE_DATA_SIGNATURE)\r
+\r
+\r
+\r
+//\r
+// Private Data Types\r
+//\r
+#define IMAGE_FILE_HANDLE_SIGNATURE       EFI_SIGNATURE_32('i','m','g','f')\r
+typedef struct {\r
+  UINTN               Signature;\r
+  BOOLEAN             FreeBuffer;\r
+  VOID                *Source;\r
+  UINTN               SourceSize;\r
+} IMAGE_FILE_HANDLE;\r
+\r
+\r
+//\r
+// Abstractions for reading image contents\r
+//\r
+\r
+EFI_STATUS\r
+CoreOpenImageFile (\r
+  IN BOOLEAN                        BootPolicy,\r
+  IN VOID                           *SourceBuffer   OPTIONAL,\r
+  IN UINTN                          SourceSize,\r
+  IN OUT EFI_DEVICE_PATH_PROTOCOL   *FilePath,\r
+  OUT EFI_HANDLE                    *DeviceHandle,\r
+  IN IMAGE_FILE_HANDLE              *ImageFileHandle,\r
+  OUT UINT32                        *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Opens a file for (simple) reading.  The simple read abstraction\r
+    will access the file either from a memory copy, from a file\r
+    system interface, or from the load file interface.\r
+\r
+Arguments:\r
+\r
+  BootPolicy    - Policy for Open Image File.\r
+  SourceBuffer  - Pointer to the memory location containing copy\r
+                  of the image to be loaded.\r
+  SourceSize    - The size in bytes of SourceBuffer.\r
+  FilePath      - The specific file path from which the image is loaded\r
+  DeviceHandle  - Pointer to the return device handle.\r
+  ImageFileHandle      - Pointer to the image file handle.\r
+  AuthenticationStatus - Pointer to a caller-allocated UINT32 in which the authentication status is returned.\r
+\r
+Returns:\r
+\r
+    A handle to access the file\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreReadImageFile (\r
+  IN     VOID     *UserHandle,\r
+  IN     UINTN    Offset,\r
+  IN OUT UINTN    *ReadSize,\r
+  OUT     VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Read image file (specified by UserHandle) into user specified buffer with specified offset\r
+  and length.\r
+\r
+Arguments:\r
+\r
+  UserHandle      - Image file handle\r
+\r
+  Offset          - Offset to the source file\r
+\r
+  ReadSize        - For input, pointer of size to read;\r
+                    For output, pointer of size actually read.\r
+\r
+  Buffer          - Buffer to write into\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS     - Successfully read the specified part of file into buffer.\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+EFIAPI\r
+CoreCloseImageFile (\r
+  IN IMAGE_FILE_HANDLE *ImageFileHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  A function out of date, should be removed.\r
+\r
+Arguments:\r
+\r
+  ImageFileHandle    - Handle of the file to close\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+//\r
+// Image processing worker functions\r
+//\r
+EFI_STATUS\r
+CoreDevicePathToInterface (\r
+  IN EFI_GUID                     *Protocol,\r
+  IN OUT EFI_DEVICE_PATH_PROTOCOL **FilePath,\r
+  OUT VOID                        **Interface,\r
+  OUT EFI_HANDLE                  *Handle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Search a handle to a device on a specified device path that supports a specified protocol,\r
+  interface of that protocol on that handle is another output.\r
+\r
+Arguments:\r
+\r
+  Protocol      - The protocol to search for\r
+\r
+  FilePath      - The specified device path\r
+\r
+  Interface     - Interface of the protocol on the handle\r
+\r
+  Handle        - The handle to the device on the specified device path that supports the protocol.\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreLoadPeImage (\r
+  IN  VOID                       *Pe32Handle,\r
+  IN  LOADED_IMAGE_PRIVATE_DATA  *Image,\r
+  IN  EFI_PHYSICAL_ADDRESS       DstBuffer   OPTIONAL,\r
+  OUT EFI_PHYSICAL_ADDRESS       *EntryPoint  OPTIONAL,\r
+  IN  UINT32                     Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads, relocates, and invokes a PE/COFF image\r
+\r
+Arguments:\r
+\r
+  Pe32Handle       - The handle of PE32 image\r
+  Image            - PE image to be loaded\r
+  DstBuffer        - The buffer to store the image\r
+  EntryPoint       - A pointer to the entry point\r
+  Attribute        - The bit mask of attributes to set for the load PE image\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The file was loaded, relocated, and invoked\r
+\r
+  EFI_OUT_OF_RESOURCES  - There was not enough memory to load and relocate the PE/COFF file\r
+\r
+  EFI_INVALID_PARAMETER - Invalid parameter\r
+\r
+  EFI_BUFFER_TOO_SMALL  - Buffer for image is too small\r
+\r
+--*/\r
+;\r
+\r
+LOADED_IMAGE_PRIVATE_DATA *\r
+CoreLoadedImageInfo (\r
+  IN EFI_HANDLE  ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  TODO: Add function description\r
+\r
+Arguments:\r
+\r
+  ImageHandle - TODO: add argument description\r
+\r
+Returns:\r
+\r
+  TODO: add return values\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreUnloadAndCloseImage (\r
+  IN LOADED_IMAGE_PRIVATE_DATA  *Image,\r
+  IN BOOLEAN                    FreePage\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unloads EFI image from memory.\r
+\r
+Arguments:\r
+\r
+  Image      - EFI image\r
+  FreePage   - Free allocated pages\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+//\r
+// Exported Image functions\r
+//\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLoadImageEx (\r
+  IN EFI_PE32_IMAGE_PROTOCOL           *This,\r
+  IN  EFI_HANDLE                       ParentImageHandle,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL         *FilePath,\r
+  IN  VOID                             *SourceBuffer       OPTIONAL,\r
+  IN  UINTN                            SourceSize,\r
+  IN  EFI_PHYSICAL_ADDRESS             DstBuffer           OPTIONAL,\r
+  OUT UINTN                            *NumberOfPages      OPTIONAL,\r
+  OUT EFI_HANDLE                       *ImageHandle,\r
+  OUT EFI_PHYSICAL_ADDRESS             *EntryPoint         OPTIONAL,\r
+  IN  UINT32                           Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads an EFI image into memory and returns a handle to the image with extended parameters.\r
+\r
+Arguments:\r
+\r
+  ParentImageHandle   - The caller's image handle.\r
+  FilePath            - The specific file path from which the image is loaded.\r
+  SourceBuffer        - If not NULL, a pointer to the memory location containing a copy of\r
+                        the image to be loaded.\r
+  SourceSize          - The size in bytes of SourceBuffer.\r
+  DstBuffer           - The buffer to store the image.\r
+  NumberOfPages       - For input, specifies the space size of the image by caller if not NULL.\r
+                        For output, specifies the actual space size needed.\r
+  ImageHandle         - Image handle for output.\r
+  EntryPoint          - Image entry point for output.\r
+  Attribute           - The bit mask of attributes to set for the load PE image.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - The image was loaded into memory.\r
+  EFI_NOT_FOUND          - The FilePath was not found.\r
+  EFI_INVALID_PARAMETER  - One of the parameters has an invalid value.\r
+  EFI_UNSUPPORTED        - The image type is not supported, or the device path cannot be\r
+                           parsed to locate the proper protocol for loading the file.\r
+  EFI_OUT_OF_RESOURCES   - Image was not loaded due to insufficient resources.\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUnloadImageEx (\r
+  IN EFI_PE32_IMAGE_PROTOCOL            *This,\r
+  IN EFI_HANDLE                         ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unload the specified image.\r
+\r
+Arguments:\r
+\r
+  This              - Indicates the calling context.\r
+\r
+  ImageHandle       - The specified image handle.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Image handle is NULL.\r
+\r
+  EFI_UNSUPPORTED             - Attempt to unload an unsupported image.\r
+\r
+  EFI_SUCCESS                 - Image successfully unloaded.\r
+\r
+--*/\r
+;\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/Image/Image.c b/MdeModulePkg/Core/Dxe/Image/Image.c
new file mode 100644 (file)
index 0000000..daf5fd1
--- /dev/null
@@ -0,0 +1,1390 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  Image.c\r
+\r
+Abstract:\r
+\r
+  Core image handling services\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+//\r
+// Module Globals\r
+//\r
+\r
+LOADED_IMAGE_PRIVATE_DATA  *mCurrentImage = NULL;\r
+\r
+LOAD_PE32_IMAGE_PRIVATE_DATA  mLoadPe32PrivateData = {\r
+  LOAD_PE32_IMAGE_PRIVATE_DATA_SIGNATURE,\r
+  NULL,\r
+  {\r
+    CoreLoadImageEx,\r
+    CoreUnloadImageEx\r
+  }\r
+};\r
+\r
+\r
+//\r
+// This code is needed to build the Image handle for the DXE Core\r
+//\r
+LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage  = {\r
+  LOADED_IMAGE_PRIVATE_DATA_SIGNATURE,            // Signature\r
+  NULL,                                           // Image handle\r
+  EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER,    // Image type\r
+  TRUE,                                           // If entrypoint has been called\r
+  NULL, // EntryPoint\r
+  {\r
+    EFI_LOADED_IMAGE_INFORMATION_REVISION,        // Revision\r
+    NULL,                                         // Parent handle\r
+    NULL,                                         // System handle\r
+\r
+    NULL,                                         // Device handle\r
+    NULL,                                         // File path\r
+    NULL,                                         // Reserved\r
+\r
+    0,                                            // LoadOptionsSize\r
+    NULL,                                         // LoadOptions\r
+\r
+    NULL,                                         // ImageBase\r
+    0,                                            // ImageSize\r
+    EfiBootServicesCode,                          // ImageCodeType\r
+    EfiBootServicesData                           // ImageDataType\r
+  },\r
+  (EFI_PHYSICAL_ADDRESS)0,    // ImageBasePage\r
+  0,                          // NumberOfPages\r
+  NULL,                       // FixupData\r
+  0,                          // Tpl\r
+  EFI_SUCCESS,                // Status\r
+  0,                          // ExitDataSize\r
+  NULL,                       // ExitData\r
+  NULL,                       // JumpBuffer\r
+  NULL,                       // JumpContext\r
+  0,                          // Machine\r
+  NULL,                       // Ebc\r
+  NULL,                       // RuntimeData\r
+};\r
+\r
+\r
+EFI_STATUS\r
+CoreInitializeImageServices (\r
+  IN  VOID *HobStart\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Add the Image Services to EFI Boot Services Table and install the protocol\r
+  interfaces for this image.\r
+\r
+Arguments:\r
+\r
+  HobStart        - The HOB to initialize\r
+\r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                        Status;\r
+  LOADED_IMAGE_PRIVATE_DATA         *Image;\r
+  EFI_PHYSICAL_ADDRESS              DxeCoreImageBaseAddress;\r
+  UINT64                            DxeCoreImageLength;\r
+  VOID                              *DxeCoreEntryPoint;\r
+  EFI_PEI_HOB_POINTERS              DxeCoreHob;\r
+  //\r
+  // Searching for image hob\r
+  //\r
+  DxeCoreHob.Raw          = HobStart;\r
+  while ((DxeCoreHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, DxeCoreHob.Raw)) != NULL) {\r
+    if (CompareGuid (&DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.Name, &gEfiHobMemoryAllocModuleGuid)) {\r
+      //\r
+      // Find Dxe Core HOB\r
+      //\r
+      break;\r
+    }\r
+    DxeCoreHob.Raw = GET_NEXT_HOB (DxeCoreHob);\r
+  }\r
+  ASSERT (DxeCoreHob.Raw != NULL);\r
+\r
+  DxeCoreImageBaseAddress = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress;\r
+  DxeCoreImageLength      = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength;\r
+  DxeCoreEntryPoint       = (VOID *) (UINTN) DxeCoreHob.MemoryAllocationModule->EntryPoint;\r
+  gDxeCoreFileName        = &DxeCoreHob.MemoryAllocationModule->ModuleName;\r
+  //\r
+  // Initialize the fields for an internal driver\r
+  //\r
+  Image = &mCorePrivateImage;\r
+\r
+  Image->EntryPoint         = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint;\r
+  Image->ImageBasePage      = DxeCoreImageBaseAddress;\r
+  Image->NumberOfPages      = (UINTN)(EFI_SIZE_TO_PAGES((UINTN)(DxeCoreImageLength)));\r
+  Image->Tpl                = gEfiCurrentTpl;\r
+  Image->Info.SystemTable   = gDxeCoreST;\r
+  Image->Info.ImageBase     = (VOID *)(UINTN)DxeCoreImageBaseAddress;\r
+  Image->Info.ImageSize     = DxeCoreImageLength;\r
+\r
+  //\r
+  // Install the protocol interfaces for this image\r
+  //\r
+  Status = CoreInstallProtocolInterface (\r
+             &Image->Handle,\r
+             &gEfiLoadedImageProtocolGuid,\r
+             EFI_NATIVE_INTERFACE,\r
+             &Image->Info\r
+             );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  mCurrentImage = Image;\r
+\r
+  //\r
+  // Fill in DXE globals\r
+  //\r
+  gDxeCoreImageHandle = Image->Handle;\r
+  gDxeCoreLoadedImage = &Image->Info;\r
+\r
+  //\r
+  // Export DXE Core PE Loader functionality\r
+  //\r
+  return CoreInstallProtocolInterface (\r
+           &mLoadPe32PrivateData.Handle,\r
+           &gEfiLoadPeImageProtocolGuid,\r
+           EFI_NATIVE_INTERFACE,\r
+           &mLoadPe32PrivateData.Pe32Image\r
+           );\r
+}\r
+\r
+EFI_STATUS\r
+CoreLoadPeImage (\r
+  IN VOID                        *Pe32Handle,\r
+  IN LOADED_IMAGE_PRIVATE_DATA   *Image,\r
+  IN EFI_PHYSICAL_ADDRESS        DstBuffer    OPTIONAL,\r
+  OUT EFI_PHYSICAL_ADDRESS       *EntryPoint  OPTIONAL,\r
+  IN  UINT32                     Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads, relocates, and invokes a PE/COFF image\r
+\r
+Arguments:\r
+\r
+  Pe32Handle       - The handle of PE32 image\r
+  Image            - PE image to be loaded\r
+  DstBuffer        - The buffer to store the image\r
+  EntryPoint       - A pointer to the entry point\r
+  Attribute        - The bit mask of attributes to set for the load PE image\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS          - The file was loaded, relocated, and invoked\r
+\r
+  EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file\r
+\r
+  EFI_INVALID_PARAMETER - Invalid parameter\r
+\r
+  EFI_BUFFER_TOO_SMALL  - Buffer for image is too small\r
+\r
+--*/\r
+{\r
+  EFI_STATUS      Status;\r
+  BOOLEAN         DstBufAlocated;\r
+  UINTN           Size;\r
+\r
+  ZeroMem (&Image->ImageContext, sizeof (Image->ImageContext));\r
+\r
+  Image->ImageContext.Handle    = Pe32Handle;\r
+  Image->ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)CoreReadImageFile;\r
+\r
+  //\r
+  // Get information about the image being loaded\r
+  //\r
+  Status = gEfiPeiPeCoffLoader->GetImageInfo (gEfiPeiPeCoffLoader, &Image->ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->ImageContext.Machine)) {\r
+    //\r
+    // The PE/COFF loader can support loading image types that can be executed.\r
+    // If we loaded an image type that we can not execute return EFI_UNSUPORTED.\r
+    //\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+\r
+  //\r
+  // Allocate memory of the correct memory type aligned on the required image boundry\r
+  //\r
+  DstBufAlocated = FALSE;\r
+  if (DstBuffer == 0) {\r
+    //\r
+    // Allocate Destination Buffer as caller did not pass it in\r
+    //\r
+\r
+    if (Image->ImageContext.SectionAlignment > EFI_PAGE_SIZE) {\r
+      Size = (UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment;\r
+    } else {\r
+      Size = (UINTN)Image->ImageContext.ImageSize;\r
+    }\r
+\r
+    Image->NumberOfPages = EFI_SIZE_TO_PAGES (Size);\r
+\r
+    //\r
+    // If the image relocations have not been stripped, then load at any address.\r
+    // Otherwise load at the address at which it was linked.\r
+    //\r
+    // Memory below 1MB should be treated reserved for CSM and there should be\r
+    // no modules whose preferred load addresses are below 1MB.\r
+    //\r
+    Status = EFI_OUT_OF_RESOURCES;\r
+    if (Image->ImageContext.ImageAddress >= 0x100000 || Image->ImageContext.RelocationsStripped) {\r
+      Status = CoreAllocatePages (\r
+                 AllocateAddress,\r
+                 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),\r
+                 Image->NumberOfPages,\r
+                 &Image->ImageContext.ImageAddress\r
+                 );\r
+    }\r
+    if (EFI_ERROR (Status) && !Image->ImageContext.RelocationsStripped) {\r
+      Status = CoreAllocatePages (\r
+                 AllocateAnyPages,\r
+                 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),\r
+                 Image->NumberOfPages,\r
+                 &Image->ImageContext.ImageAddress\r
+                 );\r
+    }\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+    DstBufAlocated = TRUE;\r
+  } else {\r
+    //\r
+    // Caller provided the destination buffer\r
+    //\r
+\r
+    if (Image->ImageContext.RelocationsStripped && (Image->ImageContext.ImageAddress != DstBuffer)) {\r
+      //\r
+      // If the image relocations were stripped, and the caller provided a\r
+      // destination buffer address that does not match the address that the\r
+      // image is linked at, then the image cannot be loaded.\r
+      //\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+\r
+    if (Image->NumberOfPages != 0 &&\r
+        Image->NumberOfPages <\r
+        (EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment))) {\r
+      Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);\r
+      return EFI_BUFFER_TOO_SMALL;\r
+    }\r
+\r
+    Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);\r
+    Image->ImageContext.ImageAddress = DstBuffer;\r
+  }\r
+\r
+  Image->ImageBasePage = Image->ImageContext.ImageAddress;\r
+  Image->ImageContext.ImageAddress =\r
+      (Image->ImageContext.ImageAddress + Image->ImageContext.SectionAlignment - 1) &\r
+      ~((UINTN)Image->ImageContext.SectionAlignment - 1);\r
+\r
+  //\r
+  // Load the image from the file into the allocated memory\r
+  //\r
+  Status = gEfiPeiPeCoffLoader->LoadImage (gEfiPeiPeCoffLoader, &Image->ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // If this is a Runtime Driver, then allocate memory for the FixupData that\r
+  // is used to relocate the image when SetVirtualAddressMap() is called. The\r
+  // relocation is done by the Runtime AP.\r
+  //\r
+  if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) {\r
+    if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {\r
+      Image->ImageContext.FixupData = CoreAllocateRuntimePool ((UINTN)(Image->ImageContext.FixupDataSize));\r
+      if (Image->ImageContext.FixupData == NULL) {\r
+        Status = EFI_OUT_OF_RESOURCES;\r
+        goto Done;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Relocate the image in memory\r
+  //\r
+  Status = gEfiPeiPeCoffLoader->RelocateImage (gEfiPeiPeCoffLoader, &Image->ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Flush the Instruction Cache\r
+  //\r
+  InvalidateInstructionCacheRange ((VOID *)(UINTN)Image->ImageContext.ImageAddress, (UINTN)Image->ImageContext.ImageSize);\r
+\r
+  //\r
+  // Copy the machine type from the context to the image private data. This\r
+  // is needed during image unload to know if we should call an EBC protocol\r
+  // to unload the image.\r
+  //\r
+  Image->Machine = Image->ImageContext.Machine;\r
+\r
+  //\r
+  // Get the image entry point. If it's an EBC image, then call into the\r
+  // interpreter to create a thunk for the entry point and use the returned\r
+  // value for the entry point.\r
+  //\r
+  Image->EntryPoint   = (EFI_IMAGE_ENTRY_POINT)(UINTN)Image->ImageContext.EntryPoint;\r
+  if (Image->ImageContext.Machine == EFI_IMAGE_MACHINE_EBC) {\r
+    //\r
+    // Locate the EBC interpreter protocol\r
+    //\r
+    Status = CoreLocateProtocol (&gEfiEbcProtocolGuid, NULL, (VOID **)&Image->Ebc);\r
+    if (EFI_ERROR(Status)) {\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Register a callback for flushing the instruction cache so that created\r
+    // thunks can be flushed.\r
+    //\r
+    Status = Image->Ebc->RegisterICacheFlush (Image->Ebc, (EBC_ICACHE_FLUSH)InvalidateInstructionCacheRange);\r
+    if (EFI_ERROR(Status)) {\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Create a thunk for the image's entry point. This will be the new\r
+    // entry point for the image.\r
+    //\r
+    Status = Image->Ebc->CreateThunk (\r
+                           Image->Ebc,\r
+                           Image->Handle,\r
+                           (VOID *)(UINTN)Image->ImageContext.EntryPoint,\r
+                           (VOID **)&Image->EntryPoint\r
+                           );\r
+    if (EFI_ERROR(Status)) {\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Fill in the image information for the Loaded Image Protocol\r
+  //\r
+  Image->Type               = Image->ImageContext.ImageType;\r
+  Image->Info.ImageBase     = (VOID *)(UINTN)Image->ImageContext.ImageAddress;\r
+  Image->Info.ImageSize     = Image->ImageContext.ImageSize;\r
+  Image->Info.ImageCodeType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType);\r
+  Image->Info.ImageDataType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageDataMemoryType);\r
+  if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) {\r
+    if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {\r
+      //\r
+      // Make a list off all the RT images so we can let the RT AP know about them.\r
+      //\r
+      Image->RuntimeData = CoreAllocateRuntimePool (sizeof(EFI_RUNTIME_IMAGE_ENTRY));\r
+      if (Image->RuntimeData == NULL) {\r
+        goto Done;\r
+      }\r
+      Image->RuntimeData->ImageBase      = Image->Info.ImageBase;\r
+      Image->RuntimeData->ImageSize      = (UINT64) (Image->Info.ImageSize);\r
+      Image->RuntimeData->RelocationData = Image->ImageContext.FixupData;\r
+      Image->RuntimeData->Handle         = Image->Handle;\r
+      InsertTailList (&gRuntime->ImageHead, &Image->RuntimeData->Link);\r
+    }\r
+  }\r
+\r
+  //\r
+  // Fill in the entry point of the image if it is available\r
+  //\r
+  if (EntryPoint != NULL) {\r
+    *EntryPoint = Image->ImageContext.EntryPoint;\r
+  }\r
+\r
+  //\r
+  // Print the load address and the PDB file name if it is available\r
+  //\r
+\r
+  DEBUG_CODE_BEGIN ();\r
+\r
+    UINTN Index;\r
+    UINTN StartIndex;\r
+    CHAR8 EfiFileName[256];\r
+\r
+    DEBUG ((EFI_D_INFO | EFI_D_LOAD, "Loading driver at 0x%10p EntryPoint=0x%10p ", (VOID *)(UINTN)Image->ImageContext.ImageAddress, (VOID *)(UINTN)Image->ImageContext.EntryPoint));\r
+    if (Image->ImageContext.PdbPointer != NULL) {\r
+      StartIndex = 0;\r
+      for (Index = 0; Image->ImageContext.PdbPointer[Index] != 0; Index++) {\r
+        if (Image->ImageContext.PdbPointer[Index] == '\\') {\r
+          StartIndex = Index + 1;\r
+        }\r
+      }\r
+      //\r
+      // Copy the PDB file name to our temporary string, and replace .pdb with .efi\r
+      //\r
+      for (Index = 0; Index < sizeof (EfiFileName); Index++) {\r
+        EfiFileName[Index] = Image->ImageContext.PdbPointer[Index + StartIndex];\r
+        if (EfiFileName[Index] == 0) {\r
+          EfiFileName[Index] = '.';\r
+        }\r
+        if (EfiFileName[Index] == '.') {\r
+          EfiFileName[Index + 1] = 'e';\r
+          EfiFileName[Index + 2] = 'f';\r
+          EfiFileName[Index + 3] = 'i';\r
+          EfiFileName[Index + 4] = 0;\r
+          break;\r
+        }\r
+      }\r
+      DEBUG ((EFI_D_INFO | EFI_D_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex]));\r
+    }\r
+    DEBUG ((EFI_D_INFO | EFI_D_LOAD, "\n"));\r
+\r
+  DEBUG_CODE_END ();\r
+\r
+  return EFI_SUCCESS;\r
+\r
+Done:\r
+\r
+  //\r
+  // Free memory.\r
+  //\r
+\r
+  if (DstBufAlocated) {\r
+    CoreFreePages (Image->ImageContext.ImageAddress, Image->NumberOfPages);\r
+  }\r
+\r
+  if (Image->ImageContext.FixupData != NULL) {\r
+    CoreFreePool (Image->ImageContext.FixupData);\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+LOADED_IMAGE_PRIVATE_DATA *\r
+CoreLoadedImageInfo (\r
+  IN EFI_HANDLE  ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Get the image's private data from its handle.\r
+\r
+Arguments:\r
+\r
+  ImageHandle     - The image handle\r
+\r
+Returns:\r
+\r
+  Return the image private data associated with ImageHandle.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                 Status;\r
+  EFI_LOADED_IMAGE_PROTOCOL  *LoadedImage;\r
+  LOADED_IMAGE_PRIVATE_DATA  *Image;\r
+\r
+  Status = CoreHandleProtocol (\r
+             ImageHandle,\r
+             &gEfiLoadedImageProtocolGuid,\r
+             (VOID **)&LoadedImage\r
+             );\r
+  if (!EFI_ERROR (Status)) {\r
+    Image = LOADED_IMAGE_PRIVATE_DATA_FROM_THIS (LoadedImage);\r
+  } else {\r
+    DEBUG ((EFI_D_LOAD, "CoreLoadedImageInfo: Not an ImageHandle %x\n", ImageHandle));\r
+    Image = NULL;\r
+  }\r
+\r
+  return Image;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreLoadImageCommon (\r
+  IN  BOOLEAN                          BootPolicy,\r
+  IN  EFI_HANDLE                       ParentImageHandle,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL         *FilePath,\r
+  IN  VOID                             *SourceBuffer       OPTIONAL,\r
+  IN  UINTN                            SourceSize,\r
+  IN  EFI_PHYSICAL_ADDRESS             DstBuffer           OPTIONAL,\r
+  IN OUT UINTN                         *NumberOfPages      OPTIONAL,\r
+  OUT EFI_HANDLE                       *ImageHandle,\r
+  OUT EFI_PHYSICAL_ADDRESS             *EntryPoint         OPTIONAL,\r
+  IN  UINT32                           Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads an EFI image into memory and returns a handle to the image.\r
+\r
+Arguments:\r
+\r
+  BootPolicy          - If TRUE, indicates that the request originates from the boot manager,\r
+                        and that the boot manager is attempting to load FilePath as a boot selection.\r
+  ParentImageHandle   - The caller's image handle.\r
+  FilePath            - The specific file path from which the image is loaded.\r
+  SourceBuffer        - If not NULL, a pointer to the memory location containing a copy of\r
+                        the image to be loaded.\r
+  SourceSize          - The size in bytes of SourceBuffer.\r
+  DstBuffer           - The buffer to store the image\r
+  NumberOfPages       - If not NULL, a pointer to the image's page number, if this number\r
+                        is not enough, return EFI_BUFFER_TOO_SMALL and this parameter contain\r
+                        the required number.\r
+  ImageHandle         - Pointer to the returned image handle that is created when the image\r
+                        is successfully loaded.\r
+  EntryPoint          - A pointer to the entry point\r
+  Attribute           - The bit mask of attributes to set for the load PE image\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - The image was loaded into memory.\r
+  EFI_NOT_FOUND          - The FilePath was not found.\r
+  EFI_INVALID_PARAMETER  - One of the parameters has an invalid value.\r
+  EFI_BUFFER_TOO_SMALL   - The buffer is too small\r
+  EFI_UNSUPPORTED        - The image type is not supported, or the device path cannot be\r
+                           parsed to locate the proper protocol for loading the file.\r
+  EFI_OUT_OF_RESOURCES   - Image was not loaded due to insufficient resources.\r
+--*/\r
+{\r
+  LOADED_IMAGE_PRIVATE_DATA  *Image;\r
+  LOADED_IMAGE_PRIVATE_DATA  *ParentImage;\r
+  IMAGE_FILE_HANDLE          FHand;\r
+  EFI_STATUS                 Status;\r
+  EFI_STATUS                 SecurityStatus;\r
+  EFI_HANDLE                 DeviceHandle;\r
+  UINT32                     AuthenticationStatus;\r
+  EFI_DEVICE_PATH_PROTOCOL   *OriginalFilePath;\r
+  EFI_DEVICE_PATH_PROTOCOL   *HandleFilePath;\r
+  UINTN                      FilePathSize;\r
+\r
+  SecurityStatus = EFI_SUCCESS;\r
+\r
+  ASSERT (gEfiCurrentTpl < TPL_NOTIFY);\r
+  ParentImage = NULL;\r
+\r
+  //\r
+  // The caller must pass in a valid ParentImageHandle\r
+  //\r
+  if (ImageHandle == NULL || ParentImageHandle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  ParentImage = CoreLoadedImageInfo (ParentImageHandle);\r
+  if (ParentImage == NULL) {\r
+    DEBUG((EFI_D_LOAD|EFI_D_ERROR, "LoadImageEx: Parent handle not an image handle\n"));\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Get simple read access to the source file\r
+  //\r
+  OriginalFilePath = FilePath;\r
+  Status = CoreOpenImageFile (\r
+             BootPolicy,\r
+             SourceBuffer,\r
+             SourceSize,\r
+             FilePath,\r
+             &DeviceHandle,\r
+             &FHand,\r
+             &AuthenticationStatus\r
+             );\r
+  if (Status == EFI_ALREADY_STARTED) {\r
+    Image = NULL;\r
+    goto Done;\r
+  } else if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Verify the Authentication Status through the Security Architectural Protocol\r
+  //\r
+  if ((gSecurity != NULL) && (OriginalFilePath != NULL)) {\r
+    SecurityStatus = gSecurity->FileAuthenticationState (\r
+                                  gSecurity,\r
+                                  AuthenticationStatus,\r
+                                  OriginalFilePath\r
+                                  );\r
+    if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {\r
+      Status = SecurityStatus;\r
+      Image = NULL;\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+\r
+  //\r
+  // Allocate a new image structure\r
+  //\r
+  Image = CoreAllocateZeroBootServicesPool (sizeof(LOADED_IMAGE_PRIVATE_DATA));\r
+  if (Image == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Pull out just the file portion of the DevicePath for the LoadedImage FilePath\r
+  //\r
+  Status = CoreHandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);\r
+  if (!EFI_ERROR (Status)) {\r
+    FilePathSize = CoreDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);\r
+    FilePath = (EFI_DEVICE_PATH_PROTOCOL *) ( ((UINT8 *)FilePath) + FilePathSize );\r
+  }\r
+\r
+  //\r
+  // Initialize the fields for an internal driver\r
+  //\r
+  Image->Signature         = LOADED_IMAGE_PRIVATE_DATA_SIGNATURE;\r
+  Image->Info.SystemTable  = gDxeCoreST;\r
+  Image->Info.DeviceHandle = DeviceHandle;\r
+  Image->Info.Revision     = EFI_LOADED_IMAGE_INFORMATION_REVISION;\r
+  Image->Info.FilePath     = CoreDuplicateDevicePath (FilePath);\r
+  Image->Info.ParentHandle = ParentImageHandle;\r
+\r
+  if (NumberOfPages != NULL) {\r
+    Image->NumberOfPages = *NumberOfPages ;\r
+  } else {\r
+    Image->NumberOfPages = 0 ;\r
+  }\r
+\r
+  //\r
+  // Install the protocol interfaces for this image\r
+  // don't fire notifications yet\r
+  //\r
+  Status = CoreInstallProtocolInterfaceNotify (\r
+             &Image->Handle,\r
+             &gEfiLoadedImageProtocolGuid,\r
+             EFI_NATIVE_INTERFACE,\r
+             &Image->Info,\r
+             FALSE\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Load the image.  If EntryPoint is Null, it will not be set.\r
+  //\r
+  Status = CoreLoadPeImage (&FHand, Image, DstBuffer, EntryPoint, Attribute);\r
+  if (EFI_ERROR (Status)) {\r
+    if ((Status == EFI_BUFFER_TOO_SMALL) || (Status == EFI_OUT_OF_RESOURCES)) {\r
+      if (NumberOfPages != NULL) {\r
+        *NumberOfPages = Image->NumberOfPages;\r
+      }\r
+    }\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Register the image in the Debug Image Info Table if the attribute is set\r
+  //\r
+  if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION) {\r
+    CoreNewDebugImageInfoEntry (EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, &Image->Info, Image->Handle);\r
+  }\r
+\r
+  //\r
+  //Reinstall loaded image protocol to fire any notifications\r
+  //\r
+  Status = CoreReinstallProtocolInterface (\r
+             Image->Handle,\r
+             &gEfiLoadedImageProtocolGuid,\r
+             &Image->Info,\r
+             &Image->Info\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+\r
+  //\r
+  // Success.  Return the image handle\r
+  //\r
+  *ImageHandle = Image->Handle;\r
+\r
+Done:\r
+  //\r
+  // All done accessing the source file\r
+  // If we allocated the Source buffer, free it\r
+  //\r
+  if (FHand.FreeBuffer) {\r
+    CoreFreePool (FHand.Source);\r
+  }\r
+\r
+  //\r
+  // There was an error.  If there's an Image structure, free it\r
+  //\r
+  if (EFI_ERROR (Status)) {\r
+    if (Image != NULL) {\r
+      CoreUnloadAndCloseImage (Image, (BOOLEAN)(DstBuffer == 0));\r
+      *ImageHandle = NULL;\r
+    }\r
+  } else if (EFI_ERROR (SecurityStatus)) {\r
+    Status = SecurityStatus;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLoadImage (\r
+  IN BOOLEAN                    BootPolicy,\r
+  IN EFI_HANDLE                 ParentImageHandle,\r
+  IN EFI_DEVICE_PATH_PROTOCOL   *FilePath,\r
+  IN VOID                       *SourceBuffer   OPTIONAL,\r
+  IN UINTN                      SourceSize,\r
+  OUT EFI_HANDLE                *ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads an EFI image into memory and returns a handle to the image.\r
+\r
+Arguments:\r
+\r
+  BootPolicy          - If TRUE, indicates that the request originates from the boot manager,\r
+                        and that the boot manager is attempting to load FilePath as a boot selection.\r
+  ParentImageHandle   - The caller's image handle.\r
+  FilePath            - The specific file path from which the image is loaded.\r
+  SourceBuffer        - If not NULL, a pointer to the memory location containing a copy of\r
+                        the image to be loaded.\r
+  SourceSize          - The size in bytes of SourceBuffer.\r
+  ImageHandle         - Pointer to the returned image handle that is created when the image\r
+                        is successfully loaded.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - The image was loaded into memory.\r
+  EFI_NOT_FOUND          - The FilePath was not found.\r
+  EFI_INVALID_PARAMETER  - One of the parameters has an invalid value.\r
+  EFI_UNSUPPORTED        - The image type is not supported, or the device path cannot be\r
+                           parsed to locate the proper protocol for loading the file.\r
+  EFI_OUT_OF_RESOURCES   - Image was not loaded due to insufficient resources.\r
+--*/\r
+{\r
+  EFI_STATUS    Status;\r
+\r
+  PERF_START (NULL, "LoadImage", NULL, 0);\r
+\r
+  Status = CoreLoadImageCommon (\r
+             BootPolicy,\r
+             ParentImageHandle,\r
+             FilePath,\r
+             SourceBuffer,\r
+             SourceSize,\r
+             (EFI_PHYSICAL_ADDRESS)NULL,\r
+             NULL,\r
+             ImageHandle,\r
+             NULL,\r
+             EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION | EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION\r
+             );\r
+\r
+  PERF_END (NULL, "LoadImage", NULL, 0);\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreLoadImageEx (\r
+  IN  EFI_PE32_IMAGE_PROTOCOL          *This,\r
+  IN  EFI_HANDLE                       ParentImageHandle,\r
+  IN  EFI_DEVICE_PATH_PROTOCOL         *FilePath,\r
+  IN  VOID                             *SourceBuffer       OPTIONAL,\r
+  IN  UINTN                            SourceSize,\r
+  IN  EFI_PHYSICAL_ADDRESS             DstBuffer           OPTIONAL,\r
+  OUT UINTN                            *NumberOfPages      OPTIONAL,\r
+  OUT EFI_HANDLE                       *ImageHandle,\r
+  OUT EFI_PHYSICAL_ADDRESS             *EntryPoint         OPTIONAL,\r
+  IN  UINT32                           Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Loads an EFI image into memory and returns a handle to the image with extended parameters.\r
+\r
+Arguments:\r
+\r
+  This                - Calling context\r
+  ParentImageHandle   - The caller's image handle.\r
+  FilePath            - The specific file path from which the image is loaded.\r
+  SourceBuffer        - If not NULL, a pointer to the memory location containing a copy of\r
+                        the image to be loaded.\r
+  SourceSize          - The size in bytes of SourceBuffer.\r
+  DstBuffer           - The buffer to store the image.\r
+  NumberOfPages       - For input, specifies the space size of the image by caller if not NULL.\r
+                        For output, specifies the actual space size needed.\r
+  ImageHandle         - Image handle for output.\r
+  EntryPoint          - Image entry point for output.\r
+  Attribute           - The bit mask of attributes to set for the load PE image.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - The image was loaded into memory.\r
+  EFI_NOT_FOUND          - The FilePath was not found.\r
+  EFI_INVALID_PARAMETER  - One of the parameters has an invalid value.\r
+  EFI_UNSUPPORTED        - The image type is not supported, or the device path cannot be\r
+                           parsed to locate the proper protocol for loading the file.\r
+  EFI_OUT_OF_RESOURCES   - Image was not loaded due to insufficient resources.\r
+--*/\r
+{\r
+  return CoreLoadImageCommon (\r
+           TRUE,\r
+           ParentImageHandle,\r
+           FilePath,\r
+           SourceBuffer,\r
+           SourceSize,\r
+           DstBuffer,\r
+           NumberOfPages,\r
+           ImageHandle,\r
+           EntryPoint,\r
+           Attribute\r
+           );\r
+}\r
+\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreStartImage (\r
+  IN EFI_HANDLE  ImageHandle,\r
+  OUT UINTN      *ExitDataSize,\r
+  OUT CHAR16     **ExitData  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Transfer control to a loaded image's entry point.\r
+\r
+Arguments:\r
+\r
+  ImageHandle     - Handle of image to be started.\r
+\r
+  ExitDataSize    - Pointer of the size to ExitData\r
+\r
+  ExitData        - Pointer to a pointer to a data buffer that includes a Null-terminated\r
+                    Unicode string, optionally followed by additional binary data. The string\r
+                    is a description that the caller may use to further indicate the reason for\r
+                    the image's exit.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Invalid parameter\r
+\r
+  EFI_OUT_OF_RESOURCES       - No enough buffer to allocate\r
+\r
+  EFI_SUCCESS               - Successfully transfer control to the image's entry point.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                    Status;\r
+  LOADED_IMAGE_PRIVATE_DATA     *Image;\r
+  LOADED_IMAGE_PRIVATE_DATA     *LastImage;\r
+  UINT64                        HandleDatabaseKey;\r
+  UINTN                         SetJumpFlag;\r
+\r
+  Image = CoreLoadedImageInfo (ImageHandle);\r
+  if (Image == NULL_HANDLE  ||  Image->Started) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Don't profile Objects or invalid start requests\r
+  //\r
+  PERF_START (ImageHandle, START_IMAGE_TOK, NULL, 0);\r
+\r
+\r
+  //\r
+  // Push the current start image context, and\r
+  // link the current image to the head.   This is the\r
+  // only image that can call Exit()\r
+  //\r
+  HandleDatabaseKey = CoreGetHandleDatabaseKey ();\r
+  LastImage         = mCurrentImage;\r
+  mCurrentImage     = Image;\r
+  Image->Tpl        = gEfiCurrentTpl;\r
+\r
+  //\r
+  // Set long jump for Exit() support\r
+  // JumpContext must be aligned on a CPU specific boundary.\r
+  // Overallocate the buffer and force the required alignment\r
+  //\r
+  Image->JumpBuffer = CoreAllocateBootServicesPool (sizeof (BASE_LIBRARY_JUMP_BUFFER) + BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);\r
+  if (Image->JumpBuffer == NULL) {\r
+    PERF_END (ImageHandle, START_IMAGE_TOK, NULL, 0);\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+  Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);\r
+\r
+  SetJumpFlag = SetJump (Image->JumpContext);\r
+  //\r
+  // The initial call to SetJump() must always return 0.\r
+  // Subsequent calls to LongJump() cause a non-zero value to be returned by SetJump().\r
+  //\r
+  if (!SetJumpFlag) {\r
+    //\r
+    // Call the image's entry point\r
+    //\r
+    Image->Started = TRUE;\r
+    Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable);\r
+\r
+    //\r
+    // Add some debug information if the image returned with error.\r
+    // This make the user aware and check if the driver image have already released\r
+    // all the resource in this situation.\r
+    //\r
+    DEBUG_CODE_BEGIN ();\r
+      if (EFI_ERROR (Image->Status)) {\r
+        DEBUG ((EFI_D_ERROR, "Error: Image at %10p start failed: %r\n", Image->Info.ImageBase, Image->Status));\r
+      }\r
+    DEBUG_CODE_END ();\r
+\r
+    //\r
+    // If the image returns, exit it through Exit()\r
+    //\r
+    CoreExit (ImageHandle, Image->Status, 0, NULL);\r
+  }\r
+\r
+  //\r
+  // Image has completed.  Verify the tpl is the same\r
+  //\r
+  ASSERT (Image->Tpl == gEfiCurrentTpl);\r
+  CoreRestoreTpl (Image->Tpl);\r
+\r
+  CoreFreePool (Image->JumpBuffer);\r
+\r
+  //\r
+  // Pop the current start image context\r
+  //\r
+  mCurrentImage = LastImage;\r
+\r
+  //\r
+  // Go connect any handles that were created or modified while the image executed.\r
+  //\r
+  CoreConnectHandlesByKey (HandleDatabaseKey);\r
+\r
+  //\r
+  // Handle the image's returned ExitData\r
+  //\r
+  DEBUG_CODE_BEGIN ();\r
+    if (Image->ExitDataSize != 0 || Image->ExitData != NULL) {\r
+\r
+      DEBUG (\r
+        (EFI_D_LOAD,\r
+        "StartImage: ExitDataSize %d, ExitData %x",\r
+                            Image->ExitDataSize,\r
+        Image->ExitData)\r
+        );\r
+      if (Image->ExitData != NULL) {\r
+        DEBUG ((EFI_D_LOAD, " (%hs)", Image->ExitData));\r
+      }\r
+      DEBUG ((EFI_D_LOAD, "\n"));\r
+    }\r
+  DEBUG_CODE_END ();\r
+\r
+  //\r
+  //  Return the exit data to the caller\r
+  //\r
+  if (ExitData != NULL && ExitDataSize != NULL) {\r
+    *ExitDataSize = Image->ExitDataSize;\r
+    *ExitData     = Image->ExitData;\r
+  } else {\r
+    //\r
+    // Caller doesn't want the exit data, free it\r
+    //\r
+    CoreFreePool (Image->ExitData);\r
+    Image->ExitData = NULL;\r
+  }\r
+\r
+  //\r
+  // Save the Status because Image will get destroyed if it is unloaded.\r
+  //\r
+  Status = Image->Status;\r
+\r
+  //\r
+  // If the image returned an error, or if the image is an application\r
+  // unload it\r
+  //\r
+  if (EFI_ERROR (Image->Status) || Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {\r
+    CoreUnloadAndCloseImage (Image, TRUE);\r
+  }\r
+\r
+  //\r
+  // Done\r
+  //\r
+  PERF_END (ImageHandle, START_IMAGE_TOK, NULL, 0);\r
+  return Status;\r
+}\r
+\r
+\r
+VOID\r
+CoreUnloadAndCloseImage (\r
+  IN LOADED_IMAGE_PRIVATE_DATA  *Image,\r
+  IN BOOLEAN                    FreePage\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unloads EFI image from memory.\r
+\r
+Arguments:\r
+\r
+  Image      - EFI image\r
+  FreePage   - Free allocated pages\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                          Status;\r
+  UINTN                               HandleCount;\r
+  EFI_HANDLE                          *HandleBuffer;\r
+  UINTN                               HandleIndex;\r
+  EFI_GUID                            **ProtocolGuidArray;\r
+  UINTN                               ArrayCount;\r
+  UINTN                               ProtocolIndex;\r
+  EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo;\r
+  UINTN                               OpenInfoCount;\r
+  UINTN                               OpenInfoIndex;\r
+\r
+  if (Image->Ebc != NULL) {\r
+    //\r
+    // If EBC protocol exists we must perform cleanups for this image.\r
+    //\r
+    Image->Ebc->UnloadImage (Image->Ebc, Image->Handle);\r
+  }\r
+\r
+  //\r
+  // Unload image, free Image->ImageContext->ModHandle\r
+  //\r
+  gEfiPeiPeCoffLoader->UnloadImage (gEfiPeiPeCoffLoader, &Image->ImageContext);\r
+\r
+  //\r
+  // Free our references to the image handle\r
+  //\r
+  if (Image->Handle != NULL_HANDLE) {\r
+\r
+    Status = CoreLocateHandleBuffer (\r
+               AllHandles,\r
+               NULL,\r
+               NULL,\r
+               &HandleCount,\r
+               &HandleBuffer\r
+               );\r
+    if (!EFI_ERROR (Status)) {\r
+      for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {\r
+        Status = CoreProtocolsPerHandle (\r
+                   HandleBuffer[HandleIndex],\r
+                   &ProtocolGuidArray,\r
+                   &ArrayCount\r
+                   );\r
+        if (!EFI_ERROR (Status)) {\r
+          for (ProtocolIndex = 0; ProtocolIndex < ArrayCount; ProtocolIndex++) {\r
+            Status = CoreOpenProtocolInformation (\r
+                       HandleBuffer[HandleIndex],\r
+                       ProtocolGuidArray[ProtocolIndex],\r
+                       &OpenInfo,\r
+                       &OpenInfoCount\r
+                       );\r
+            if (!EFI_ERROR (Status)) {\r
+              for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) {\r
+                if (OpenInfo[OpenInfoIndex].AgentHandle == Image->Handle) {\r
+                  Status = CoreCloseProtocol (\r
+                             HandleBuffer[HandleIndex],\r
+                             ProtocolGuidArray[ProtocolIndex],\r
+                             Image->Handle,\r
+                             OpenInfo[OpenInfoIndex].ControllerHandle\r
+                             );\r
+                }\r
+              }\r
+              if (OpenInfo != NULL) {\r
+                CoreFreePool(OpenInfo);\r
+              }\r
+            }\r
+          }\r
+          if (ProtocolGuidArray != NULL) {\r
+            CoreFreePool(ProtocolGuidArray);\r
+          }\r
+        }\r
+      }\r
+      if (HandleBuffer != NULL) {\r
+        CoreFreePool (HandleBuffer);\r
+      }\r
+    }\r
+\r
+    CoreRemoveDebugImageInfoEntry (Image->Handle);\r
+\r
+    Status = CoreUninstallProtocolInterface (\r
+               Image->Handle,\r
+               &gEfiLoadedImageProtocolGuid,\r
+               &Image->Info\r
+               );\r
+  }\r
+\r
+  if (Image->RuntimeData != NULL) {\r
+    if (Image->RuntimeData->Link.ForwardLink != NULL) {\r
+      //\r
+      // Remove the Image from the Runtime Image list as we are about to Free it!\r
+      //\r
+      RemoveEntryList (&Image->RuntimeData->Link);\r
+    }\r
+    CoreFreePool (Image->RuntimeData);\r
+  }\r
+\r
+  //\r
+  // Free the Image from memory\r
+  //\r
+  if ((Image->ImageBasePage != 0) && FreePage) {\r
+    CoreFreePages (Image->ImageBasePage, Image->NumberOfPages);\r
+  }\r
+\r
+  //\r
+  // Done with the Image structure\r
+  //\r
+  if (Image->Info.FilePath != NULL) {\r
+    CoreFreePool (Image->Info.FilePath);\r
+  }\r
+\r
+  if (Image->FixupData != NULL) {\r
+    CoreFreePool (Image->FixupData);\r
+  }\r
+\r
+  CoreFreePool (Image);\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreExit (\r
+  IN EFI_HANDLE  ImageHandle,\r
+  IN EFI_STATUS  Status,\r
+  IN UINTN       ExitDataSize,\r
+  IN CHAR16      *ExitData  OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Terminates the currently loaded EFI image and returns control to boot services.\r
+\r
+Arguments:\r
+\r
+  ImageHandle       - Handle that identifies the image. This parameter is passed to the image\r
+                      on entry.\r
+  Status            - The image's exit code.\r
+  ExitDataSize      - The size, in bytes, of ExitData. Ignored if ExitStatus is\r
+                      EFI_SUCCESS.\r
+  ExitData          - Pointer to a data buffer that includes a Null-terminated Unicode string,\r
+                      optionally followed by additional binary data. The string is a\r
+                      description that the caller may use to further indicate the reason for\r
+                      the image's exit.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Image handle is NULL or it is not current image.\r
+\r
+  EFI_SUCCESS               - Successfully terminates the currently loaded EFI image.\r
+\r
+  EFI_ACCESS_DENIED         - Should never reach there.\r
+\r
+  EFI_OUT_OF_RESOURCES      - Could not allocate pool\r
+\r
+--*/\r
+{\r
+  LOADED_IMAGE_PRIVATE_DATA  *Image;\r
+  EFI_TPL                    OldTpl;\r
+\r
+  //\r
+  // Prevent possible reentrance to this function\r
+  // for the same ImageHandle\r
+  // \r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY); \r
\r
+  Image = CoreLoadedImageInfo (ImageHandle);\r
+  if (Image == NULL_HANDLE) {\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
+  }\r
+\r
+  if (!Image->Started) {\r
+    //\r
+    // The image has not been started so just free its resources\r
+    //\r
+    CoreUnloadAndCloseImage (Image, TRUE);\r
+    Status = EFI_SUCCESS;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Image has been started, verify this image can exit\r
+  //\r
+  if (Image != mCurrentImage) {\r
+    DEBUG ((EFI_D_LOAD|EFI_D_ERROR, "Exit: Image is not exitable image\n"));\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Set status\r
+  //\r
+  Image->Status = Status;\r
+\r
+  //\r
+  // If there's ExitData info, move it\r
+  //\r
+  if (ExitData != NULL) {\r
+    Image->ExitDataSize = ExitDataSize;\r
+    Image->ExitData = CoreAllocateBootServicesPool (Image->ExitDataSize);\r
+    if (Image->ExitData == NULL) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto Done;\r
+    }\r
+    CopyMem (Image->ExitData, ExitData, Image->ExitDataSize);\r
+  }\r
+\r
+  CoreRestoreTpl (OldTpl);\r
+  //\r
+  // return to StartImage\r
+  //\r
+  LongJump (Image->JumpContext, (UINTN)-1);\r
+\r
+  //\r
+  // If we return from LongJump, then it is an error\r
+  //\r
+  ASSERT (FALSE);\r
+  Status = EFI_ACCESS_DENIED;\r
+Done:\r
+  CoreRestoreTpl (OldTpl);\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUnloadImage (\r
+  IN EFI_HANDLE  ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unloads an image.\r
+\r
+Arguments:\r
+\r
+  ImageHandle           - Handle that identifies the image to be unloaded.\r
+\r
+Returns:\r
+\r
+ EFI_SUCCESS            - The image has been unloaded.\r
+ EFI_UNSUPPORTED        - The image has been sarted, and does not support unload.\r
+ EFI_INVALID_PARAMPETER - ImageHandle is not a valid image handle.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                 Status;\r
+  LOADED_IMAGE_PRIVATE_DATA  *Image;\r
+  EFI_TPL                    OldTpl;\r
+\r
+  //\r
+  // Prevent possible reentrance to this function\r
+  // for the same ImageHandle\r
+  // \r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY);\r
\r
+  Image = CoreLoadedImageInfo (ImageHandle);\r
+  if (Image == NULL ) {\r
+    //\r
+    // The image handle is not valid\r
+    //\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
+  }\r
+\r
+  if (Image->Started) {\r
+    //\r
+    // The image has been started, request it to unload.\r
+    //\r
+    Status = EFI_UNSUPPORTED;\r
+    if (Image->Info.Unload != NULL) {\r
+      Status = Image->Info.Unload (ImageHandle);\r
+    }\r
+\r
+  } else {\r
+    //\r
+    // This Image hasn't been started, thus it can be unloaded\r
+    //\r
+    Status = EFI_SUCCESS;\r
+  }\r
+\r
+\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // if the Image was not started or Unloaded O.K. then clean up\r
+    //\r
+    CoreUnloadAndCloseImage (Image, TRUE);\r
+  }\r
+\r
+Done:\r
+  CoreRestoreTpl (OldTpl);\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreUnloadImageEx (\r
+  IN EFI_PE32_IMAGE_PROTOCOL  *This,\r
+  IN EFI_HANDLE                         ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Unload the specified image.\r
+\r
+Arguments:\r
+\r
+  This              - Indicates the calling context.\r
+\r
+  ImageHandle       - The specified image handle.\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Image handle is NULL.\r
+\r
+  EFI_UNSUPPORTED             - Attempt to unload an unsupported image.\r
+\r
+  EFI_SUCCESS                 - Image successfully unloaded.\r
+\r
+--*/\r
+{\r
+  return CoreUnloadImage (ImageHandle);\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Image/ImageFile.c b/MdeModulePkg/Core/Dxe/Image/ImageFile.c
new file mode 100644 (file)
index 0000000..408688c
--- /dev/null
@@ -0,0 +1,499 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+  \r
+  ImageFile.c\r
+\r
+\r
+Abstract:\r
+\r
+  \r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+EFI_STATUS\r
+CoreOpenImageFile (\r
+  IN BOOLEAN                        BootPolicy,\r
+  IN VOID                           *SourceBuffer   OPTIONAL,\r
+  IN UINTN                          SourceSize,\r
+  IN OUT EFI_DEVICE_PATH_PROTOCOL   *FilePath,\r
+  OUT EFI_HANDLE                    *DeviceHandle,\r
+  IN IMAGE_FILE_HANDLE              *ImageFileHandle,\r
+  OUT UINT32                        *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Opens a file for (simple) reading.  The simple read abstraction\r
+    will access the file either from a memory copy, from a file\r
+    system interface, or from the load file interface.\r
+\r
+Arguments:\r
+\r
+  BootPolicy    - Policy for Open Image File.\r
+  SourceBuffer  - Pointer to the memory location containing copy\r
+                  of the image to be loaded.\r
+  SourceSize    - The size in bytes of SourceBuffer.\r
+  FilePath      - The specific file path from which the image is loaded\r
+  DeviceHandle  - Pointer to the return device handle.\r
+  ImageFileHandle      - Pointer to the image file handle.\r
+  AuthenticationStatus - Pointer to a caller-allocated UINT32 in which the authentication status is returned. \r
+    \r
+Returns:\r
+\r
+    EFI_SUCCESS     - Image file successfully opened.\r
+    \r
+    EFI_LOAD_ERROR  - If the caller passed a copy of the file, and SourceSize is 0.\r
+    \r
+    EFI_INVALID_PARAMETER   - File path is not valid.\r
+    \r
+    EFI_NOT_FOUND   - File not found.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                        Status;\r
+  EFI_DEVICE_PATH_PROTOCOL          *TempFilePath;\r
+  FILEPATH_DEVICE_PATH              *FilePathNode;\r
+  MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FwVolFilePathNode;\r
+  EFI_SIMPLE_FILE_SYSTEM_PROTOCOL   *Volume;\r
+  EFI_FILE_HANDLE                   FileHandle;\r
+  EFI_FILE_HANDLE                   LastHandle;\r
+  EFI_LOAD_FILE_PROTOCOL            *LoadFile;\r
+  EFI_FIRMWARE_VOLUME_PROTOCOL      *FwVol;\r
+  EFI_SECTION_TYPE                  SectionType;\r
+  UINT8                             *Pe32Buffer;\r
+  UINTN                             Pe32BufferSize;\r
+  EFI_FV_FILETYPE                   Type;\r
+  EFI_FV_FILE_ATTRIBUTES            Attrib;\r
+  EFI_FILE_INFO                     *FileInfo;\r
+  UINTN                             FileInfoSize;\r
+  EFI_GUID                          *NameGuid;\r
+\r
+  *AuthenticationStatus = 0;\r
+  ZeroMem (ImageFileHandle, sizeof (IMAGE_FILE_HANDLE));\r
+  ImageFileHandle->Signature = IMAGE_FILE_HANDLE_SIGNATURE;\r
+\r
+  //\r
+  // If the caller passed a copy of the file, then just use it\r
+  //\r
+  if (SourceBuffer != NULL) {\r
+    ImageFileHandle->Source     = SourceBuffer;\r
+    ImageFileHandle->SourceSize = SourceSize;\r
+    *DeviceHandle     = NULL;\r
+    if (SourceSize > 0) {\r
+      Status = EFI_SUCCESS;\r
+    } else {\r
+      Status = EFI_LOAD_ERROR;\r
+    }\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Make sure FilePath is valid\r
+  //\r
+  if (FilePath == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Check to see if it's in a Firmware Volume\r
+  //\r
+  FwVolFilePathNode = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)FilePath;\r
+  Status = CoreDevicePathToInterface (\r
+            &gEfiFirmwareVolumeProtocolGuid, \r
+            (EFI_DEVICE_PATH_PROTOCOL **)&FwVolFilePathNode, \r
+            (VOID*)&FwVol, \r
+            DeviceHandle\r
+            );\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // For FwVol File system there is only a single file name that is a GUID.\r
+    //\r
+    NameGuid = EfiGetNameGuidFromFwVolDevicePathNode (FwVolFilePathNode);\r
+    if (NameGuid != NULL) {\r
+\r
+      SectionType = EFI_SECTION_PE32;\r
+      Pe32Buffer  = NULL;\r
+      Status = FwVol->ReadSection (\r
+                        FwVol, \r
+                        NameGuid,  \r
+                        SectionType,   \r
+                        0,\r
+                        (VOID **)&Pe32Buffer,\r
+                        &Pe32BufferSize,\r
+                        AuthenticationStatus\r
+                        );\r
+      if (EFI_ERROR (Status)) {\r
+        //\r
+        // Try a raw file, since a PE32 SECTION does not exist\r
+        //\r
+        if (Pe32Buffer != NULL) {\r
+          CoreFreePool (Pe32Buffer);\r
+          *AuthenticationStatus = 0;\r
+        }\r
+        Pe32Buffer = NULL;\r
+        Status = FwVol->ReadFile (\r
+                          FwVol, \r
+                          NameGuid, \r
+                          (VOID **)&Pe32Buffer,\r
+                          &Pe32BufferSize,\r
+                          &Type,\r
+                          &Attrib,\r
+                          AuthenticationStatus\r
+                          );\r
+      }\r
+            \r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // One of the reads passed so we are done\r
+        //\r
+        ImageFileHandle->Source = Pe32Buffer;\r
+        ImageFileHandle->SourceSize = Pe32BufferSize;\r
+        ImageFileHandle->FreeBuffer = TRUE;\r
+        goto Done;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Attempt to access the file via a file system interface\r
+  //\r
+  FilePathNode = (FILEPATH_DEVICE_PATH *) FilePath;\r
+  Status = CoreDevicePathToInterface (\r
+            &gEfiSimpleFileSystemProtocolGuid, \r
+            (EFI_DEVICE_PATH_PROTOCOL **)&FilePathNode, \r
+            (VOID*)&Volume, \r
+            DeviceHandle\r
+            );\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Open the Volume to get the File System handle\r
+    //\r
+    Status = Volume->OpenVolume (Volume, &FileHandle);\r
+    if (!EFI_ERROR (Status)) {\r
+     \r
+      //\r
+      // Parse each MEDIA_FILEPATH_DP node. There may be more than one, since the\r
+      //  directory information and filename can be seperate. The goal is to inch\r
+      //  our way down each device path node and close the previous node\r
+      //\r
+      while (!IsDevicePathEnd (&FilePathNode->Header)) {\r
+        if (DevicePathType (&FilePathNode->Header) != MEDIA_DEVICE_PATH ||\r
+            DevicePathSubType (&FilePathNode->Header) != MEDIA_FILEPATH_DP) {\r
+          Status = EFI_UNSUPPORTED;\r
+        }\r
+\r
+        if (EFI_ERROR (Status)) {\r
+          //\r
+          // Exit loop on Error\r
+          //\r
+          break;\r
+        }\r
+\r
+        LastHandle = FileHandle;\r
+        FileHandle = NULL;\r
+        Status = LastHandle->Open (\r
+                              LastHandle,\r
+                              &FileHandle,\r
+                              FilePathNode->PathName,\r
+                              EFI_FILE_MODE_READ,\r
+                              0\r
+                              );\r
+\r
+        //\r
+        // Close the previous node\r
+        //\r
+        LastHandle->Close (LastHandle);\r
+\r
+        FilePathNode = (FILEPATH_DEVICE_PATH *) NextDevicePathNode (&FilePathNode->Header);\r
+      }\r
+\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // We have found the file. Now we need to read it. Before we can read the file we need to\r
+        // figure out how big the file is.\r
+        //\r
+        FileInfo = NULL;\r
+        FileInfoSize = sizeof (EFI_FILE_INFO);\r
+        while (CoreGrowBuffer (&Status, (VOID **)&FileInfo, FileInfoSize)) {\r
+          //\r
+          // Automatically allocate buffer of the correct size and make the call\r
+          //\r
+          Status = FileHandle->GetInfo (\r
+                                FileHandle,\r
+                                &gEfiFileInfoGuid,\r
+                                &FileInfoSize,\r
+                                FileInfo                               \r
+                                );\r
+        }\r
+        if (!EFI_ERROR (Status)) {\r
+          //\r
+          // Allocate space for the file\r
+          //\r
+          ImageFileHandle->Source = CoreAllocateBootServicesPool ((UINTN)FileInfo->FileSize);\r
+          if (ImageFileHandle->Source != NULL) {\r
+            //\r
+            // Read the file into the buffer we allocated\r
+            //\r
+            ImageFileHandle->SourceSize = (UINTN)FileInfo->FileSize;\r
+            ImageFileHandle->FreeBuffer = TRUE;\r
+            Status = FileHandle->Read (FileHandle, &ImageFileHandle->SourceSize, ImageFileHandle->Source);\r
+\r
+            //\r
+            // Close the file since we are done\r
+            //\r
+            FileHandle->Close (FileHandle);\r
+          } else {\r
+            Status = EFI_OUT_OF_RESOURCES;\r
+          }\r
+\r
+          goto Done;\r
+        }\r
+      }\r
+    }\r
+  } \r
+\r
+\r
+  //\r
+  // Try LoadFile style\r
+  //\r
+\r
+  TempFilePath = FilePath;\r
+  Status = CoreDevicePathToInterface (\r
+              &gEfiLoadFileProtocolGuid,\r
+              &TempFilePath,\r
+              (VOID*)&LoadFile,\r
+              DeviceHandle\r
+              );\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Call LoadFile with the correct buffer size\r
+    //\r
+    while (CoreGrowBuffer (&Status, (VOID **)&ImageFileHandle->Source, ImageFileHandle->SourceSize)) {\r
+      Status = LoadFile->LoadFile (\r
+                           LoadFile,\r
+                           TempFilePath,\r
+                           BootPolicy,\r
+                           &ImageFileHandle->SourceSize,\r
+                           ImageFileHandle->Source\r
+                           );\r
+      //\r
+      // If success or other error happens, stop loop\r
+      //\r
+      if (Status != EFI_BUFFER_TOO_SMALL) {\r
+        break;\r
+      }\r
+    }\r
+\r
+    if (!EFI_ERROR (Status) || Status == EFI_ALREADY_STARTED) {\r
+      ImageFileHandle->FreeBuffer = TRUE;\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Nothing else to try\r
+  //\r
+  DEBUG ((EFI_D_LOAD|EFI_D_WARN, "CoreOpenImageFile: Device did not support a known load protocol\n"));\r
+  Status = EFI_NOT_FOUND;\r
+\r
+Done:\r
+\r
+  //\r
+  // If the file was not accessed, clean up\r
+  //\r
+  if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) {\r
+    if (ImageFileHandle->FreeBuffer) {\r
+      //\r
+      // Free the source buffer if we allocated it\r
+      //\r
+      CoreFreePool (ImageFileHandle->Source);\r
+    }\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreReadImageFile (\r
+  IN     VOID    *UserHandle,\r
+  IN     UINTN   Offset,\r
+  IN OUT UINTN   *ReadSize,\r
+  OUT    VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Read image file (specified by UserHandle) into user specified buffer with specified offset\r
+  and length.\r
+\r
+Arguments:\r
+\r
+  UserHandle      - Image file handle\r
+  \r
+  Offset          - Offset to the source file\r
+  \r
+  ReadSize        - For input, pointer of size to read;\r
+                    For output, pointer of size actually read.\r
+  \r
+  Buffer          - Buffer to write into\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS     - Successfully read the specified part of file into buffer.\r
+\r
+--*/\r
+{\r
+  UINTN               EndPosition;\r
+  IMAGE_FILE_HANDLE  *FHand;\r
+\r
+  FHand = (IMAGE_FILE_HANDLE  *)UserHandle;\r
+  ASSERT (FHand->Signature == IMAGE_FILE_HANDLE_SIGNATURE);\r
+\r
+  //\r
+  // Move data from our local copy of the file\r
+  //\r
+  EndPosition = Offset + *ReadSize;\r
+  if (EndPosition > FHand->SourceSize) {\r
+    *ReadSize = (UINT32)(FHand->SourceSize - Offset);\r
+  }  \r
+  if (Offset >= FHand->SourceSize) {\r
+      *ReadSize = 0;\r
+  }\r
+\r
+  CopyMem (Buffer, (CHAR8 *)FHand->Source + Offset, *ReadSize);\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+EFI_STATUS\r
+CoreDevicePathToInterface (\r
+  IN EFI_GUID                     *Protocol,\r
+  IN EFI_DEVICE_PATH_PROTOCOL     **FilePath,\r
+  OUT VOID                        **Interface,\r
+  OUT EFI_HANDLE                  *Handle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Search a handle to a device on a specified device path that supports a specified protocol,\r
+  interface of that protocol on that handle is another output.\r
+\r
+Arguments:\r
+\r
+  Protocol      - The protocol to search for\r
+  \r
+  FilePath      - The specified device path\r
+  \r
+  Interface     - Interface of the protocol on the handle\r
+  \r
+  Handle        - The handle to the device on the specified device path that supports the protocol.\r
+  \r
+Returns:\r
+\r
+  Status code.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                      Status;\r
+\r
+  Status = CoreLocateDevicePath (Protocol, FilePath, Handle);\r
+  if (!EFI_ERROR (Status)) {\r
+    Status = CoreHandleProtocol (*Handle, Protocol, Interface);\r
+  }\r
+  return Status;\r
+}\r
+\r
+BOOLEAN\r
+CoreGrowBuffer (\r
+  IN OUT EFI_STATUS   *Status,\r
+  IN OUT VOID         **Buffer,\r
+  IN UINTN            BufferSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Helper function called as part of the code needed\r
+    to allocate the proper sized buffer for various \r
+    EFI interfaces.\r
+\r
+Arguments:\r
+\r
+    Status      - Current status\r
+\r
+    Buffer      - Current allocated buffer, or NULL\r
+\r
+    BufferSize  - Current buffer size needed\r
+    \r
+Returns:\r
+    \r
+    TRUE - if the buffer was reallocated and the caller \r
+    should try the API again.\r
+\r
+    FALSE - buffer could not be allocated and the caller\r
+    should not try the API again.\r
+\r
+--*/\r
+{\r
+  BOOLEAN         TryAgain;\r
+\r
+  TryAgain = FALSE;\r
+  //\r
+  // If this is an initial request, buffer will be null with a new buffer size\r
+  //\r
+  if (*Buffer == NULL) {\r
+    *Status = EFI_BUFFER_TOO_SMALL;\r
+  }\r
+\r
+  if (BufferSize == 0) {\r
+    return TRUE;\r
+  }\r
+\r
+  //\r
+  // If the status code is "buffer too small", resize the buffer\r
+  //\r
+      \r
+  if (*Status == EFI_BUFFER_TOO_SMALL) {\r
+    if (*Buffer != NULL) {\r
+      CoreFreePool (*Buffer);\r
+    }\r
+\r
+    *Buffer = CoreAllocateBootServicesPool (BufferSize);\r
+    if (*Buffer != NULL) {\r
+      TryAgain = TRUE;\r
+    } else {    \r
+      *Status = EFI_OUT_OF_RESOURCES;\r
+    } \r
+  }\r
+\r
+  //\r
+  // If there's an error, free the buffer\r
+  //\r
+  if ((!TryAgain) && (EFI_ERROR (*Status)) && (*Buffer)) {\r
+    CoreFreePool (*Buffer);\r
+    *Buffer = NULL;\r
+  }\r
+\r
+  return TryAgain;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Library.h b/MdeModulePkg/Core/Dxe/Library.h
new file mode 100644 (file)
index 0000000..5e33da5
--- /dev/null
@@ -0,0 +1,407 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  Library.h\r
+\r
+Abstract:\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#ifndef _DXE_LIBRARY_H_\r
+#define _DXE_LIBRARY_H_\r
+\r
+\r
+VOID\r
+CoreReportProgressCode (\r
+  IN  EFI_STATUS_CODE_VALUE   Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Report status code of type EFI_PROGRESS_CODE by caller ID gEfiDxeServicesTableGuid.\r
+    \r
+Arguments:\r
+\r
+  Value    - Describes the class/subclass/operation of the hardware or software entity \r
+             that the Status Code relates to. \r
+   \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreReportProgressCodeSpecific (\r
+  IN  EFI_STATUS_CODE_VALUE   Value,\r
+  IN  EFI_HANDLE              Handle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Report status code of type EFI_PROGRESS_CODE by caller ID gEfiDxeServicesTableGuid, \r
+  with a handle as additional information.\r
+    \r
+Arguments:\r
+\r
+  Value    - Describes the class/subclass/operation of the hardware or software entity \r
+             that the Status Code relates to. \r
+             \r
+  Handle   - Additional information.\r
+   \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreAcquireLock (\r
+  IN EFI_LOCK *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Raising to the task priority level of the mutual exclusion\r
+  lock, and then acquires ownership of the lock.\r
+    \r
+Arguments:\r
+\r
+  Lock - The lock to acquire\r
+    \r
+Returns:\r
+\r
+  Lock owned\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreAcquireLockOrFail (\r
+  IN EFI_LOCK  *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initialize a basic mutual exclusion lock.   Each lock\r
+  provides mutual exclusion access at it's task priority\r
+  level.  Since there is no-premption (at any TPL) or\r
+  multiprocessor support, acquiring the lock only consists\r
+  of raising to the locks TPL.\r
+    \r
+Arguments:\r
+\r
+  Lock        - The EFI_LOCK structure to initialize\r
+   \r
+Returns:\r
+\r
+  EFI_SUCCESS       - Lock Owned.\r
+  EFI_ACCESS_DENIED - Reentrant Lock Acquisition, Lock not Owned.\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreReleaseLock (\r
+  IN EFI_LOCK *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Releases ownership of the mutual exclusion lock, and\r
+    restores the previous task priority level.\r
+    \r
+Arguments:\r
+\r
+    Lock - The lock to release\r
+    \r
+Returns:\r
+\r
+    Lock unowned\r
+\r
+--*/\r
+;\r
+\r
+//\r
+// Device Path functions\r
+//\r
+\r
+UINTN\r
+CoreDevicePathSize (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Calculate the size of a whole device path.    \r
+    \r
+Arguments:\r
+\r
+  DevicePath - The pointer to the device path data.\r
+    \r
+Returns:\r
+\r
+  Size of device path data structure..\r
+\r
+--*/\r
+;\r
+\r
+BOOLEAN\r
+CoreIsDevicePathMultiInstance (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Return TRUE is this is a multi instance device path.\r
+\r
+Arguments:\r
+  DevicePath  - A pointer to a device path data structure.\r
+\r
+\r
+Returns:\r
+  TRUE - If DevicePath is multi instance. FALSE - If DevicePath is not multi\r
+  instance.\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreDuplicateDevicePath (\r
+  IN EFI_DEVICE_PATH_PROTOCOL   *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Duplicate a new device path data structure from the old one.\r
+\r
+Arguments:\r
+  DevicePath  - A pointer to a device path data structure.\r
+\r
+Returns:\r
+  A pointer to the new allocated device path data.\r
+  Caller must free the memory used by DevicePath if it is no longer needed.\r
+\r
+--*/\r
+;\r
+\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreAppendDevicePath (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *Src1,\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *Node\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Function is used to append a Src1 and Src2 together.\r
+\r
+Arguments:\r
+  Src1  - A pointer to a device path data structure.\r
+\r
+  Node  - A pointer to a device path data structure.\r
+\r
+Returns:\r
+\r
+  A pointer to the new device path is returned.\r
+  NULL is returned if space for the new device path could not be allocated from pool.\r
+  It is up to the caller to free the memory used by Src1 and Src2 if they are no longer needed.\r
+\r
+--*/\r
+;\r
+\r
+VOID *\r
+CoreAllocateBootServicesPool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiBootServicesData, the size is specified with AllocationSize.\r
+    \r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+   \r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+;\r
+\r
+VOID *\r
+CoreAllocateZeroBootServicesPool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiBootServicesData and zero it, the size is specified with AllocationSize.\r
+    \r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+   \r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreGetConfigTable (\r
+  IN EFI_GUID *Guid,\r
+  IN OUT VOID **Table\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Find a config table by name in system table's ConfigurationTable.\r
+\r
+Arguments:\r
+\r
+  Guid        - The table name to look for\r
+  \r
+  Table       - Pointer of the config table\r
+\r
+Returns: \r
+\r
+  EFI_NOT_FOUND       - Could not find the table in system table's ConfigurationTable.\r
+  \r
+  EFI_SUCCESS         - Table successfully found.\r
+\r
+--*/\r
+;\r
+\r
+VOID *\r
+CoreAllocateRuntimeCopyPool (\r
+  IN  UINTN   AllocationSize,\r
+  IN  VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of specified size with EfiRuntimeServicesData type, and copy specified buffer to this pool.\r
+    \r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+  \r
+  Buffer            - Specified buffer that will be copy to the allocated pool\r
+   \r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+;\r
+\r
+VOID *\r
+CoreAllocateRuntimePool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiRuntimeServicesData, the size is specified with AllocationSize.\r
+    \r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+   \r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+;\r
+\r
+VOID *\r
+CoreAllocateCopyPool (\r
+  IN  UINTN   AllocationSize,\r
+  IN  VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of specified size with EfiBootServicesData type, and copy specified buffer to this pool.\r
+    \r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+  \r
+  Buffer            - Specified buffer that will be copy to the allocated pool\r
+   \r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+;\r
+\r
+EFI_EVENT\r
+CoreCreateProtocolNotifyEvent (\r
+  IN EFI_GUID             *ProtocolGuid,\r
+  IN EFI_TPL              NotifyTpl,\r
+  IN EFI_EVENT_NOTIFY     NotifyFunction,\r
+  IN VOID                 *NotifyContext,\r
+  OUT VOID                **Registration,\r
+  IN  BOOLEAN             SignalFlag\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Create a protocol notification event and return it.\r
+\r
+Arguments:\r
+\r
+  ProtocolGuid    - Protocol to register notification event on.\r
+\r
+  NotifyTpl       - Maximum TPL to signal the NotifyFunction.\r
+\r
+  NotifyFuncition - EFI notification routine.\r
+\r
+  NotifyContext   - Context passed into Event when it is created.\r
+\r
+  Registration    - Registration key returned from RegisterProtocolNotify().\r
+\r
+  SignalFlag      -  Boolean value to decide whether kick the event after register or not. \r
+\r
+Returns:\r
+\r
+  The EFI_EVENT that has been registered to be signaled when a ProtocolGuid\r
+  is added to the system.\r
+\r
+--*/\r
+;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/Library/Library.c b/MdeModulePkg/Core/Dxe/Library/Library.c
new file mode 100644 (file)
index 0000000..3d8a312
--- /dev/null
@@ -0,0 +1,613 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+  Library.c\r
+\r
+Abstract:\r
+\r
+  DXE Core library services.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+UINTN mErrorLevel = EFI_D_ERROR | EFI_D_LOAD;\r
+\r
+EFI_DEVICE_HANDLE_EXTENDED_DATA mStatusCodeData = {\r
+  {\r
+    sizeof (EFI_STATUS_CODE_DATA),\r
+    0,\r
+    EFI_STATUS_CODE_SPECIFIC_DATA_GUID\r
+  },\r
+  NULL\r
+};\r
+\r
+VOID\r
+CoreReportProgressCodeSpecific (\r
+  IN  EFI_STATUS_CODE_VALUE   Value,\r
+  IN  EFI_HANDLE              Handle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Report status code of type EFI_PROGRESS_CODE by caller ID gEfiDxeServicesTableGuid,\r
+  with a handle as additional information.\r
+\r
+Arguments:\r
+\r
+  Value    - Describes the class/subclass/operation of the hardware or software entity\r
+             that the Status Code relates to.\r
+\r
+  Handle   - Additional information.\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  mStatusCodeData.DataHeader.Size = sizeof (EFI_DEVICE_HANDLE_EXTENDED_DATA) - sizeof (EFI_STATUS_CODE_DATA);\r
+  mStatusCodeData.Handle          = Handle;\r
+\r
+  if ((gStatusCode != NULL) && (gStatusCode->ReportStatusCode != NULL) ) {\r
+    gStatusCode->ReportStatusCode (\r
+      EFI_PROGRESS_CODE,\r
+      Value,\r
+      0,\r
+      &gEfiDxeServicesTableGuid,\r
+      (EFI_STATUS_CODE_DATA *) &mStatusCodeData\r
+      );\r
+  }\r
+}\r
+\r
+VOID\r
+CoreReportProgressCode (\r
+  IN  EFI_STATUS_CODE_VALUE   Value\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Report status code of type EFI_PROGRESS_CODE by caller ID gEfiDxeServicesTableGuid.\r
+\r
+Arguments:\r
+\r
+  Value    - Describes the class/subclass/operation of the hardware or software entity\r
+             that the Status Code relates to.\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  if ((gStatusCode != NULL) && (gStatusCode->ReportStatusCode != NULL) ) {\r
+    gStatusCode->ReportStatusCode (\r
+      EFI_PROGRESS_CODE,\r
+      Value,\r
+      0,\r
+      &gEfiDxeServicesTableGuid,\r
+      NULL\r
+      );\r
+  }\r
+}\r
+\r
+\r
+VOID *\r
+CoreAllocateBootServicesPool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiBootServicesData, the size is specified with AllocationSize.\r
+\r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+\r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+{\r
+  VOID  *Memory;\r
+\r
+  CoreAllocatePool (EfiBootServicesData, AllocationSize, &Memory);\r
+  return Memory;\r
+}\r
+\r
+\r
+VOID *\r
+CoreAllocateZeroBootServicesPool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiBootServicesData and zero it, the size is specified with AllocationSize.\r
+\r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+\r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+{\r
+  VOID  *Memory;\r
+\r
+  Memory = CoreAllocateBootServicesPool (AllocationSize);\r
+  SetMem (Memory, (Memory == NULL) ? 0 : AllocationSize, 0);\r
+  return Memory;\r
+}\r
+\r
+\r
+VOID *\r
+CoreAllocateCopyPool (\r
+  IN  UINTN   AllocationSize,\r
+  IN  VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of specified size with EfiBootServicesData type, and copy specified buffer to this pool.\r
+\r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+\r
+  Buffer            - Specified buffer that will be copy to the allocated pool\r
+\r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+{\r
+  VOID  *Memory;\r
+\r
+  Memory = CoreAllocateBootServicesPool (AllocationSize);\r
+  CopyMem (Memory, Buffer, (Memory == NULL) ? 0 : AllocationSize);\r
+\r
+  return Memory;\r
+}\r
+\r
+\r
+\r
+VOID *\r
+CoreAllocateRuntimePool (\r
+  IN  UINTN   AllocationSize\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of type EfiRuntimeServicesData, the size is specified with AllocationSize.\r
+\r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+\r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+{\r
+  VOID  *Memory;\r
+\r
+  CoreAllocatePool (EfiRuntimeServicesData, AllocationSize, &Memory);\r
+  return Memory;\r
+}\r
+\r
+VOID *\r
+CoreAllocateRuntimeCopyPool (\r
+  IN  UINTN   AllocationSize,\r
+  IN  VOID    *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of specified size with EfiRuntimeServicesData type, and copy specified buffer to this pool.\r
+\r
+Arguments:\r
+\r
+  AllocationSize    - Size to allocate.\r
+\r
+  Buffer            - Specified buffer that will be copy to the allocated pool\r
+\r
+Returns:\r
+\r
+  Pointer of the allocated pool.\r
+\r
+--*/\r
+\r
+{\r
+  VOID  *Memory;\r
+\r
+  Memory = CoreAllocateRuntimePool (AllocationSize);\r
+  CopyMem (Memory, Buffer, (Memory == NULL) ? 0 : AllocationSize);\r
+\r
+  return Memory;\r
+}\r
+\r
+\r
+\r
+//\r
+// Lock Stuff\r
+//\r
+\r
+\r
+\r
+EFI_STATUS\r
+CoreAcquireLockOrFail (\r
+  IN EFI_LOCK  *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Initialize a basic mutual exclusion lock.   Each lock\r
+  provides mutual exclusion access at it's task priority\r
+  level.  Since there is no-premption (at any TPL) or\r
+  multiprocessor support, acquiring the lock only consists\r
+  of raising to the locks TPL.\r
+\r
+Arguments:\r
+\r
+  Lock        - The EFI_LOCK structure to initialize\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Lock Owned.\r
+  EFI_ACCESS_DENIED - Reentrant Lock Acquisition, Lock not Owned.\r
+\r
+--*/\r
+{\r
+  ASSERT (Lock != NULL);\r
+  ASSERT (Lock->Lock != EfiLockUninitialized);\r
+\r
+  if (Lock->Lock == EfiLockAcquired) {\r
+    //\r
+    // Lock is already owned, so bail out\r
+    //\r
+    return EFI_ACCESS_DENIED;\r
+  }\r
+\r
+  Lock->OwnerTpl = CoreRaiseTpl (Lock->Tpl);\r
+\r
+  Lock->Lock = EfiLockAcquired;\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+VOID\r
+CoreAcquireLock (\r
+  IN EFI_LOCK  *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Raising to the task priority level of the mutual exclusion\r
+  lock, and then acquires ownership of the lock.\r
+\r
+Arguments:\r
+\r
+  Lock - The lock to acquire\r
+\r
+Returns:\r
+\r
+  Lock owned\r
+\r
+--*/\r
+{\r
+  ASSERT (Lock != NULL);\r
+  ASSERT (Lock->Lock == EfiLockReleased);\r
+\r
+  Lock->OwnerTpl = CoreRaiseTpl (Lock->Tpl);\r
+  Lock->Lock     = EfiLockAcquired;\r
+}\r
+\r
+\r
+VOID\r
+CoreReleaseLock (\r
+  IN EFI_LOCK  *Lock\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Releases ownership of the mutual exclusion lock, and\r
+    restores the previous task priority level.\r
+\r
+Arguments:\r
+\r
+    Lock - The lock to release\r
+\r
+Returns:\r
+\r
+    Lock unowned\r
+\r
+--*/\r
+{\r
+  EFI_TPL Tpl;\r
+\r
+  ASSERT (Lock != NULL);\r
+  ASSERT (Lock->Lock == EfiLockAcquired);\r
+\r
+  Tpl = Lock->OwnerTpl;\r
+\r
+  Lock->Lock = EfiLockReleased;\r
+\r
+  CoreRestoreTpl (Tpl);\r
+}\r
+\r
+\r
+UINTN\r
+CoreDevicePathSize (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Calculate the size of a whole device path.\r
+\r
+Arguments:\r
+\r
+  DevicePath - The pointer to the device path data.\r
+\r
+Returns:\r
+\r
+  Size of device path data structure..\r
+\r
+--*/\r
+{\r
+  EFI_DEVICE_PATH_PROTOCOL     *Start;\r
+\r
+  if (DevicePath == NULL) {\r
+    return 0;\r
+  }\r
+\r
+  //\r
+  // Search for the end of the device path structure\r
+  //\r
+  Start = DevicePath;\r
+  while (!EfiIsDevicePathEnd (DevicePath)) {\r
+    DevicePath = EfiNextDevicePathNode (DevicePath);\r
+  }\r
+\r
+  //\r
+  // Compute the size and add back in the size of the end device path structure\r
+  //\r
+  return ((UINTN)DevicePath - (UINTN)Start) + sizeof(EFI_DEVICE_PATH_PROTOCOL);\r
+}\r
+\r
+\r
+BOOLEAN\r
+CoreIsDevicePathMultiInstance (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Return TRUE is this is a multi instance device path.\r
+\r
+Arguments:\r
+  DevicePath  - A pointer to a device path data structure.\r
+\r
+\r
+Returns:\r
+  TRUE - If DevicePath is multi instance. FALSE - If DevicePath is not multi\r
+  instance.\r
+\r
+--*/\r
+{\r
+  EFI_DEVICE_PATH_PROTOCOL *Node;\r
+\r
+  if (DevicePath == NULL) {\r
+    return FALSE;\r
+  }\r
+\r
+  Node = DevicePath;\r
+  while (!EfiIsDevicePathEnd (Node)) {\r
+    if (EfiIsDevicePathEndInstance (Node)) {\r
+      return TRUE;\r
+    }\r
+    Node = EfiNextDevicePathNode (Node);\r
+  }\r
+  return FALSE;\r
+}\r
+\r
+\r
+\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreDuplicateDevicePath (\r
+  IN EFI_DEVICE_PATH_PROTOCOL   *DevicePath\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Duplicate a new device path data structure from the old one.\r
+\r
+Arguments:\r
+  DevicePath  - A pointer to a device path data structure.\r
+\r
+Returns:\r
+  A pointer to the new allocated device path data.\r
+  Caller must free the memory used by DevicePath if it is no longer needed.\r
+\r
+--*/\r
+{\r
+  EFI_DEVICE_PATH_PROTOCOL  *NewDevicePath;\r
+  UINTN                     Size;\r
+\r
+  if (DevicePath == NULL) {\r
+    return NULL;\r
+  }\r
+\r
+  //\r
+  // Compute the size\r
+  //\r
+  Size = CoreDevicePathSize (DevicePath);\r
+\r
+  //\r
+  // Allocate space for duplicate device path\r
+  //\r
+  NewDevicePath = CoreAllocateCopyPool (Size, DevicePath);\r
+\r
+  return NewDevicePath;\r
+}\r
+\r
+\r
+\r
+EFI_DEVICE_PATH_PROTOCOL *\r
+CoreAppendDevicePath (\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *Src1,\r
+  IN EFI_DEVICE_PATH_PROTOCOL  *Src2\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Function is used to append a Src1 and Src2 together.\r
+\r
+Arguments:\r
+  Src1  - A pointer to a device path data structure.\r
+\r
+  Src2  - A pointer to a device path data structure.\r
+\r
+Returns:\r
+\r
+  A pointer to the new device path is returned.\r
+  NULL is returned if space for the new device path could not be allocated from pool.\r
+  It is up to the caller to free the memory used by Src1 and Src2 if they are no longer needed.\r
+\r
+--*/\r
+{\r
+  UINTN                       Size;\r
+  UINTN                       Size1;\r
+  UINTN                       Size2;\r
+  EFI_DEVICE_PATH_PROTOCOL    *NewDevicePath;\r
+  EFI_DEVICE_PATH_PROTOCOL    *SecondDevicePath;\r
+\r
+  if (Src1 == NULL && Src2 == NULL) {\r
+    return NULL;\r
+  }\r
+\r
+  //\r
+  // Allocate space for the combined device path. It only has one end node of\r
+  // length EFI_DEVICE_PATH_PROTOCOL\r
+  //\r
+  Size1 = CoreDevicePathSize (Src1);\r
+  Size2 = CoreDevicePathSize (Src2);\r
+  Size = Size1 + Size2 - sizeof(EFI_DEVICE_PATH_PROTOCOL);\r
+\r
+  NewDevicePath = CoreAllocateCopyPool (Size, Src1);\r
+  if (NewDevicePath != NULL) {\r
+\r
+     //\r
+     // Over write Src1 EndNode and do the copy\r
+     //\r
+     SecondDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)((CHAR8 *)NewDevicePath + (Size1 - sizeof(EFI_DEVICE_PATH_PROTOCOL)));\r
+     CopyMem (SecondDevicePath, Src2, Size2);\r
+  }\r
+\r
+  return NewDevicePath;\r
+}\r
+\r
+\r
+\r
+EFI_EVENT\r
+CoreCreateProtocolNotifyEvent (\r
+  IN EFI_GUID             *ProtocolGuid,\r
+  IN EFI_TPL              NotifyTpl,\r
+  IN EFI_EVENT_NOTIFY     NotifyFunction,\r
+  IN VOID                 *NotifyContext,\r
+  OUT VOID                **Registration,\r
+  IN  BOOLEAN             SignalFlag\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Create a protocol notification event and return it.\r
+\r
+Arguments:\r
+\r
+  ProtocolGuid    - Protocol to register notification event on.\r
+\r
+  NotifyTpl        - Maximum TPL to signal the NotifyFunction.\r
+\r
+  NotifyFuncition  - EFI notification routine.\r
+\r
+  NotifyContext   - Context passed into Event when it is created.\r
+\r
+  Registration    - Registration key returned from RegisterProtocolNotify().\r
+\r
+  SignalFlag      -  Boolean value to decide whether kick the event after register or not.\r
+\r
+Returns:\r
+\r
+  The EFI_EVENT that has been registered to be signaled when a ProtocolGuid\r
+  is added to the system.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS              Status;\r
+  EFI_EVENT               Event;\r
+\r
+  //\r
+  // Create the event\r
+  //\r
+\r
+  Status = CoreCreateEvent (\r
+            EVT_NOTIFY_SIGNAL,\r
+            NotifyTpl,\r
+            NotifyFunction,\r
+            NotifyContext,\r
+           &Event\r
+            );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Register for protocol notifactions on this event\r
+  //\r
+\r
+  Status = CoreRegisterProtocolNotify (\r
+            ProtocolGuid,\r
+            Event,\r
+            Registration\r
+            );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  if (SignalFlag) {\r
+    //\r
+    // Kick the event so we will perform an initial pass of\r
+    // current installed drivers\r
+    //\r
+    CoreSignalEvent (Event);\r
+  }\r
+\r
+  return Event;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c
new file mode 100644 (file)
index 0000000..c4f3274
--- /dev/null
@@ -0,0 +1,1656 @@
+/*++\r
+\r
+Copyright (c) 2007, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  page.c\r
+\r
+Abstract:\r
+\r
+  EFI Memory page management\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
+\r
+//\r
+// Entry for tracking the memory regions for each memory type to help cooalese like memory types\r
+//\r
+typedef struct {\r
+  EFI_PHYSICAL_ADDRESS  BaseAddress;\r
+  EFI_PHYSICAL_ADDRESS  MaximumAddress;\r
+  UINT64                CurrentNumberOfPages;\r
+  UINTN                 InformationIndex;\r
+} EFI_MEMORY_TYPE_STAISTICS;\r
+\r
+//\r
+// MemoryMap - The current memory map\r
+//\r
+UINTN     mMemoryMapKey = 0;\r
+\r
+//\r
+// mMapStack - space to use as temp storage to build new map descriptors\r
+// mMapDepth - depth of new descriptor stack\r
+//\r
+\r
+#define MAX_MAP_DEPTH 6\r
+UINTN         mMapDepth = 0;\r
+MEMORY_MAP    mMapStack[MAX_MAP_DEPTH];\r
+UINTN         mFreeMapStack = 0;\r
+//\r
+// This list maintain the free memory map list\r
+//\r
+LIST_ENTRY   mFreeMemoryMapEntryList  = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList);\r
+BOOLEAN mMemoryTypeInformationInitialized = FALSE;\r
+\r
+EFI_MEMORY_TYPE_STAISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = {\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiReservedMemoryType\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiLoaderCode\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiLoaderData\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiBootServicesCode\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiBootServicesData\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiRuntimeServicesCode\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiRuntimeServicesData\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiConventionalMemory\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiUnusableMemory\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiACPIReclaimMemory\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiACPIMemoryNVS\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiMemoryMappedIO\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiMemoryMappedIOPortSpace\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType },  // EfiPalCode\r
+  { 0, EFI_MAX_ADDRESS, 0, EfiMaxMemoryType }   // EfiMaxMemoryType\r
+};\r
+\r
+EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = EFI_MAX_ADDRESS;\r
+\r
+EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {\r
+  { EfiReservedMemoryType,      0 },\r
+  { EfiLoaderCode,              0 },\r
+  { EfiLoaderData,              0 },\r
+  { EfiBootServicesCode,        0 },\r
+  { EfiBootServicesData,        0 },\r
+  { EfiRuntimeServicesCode,     0 },\r
+  { EfiRuntimeServicesData,     0 },\r
+  { EfiConventionalMemory,      0 },\r
+  { EfiUnusableMemory,          0 },\r
+  { EfiACPIReclaimMemory,       0 },\r
+  { EfiACPIMemoryNVS,           0 },\r
+  { EfiMemoryMappedIO,          0 },\r
+  { EfiMemoryMappedIOPortSpace, 0 },\r
+  { EfiPalCode,                 0 },\r
+  { EfiMaxMemoryType,           0 }\r
+};\r
+\r
+//\r
+// Internal prototypes\r
+//\r
+STATIC\r
+VOID \r
+PromoteMemoryResource (\r
+  VOID\r
+);\r
+\r
+STATIC\r
+VOID\r
+CoreAddRange (\r
+  IN EFI_MEMORY_TYPE          Type,\r
+  IN EFI_PHYSICAL_ADDRESS     Start,\r
+  IN EFI_PHYSICAL_ADDRESS     End,\r
+  IN UINT64                   Attribute\r
+  );\r
+\r
+STATIC\r
+VOID\r
+CoreFreeMemoryMapStack (\r
+  VOID\r
+  );\r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreConvertPages (\r
+  IN UINT64           Start,\r
+  IN UINT64           NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType\r
+  );\r
+\r
+STATIC\r
+VOID\r
+RemoveMemoryMapEntry (\r
+  MEMORY_MAP      *Entry\r
+  );\r
+  \r
+STATIC\r
+MEMORY_MAP *\r
+AllocateMemoryMapEntry (\r
+  VOID\r
+  );\r
\r
+VOID\r
+CoreAcquireMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Enter critical section by gaining lock on gMemoryLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreAcquireLock (&gMemoryLock);\r
+}\r
+\r
+\r
+VOID\r
+CoreReleaseMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Exit critical section by releasing lock on gMemoryLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreReleaseLock (&gMemoryLock);\r
+}\r
+\r
+STATIC\r
+VOID\r
+PromoteMemoryResource (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Find untested but initialized memory regions in GCD map and convert them to be DXE allocatable.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY                       *Link;\r
+  EFI_GCD_MAP_ENTRY                *Entry;\r
+\r
+  DEBUG ((EFI_D_ERROR | EFI_D_PAGE, "Promote the memory resource\n"));\r
+  \r
+  CoreAcquireGcdMemoryLock ();\r
+  \r
+  Link = mGcdMemorySpaceMap.ForwardLink;\r
+  while (Link != &mGcdMemorySpaceMap) {\r
+\r
+    Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+\r
+    if (Entry->GcdMemoryType == EfiGcdMemoryTypeReserved &&\r
+        Entry->EndAddress < EFI_MAX_ADDRESS &&\r
+        (Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) ==\r
+          (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)) {\r
+      //\r
+      // Update the GCD map\r
+      //\r
+      Entry->GcdMemoryType = EfiGcdMemoryTypeSystemMemory;\r
+      Entry->Capabilities |= EFI_MEMORY_TESTED;\r
+      Entry->ImageHandle  = gDxeCoreImageHandle;\r
+      Entry->DeviceHandle = NULL;\r
+\r
+      //\r
+      // Add to allocable system memory resource\r
+      //      \r
+\r
+      CoreAddRange (\r
+        EfiConventionalMemory, \r
+        Entry->BaseAddress, \r
+        Entry->EndAddress, \r
+        Entry->Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)\r
+        );\r
+      CoreFreeMemoryMapStack ();\r
+      \r
+    }\r
+\r
+    Link = Link->ForwardLink;\r
+  }\r
+  \r
+  CoreReleaseGcdMemoryLock ();\r
+  \r
+  return;\r
+}\r
+\r
+VOID\r
+CoreAddMemoryDescriptor (\r
+  IN EFI_MEMORY_TYPE       Type,\r
+  IN EFI_PHYSICAL_ADDRESS  Start,\r
+  IN UINT64                NumberOfPages,\r
+  IN UINT64                Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called to initialize the memory map and add descriptors to\r
+  the current descriptor list.\r
+\r
+  The first descriptor that is added must be general usable\r
+  memory as the addition allocates heap.\r
+\r
+Arguments:\r
+\r
+  Type          - The type of memory to add\r
+\r
+  Start         - The starting address in the memory range\r
+                  Must be page aligned\r
+\r
+  NumberOfPages - The number of pages in the range\r
+\r
+  Attribute     - Attributes of the memory to add\r
+\r
+Returns:\r
+\r
+  None.  The range is added to the memory map\r
+\r
+--*/\r
+{\r
+  EFI_PHYSICAL_ADDRESS        End;\r
+  EFI_STATUS                  Status;\r
+  UINTN                       Index;\r
+  UINTN                       FreeIndex;\r
+\r
+  if ((Start & EFI_PAGE_MASK) != 0) {\r
+    return;\r
+  }\r
+\r
+  if (Type >= EfiMaxMemoryType && Type <= 0x7fffffff) {\r
+    return;\r
+  }\r
+  \r
+  CoreAcquireMemoryLock ();\r
+  End = Start + LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT) - 1;\r
+  CoreAddRange (Type, Start, End, Attribute);\r
+  CoreFreeMemoryMapStack ();\r
+  CoreReleaseMemoryLock ();\r
+\r
+  //\r
+  // Check to see if the statistics for the different memory types have already been established\r
+  //\r
+  if (mMemoryTypeInformationInitialized) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array\r
+  //\r
+  for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {\r
+    //\r
+    // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
+    //\r
+    Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type);\r
+    if (Type < 0 || Type > EfiMaxMemoryType) {\r
+      continue;\r
+    }\r
+\r
+    if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
+      //\r
+      // Allocate pages for the current memory type from the top of available memory\r
+      //\r
+      Status = CoreAllocatePages (\r
+                 AllocateAnyPages,\r
+                 Type,\r
+                 gMemoryTypeInformation[Index].NumberOfPages,\r
+                 &mMemoryTypeStatistics[Type].BaseAddress\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        //\r
+        // If an error occurs allocating the pages for the current memory type, then \r
+        // free all the pages allocates for the previous memory types and return.  This\r
+        // operation with be retied when/if more memory is added to the system\r
+        //\r
+        for (FreeIndex = 0; FreeIndex < Index; FreeIndex++) {\r
+          //\r
+          // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
+          //\r
+          Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[FreeIndex].Type);\r
+          if (Type < 0 || Type > EfiMaxMemoryType) {\r
+            continue;\r
+          }\r
+\r
+          if (gMemoryTypeInformation[FreeIndex].NumberOfPages != 0) {\r
+            CoreFreePages (\r
+              mMemoryTypeStatistics[Type].BaseAddress, \r
+              gMemoryTypeInformation[FreeIndex].NumberOfPages\r
+              );\r
+            mMemoryTypeStatistics[Type].BaseAddress    = 0;\r
+            mMemoryTypeStatistics[Type].MaximumAddress = EFI_MAX_ADDRESS;\r
+          }\r
+        }\r
+        return;\r
+      }\r
+\r
+      //\r
+      // Compute the address at the top of the current statistics\r
+      //\r
+      mMemoryTypeStatistics[Type].MaximumAddress = \r
+        mMemoryTypeStatistics[Type].BaseAddress + \r
+        LShiftU64 (gMemoryTypeInformation[Index].NumberOfPages, EFI_PAGE_SHIFT) - 1;\r
+\r
+      //\r
+      // If the current base address is the lowest address so far, then update the default \r
+      // maximum address\r
+      //\r
+      if (mMemoryTypeStatistics[Type].BaseAddress < mDefaultMaximumAddress) {\r
+        mDefaultMaximumAddress = mMemoryTypeStatistics[Type].BaseAddress - 1;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // There was enough system memory for all the the memory types were allocated.  So,\r
+  // those memory areas can be freed for future allocations, and all future memory\r
+  // allocations can occur within their respective bins\r
+  //\r
+  for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {\r
+    //\r
+    // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
+    //\r
+    Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type);\r
+    if (Type < 0 || Type > EfiMaxMemoryType) {\r
+      continue;\r
+    }\r
+\r
+    if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
+      CoreFreePages (\r
+        mMemoryTypeStatistics[Type].BaseAddress, \r
+        gMemoryTypeInformation[Index].NumberOfPages\r
+        );\r
+      gMemoryTypeInformation[Index].NumberOfPages = 0;\r
+    }\r
+  }\r
+\r
+  //\r
+  // If the number of pages reserved for a memory type is 0, then all allocations for that type\r
+  // should be in the default range.\r
+  //\r
+  for (Type = (EFI_MEMORY_TYPE) 0; Type < EfiMaxMemoryType; Type++) {\r
+    for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {\r
+      if (Type == (EFI_MEMORY_TYPE)gMemoryTypeInformation[Index].Type) {\r
+        mMemoryTypeStatistics[Type].InformationIndex = Index;\r
+      }\r
+    }\r
+    mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0;\r
+    if (mMemoryTypeStatistics[Type].MaximumAddress == EFI_MAX_ADDRESS) {\r
+      mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress;\r
+    }\r
+  }\r
+\r
+  mMemoryTypeInformationInitialized = TRUE;\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+CoreAddRange (\r
+  IN EFI_MEMORY_TYPE          Type,\r
+  IN EFI_PHYSICAL_ADDRESS     Start,\r
+  IN EFI_PHYSICAL_ADDRESS     End,\r
+  IN UINT64                   Attribute\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Adds a ranges to the memory map.\r
+  The range must not already exist in the map.\r
+\r
+Arguments:\r
+\r
+  Type    - The type of memory range to add\r
+\r
+  Start   - The starting address in the memory range\r
+            Must be paged aligned\r
+\r
+  End     - The last address in the range\r
+          Must be the last byte of a page\r
+\r
+  Attribute - The attributes of the memory range to add\r
+\r
+Returns:\r
+\r
+  None.  The range is added to the memory map\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY        *Link;\r
+  MEMORY_MAP        *Entry;\r
+\r
+  ASSERT ((Start & EFI_PAGE_MASK) == 0);\r
+  ASSERT (End > Start) ;\r
+\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+  \r
+  DEBUG ((EFI_D_PAGE, "AddRange: %lx-%lx to %d\n", Start, End, Type));\r
+\r
+  //\r
+  // Memory map being altered so updated key\r
+  //\r
+  mMemoryMapKey += 1;\r
+\r
+  //\r
+  // UEFI 2.0 added an event group for notificaiton on memory map changes.\r
+  // So we need to signal this Event Group every time the memory map changes.\r
+  // If we are in EFI 1.10 compatability mode no event groups will be \r
+  // found and nothing will happen we we call this function. These events\r
+  // will get signaled but since a lock is held around the call to this \r
+  // function the notificaiton events will only be called after this funciton\r
+  // returns and the lock is released.\r
+  //\r
+  CoreNotifySignalList (&gEfiEventMemoryMapChangeGuid);\r
+\r
+  //\r
+  // Look for adjoining memory descriptor\r
+  //\r
+  \r
+  // Two memory descriptors can only be merged if they have the same Type\r
+  // and the same Attribute\r
+  //\r
+\r
+  Link = gMemoryMap.ForwardLink;\r
+  while (Link != &gMemoryMap) {\r
+    Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+    Link  = Link->ForwardLink;\r
+\r
+    if (Entry->Type != Type) {\r
+      continue;\r
+    }\r
+\r
+    if (Entry->Attribute != Attribute) {\r
+      continue;\r
+    }\r
+\r
+    if (Entry->End + 1 == Start) {\r
+      \r
+      Start = Entry->Start;\r
+      RemoveMemoryMapEntry (Entry);\r
+\r
+    } else if (Entry->Start == End + 1) {\r
+      \r
+      End = Entry->End;\r
+      RemoveMemoryMapEntry (Entry);\r
+    }\r
+  }\r
+\r
+  //\r
+  // Add descriptor \r
+  //\r
+\r
+  mMapStack[mMapDepth].Signature     = MEMORY_MAP_SIGNATURE;\r
+  mMapStack[mMapDepth].FromPages      = FALSE;\r
+  mMapStack[mMapDepth].Type          = Type;\r
+  mMapStack[mMapDepth].Start         = Start;\r
+  mMapStack[mMapDepth].End           = End;\r
+  mMapStack[mMapDepth].VirtualStart  = 0;\r
+  mMapStack[mMapDepth].Attribute     = Attribute;\r
+  InsertTailList (&gMemoryMap, &mMapStack[mMapDepth].Link);\r
+\r
+  mMapDepth += 1;\r
+  ASSERT (mMapDepth < MAX_MAP_DEPTH);\r
+\r
+  return ;\r
+}\r
+\r
+STATIC\r
+VOID\r
+CoreFreeMemoryMapStack (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Moves any memory descriptors that are on the\r
+  temporary descriptor stack to heap.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  MEMORY_MAP      *Entry;\r
+  MEMORY_MAP      *Entry2;\r
+  LIST_ENTRY      *Link2;\r
+\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+\r
+  //\r
+  // If already freeing the map stack, then return\r
+  //\r
+  if (mFreeMapStack) {\r
+    return ;\r
+  }\r
+\r
+  //\r
+  // Move the temporary memory descriptor stack into pool\r
+  //\r
+  mFreeMapStack += 1;\r
+\r
+  while (mMapDepth) {\r
+    //\r
+    // Deque an memory map entry from mFreeMemoryMapEntryList \r
+    //\r
+    Entry = AllocateMemoryMapEntry ();\r
+    \r
+    ASSERT (Entry);\r
+\r
+    //\r
+    // Update to proper entry\r
+    //\r
+    mMapDepth -= 1;\r
+\r
+    if (mMapStack[mMapDepth].Link.ForwardLink != NULL) {\r
+\r
+      //\r
+      // Move this entry to general memory\r
+      //\r
+      RemoveEntryList (&mMapStack[mMapDepth].Link);\r
+      mMapStack[mMapDepth].Link.ForwardLink = NULL;\r
+\r
+      CopyMem (Entry , &mMapStack[mMapDepth], sizeof (MEMORY_MAP));\r
+      Entry->FromPages = TRUE;\r
+\r
+      //\r
+      // Find insertion location\r
+      //\r
+      for (Link2 = gMemoryMap.ForwardLink; Link2 != &gMemoryMap; Link2 = Link2->ForwardLink) {\r
+        Entry2 = CR (Link2, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+        if (Entry2->FromPages && Entry2->Start > Entry->Start) {\r
+          break;\r
+        }\r
+      }\r
+\r
+      InsertTailList (Link2, &Entry->Link);\r
+\r
+    } else {\r
+      // \r
+      // This item of mMapStack[mMapDepth] has already been dequeued from gMemoryMap list,\r
+      // so here no need to move it to memory.\r
+      //\r
+      InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
+    }\r
+  }\r
+\r
+  mFreeMapStack -= 1;\r
+}\r
+\r
+STATIC\r
+VOID\r
+RemoveMemoryMapEntry (\r
+  MEMORY_MAP      *Entry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Removes a descriptor entry.\r
+\r
+Arguments:\r
+\r
+  Entry   - The entry to remove\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  RemoveEntryList (&Entry->Link);\r
+  Entry->Link.ForwardLink = NULL;\r
+\r
+  if (Entry->FromPages) {\r
+       //\r
+       // Insert the free memory map descriptor to the end of mFreeMemoryMapEntryList\r
+       //\r
+    InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
+  }\r
+}\r
+\r
+STATIC\r
+MEMORY_MAP *\r
+AllocateMemoryMapEntry (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Deque a descriptor entry from the mFreeMemoryMapEntryList.\r
+  If the list is emtry, then allocate a new page to refuel the list. \r
+  Please Note this algorithm to allocate the memory map descriptor has a property\r
+  that the memory allocated for memory entries always grows, and will never really be freed \r
+  For example, if the current boot uses 2000 memory map entries at the maximum point, but\r
+  ends up with only 50 at the time the OS is booted, then the memory associated with the 1950 \r
+  memory map entries is still allocated from EfiBootServicesMemory.  \r
+\r
+Arguments:\r
+\r
+  NONE\r
+\r
+Returns:\r
+\r
+  The Memory map descriptor dequed from the mFreeMemoryMapEntryList\r
+\r
+--*/ \r
+{\r
+  MEMORY_MAP*            FreeDescriptorEntries;\r
+  MEMORY_MAP*            Entry;\r
+  UINTN                  Index;\r
+  \r
+  if (IsListEmpty (&mFreeMemoryMapEntryList)) {\r
+    // \r
+    // The list is empty, to allocate one page to refuel the list\r
+    //\r
+    FreeDescriptorEntries = CoreAllocatePoolPages (EfiBootServicesData, EFI_SIZE_TO_PAGES(DEFAULT_PAGE_ALLOCATION), DEFAULT_PAGE_ALLOCATION);\r
+    if(FreeDescriptorEntries != NULL) {\r
+      //\r
+      // Enque the free memmory map entries into the list\r
+      //\r
+      for (Index = 0; Index< DEFAULT_PAGE_ALLOCATION / sizeof(MEMORY_MAP); Index++) {\r
+        FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE;\r
+        InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link);\r
+      }     \r
+    } else {\r
+      return NULL;\r
+    }\r
+  }\r
+  //\r
+  // dequeue the first descriptor from the list\r
+  //\r
+  Entry = CR (mFreeMemoryMapEntryList.ForwardLink, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+  RemoveEntryList (&Entry->Link);\r
+  \r
+  return Entry;\r
+}    \r
+\r
+STATIC\r
+EFI_STATUS\r
+CoreConvertPages (\r
+  IN UINT64           Start,\r
+  IN UINT64           NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Converts a memory range to the specified type.\r
+  The range must exist in the memory map.\r
+\r
+Arguments:\r
+\r
+  Start         - The first address of the range\r
+                  Must be page aligned\r
+\r
+  NumberOfPages - The number of pages to convert\r
+\r
+  NewType       - The new type for the memory range\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER   - Invalid parameter\r
+  \r
+  EFI_NOT_FOUND           - Could not find a descriptor cover the specified range \r
+                            or convertion not allowed.\r
+  \r
+  EFI_SUCCESS             - Successfully converts the memory range to the specified type.\r
+\r
+--*/\r
+{\r
+\r
+  UINT64          NumberOfBytes;\r
+  UINT64          End;\r
+  UINT64          RangeEnd;\r
+  UINT64          Attribute;\r
+  LIST_ENTRY      *Link;\r
+  MEMORY_MAP      *Entry;\r
+\r
+  Entry = NULL;\r
+  NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT);\r
+  End = Start + NumberOfBytes - 1;\r
+\r
+  ASSERT (NumberOfPages);\r
+  ASSERT ((Start & EFI_PAGE_MASK) == 0);\r
+  ASSERT (End > Start) ;\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+\r
+  if (NumberOfPages == 0 || (Start & EFI_PAGE_MASK ) || (Start > (Start + NumberOfBytes))) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Convert the entire range\r
+  //\r
+\r
+  while (Start < End) {\r
+\r
+    //\r
+    // Find the entry that the covers the range\r
+    //\r
+    for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+      Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+\r
+      if (Entry->Start <= Start && Entry->End > Start) {\r
+        break;\r
+      }\r
+    }\r
+\r
+    if (Link == &gMemoryMap) {\r
+      DEBUG ((EFI_D_ERROR | EFI_D_PAGE, "ConvertPages: failed to find range %lx - %lx\n", Start, End));\r
+      return EFI_NOT_FOUND;\r
+    }\r
+\r
+    //\r
+    // Convert range to the end, or to the end of the descriptor\r
+    // if that's all we've got\r
+    //\r
+    RangeEnd = End;\r
+    if (Entry->End < End) {\r
+      RangeEnd = Entry->End;\r
+    }\r
+\r
+    DEBUG ((EFI_D_PAGE, "ConvertRange: %lx-%lx to %d\n", Start, RangeEnd, NewType));\r
+\r
+    //\r
+    // Debug code - verify conversion is allowed\r
+    //\r
+    if (!(NewType == EfiConventionalMemory ? 1 : 0) ^ (Entry->Type == EfiConventionalMemory ? 1 : 0)) {\r
+      DEBUG ((EFI_D_ERROR , "ConvertPages: Incompatible memory types\n"));\r
+      return EFI_NOT_FOUND;\r
+    }  \r
+\r
+    //\r
+    // Update counters for the number of pages allocated to each memory type\r
+    //\r
+    if (Entry->Type >= 0 && Entry->Type < EfiMaxMemoryType) {\r
+      if (Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress && \r
+          Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) {\r
+        if (NumberOfPages > mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages) {\r
+          mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages = 0;\r
+        } else {\r
+          mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages -= NumberOfPages;\r
+        }\r
+      }\r
+    }\r
+\r
+    if (NewType >= 0 && NewType < EfiMaxMemoryType) {\r
+      if (Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
+        mMemoryTypeStatistics[NewType].CurrentNumberOfPages += NumberOfPages;\r
+        if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages > \r
+            gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) {\r
+          gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages = (UINT32)mMemoryTypeStatistics[NewType].CurrentNumberOfPages;\r
+        }\r
+      }\r
+    }\r
+\r
+    //\r
+    // Pull range out of descriptor\r
+    //\r
+    if (Entry->Start == Start) {\r
+      \r
+      //\r
+      // Clip start\r
+      //\r
+      Entry->Start = RangeEnd + 1;\r
+\r
+    } else if (Entry->End == RangeEnd) {\r
+      \r
+      //\r
+      // Clip end\r
+      //\r
+      Entry->End = Start - 1;\r
+\r
+    } else {\r
+\r
+      //\r
+      // Pull it out of the center, clip current\r
+      //\r
+      \r
+      //\r
+      // Add a new one\r
+      //\r
+      mMapStack[mMapDepth].Signature = MEMORY_MAP_SIGNATURE;\r
+      mMapStack[mMapDepth].FromPages  = FALSE;\r
+      mMapStack[mMapDepth].Type      = Entry->Type;\r
+      mMapStack[mMapDepth].Start     = RangeEnd+1;\r
+      mMapStack[mMapDepth].End       = Entry->End;\r
+\r
+      //\r
+      // Inherit Attribute from the Memory Descriptor that is being clipped\r
+      //\r
+      mMapStack[mMapDepth].Attribute = Entry->Attribute;\r
+\r
+      Entry->End = Start - 1;\r
+      ASSERT (Entry->Start < Entry->End);\r
+\r
+      Entry = &mMapStack[mMapDepth];\r
+      InsertTailList (&gMemoryMap, &Entry->Link);\r
+\r
+      mMapDepth += 1;\r
+      ASSERT (mMapDepth < MAX_MAP_DEPTH);\r
+    }\r
+\r
+    //\r
+    // The new range inherits the same Attribute as the Entry \r
+    //it is being cut out of\r
+    //\r
+    Attribute = Entry->Attribute;\r
+\r
+    //\r
+    // If the descriptor is empty, then remove it from the map\r
+    //\r
+    if (Entry->Start == Entry->End + 1) {\r
+      RemoveMemoryMapEntry (Entry);\r
+      Entry = NULL;\r
+    }\r
+    \r
+    //\r
+    // Add our new range in\r
+    //\r
+    CoreAddRange (NewType, Start, RangeEnd, Attribute);\r
+\r
+    //\r
+    // Move any map descriptor stack to general pool\r
+    //\r
+    CoreFreeMemoryMapStack ();\r
+\r
+    //\r
+    // Bump the starting address, and convert the next range\r
+    //\r
+    Start = RangeEnd + 1;\r
+  }\r
+\r
+  //\r
+  // Converted the whole range, done\r
+  //\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+STATIC\r
+UINT64\r
+CoreFindFreePagesI (\r
+  IN UINT64           MaxAddress,\r
+  IN UINT64           NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType,\r
+  IN UINTN            Alignment\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function. Finds a consecutive free page range below\r
+  the requested address.\r
+\r
+Arguments:\r
+\r
+  MaxAddress    - The address that the range must be below\r
+\r
+  NumberOfPages - Number of pages needed\r
+\r
+  NewType       - The type of memory the range is going to be turned into\r
+\r
+  Alignment     - Bits to align with\r
+\r
+Returns:\r
+\r
+  The base address of the range, or 0 if the range was not found\r
+\r
+--*/\r
+{\r
+  UINT64          NumberOfBytes;\r
+  UINT64          Target;\r
+  UINT64          DescStart;\r
+  UINT64          DescEnd;\r
+  UINT64          DescNumberOfBytes;\r
+  LIST_ENTRY      *Link;\r
+  MEMORY_MAP      *Entry;\r
+\r
+  if ((MaxAddress < EFI_PAGE_MASK) ||(NumberOfPages == 0)) {\r
+    return 0;\r
+  }\r
+\r
+  if ((MaxAddress & EFI_PAGE_MASK) != EFI_PAGE_MASK) {\r
+    \r
+    //\r
+    // If MaxAddress is not aligned to the end of a page\r
+    //\r
+    \r
+    //\r
+    // Change MaxAddress to be 1 page lower\r
+    //\r
+    MaxAddress -= (EFI_PAGE_MASK + 1);\r
+    \r
+    //\r
+    // Set MaxAddress to a page boundary\r
+    //\r
+    MaxAddress &= ~EFI_PAGE_MASK;\r
+    \r
+    //\r
+    // Set MaxAddress to end of the page\r
+    //\r
+    MaxAddress |= EFI_PAGE_MASK;\r
+  }\r
+\r
+  NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT);\r
+  Target = 0;\r
+\r
+  for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+    Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+  \r
+    //\r
+    // If it's not a free entry, don't bother with it\r
+    //\r
+    if (Entry->Type != EfiConventionalMemory) {\r
+      continue;\r
+    }\r
+\r
+    DescStart = Entry->Start;\r
+    DescEnd = Entry->End;\r
+\r
+    //\r
+    // If desc is past max allowed address, skip it\r
+    //\r
+    if (DescStart >= MaxAddress) {\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // If desc ends past max allowed address, clip the end\r
+    //\r
+    if (DescEnd >= MaxAddress) {\r
+      DescEnd = MaxAddress;\r
+    }\r
+\r
+    DescEnd = ((DescEnd + 1) & (~(Alignment - 1))) - 1;\r
+\r
+    //\r
+    // Compute the number of bytes we can used from this \r
+    // descriptor, and see it's enough to satisfy the request\r
+    //\r
+    DescNumberOfBytes = DescEnd - DescStart + 1;\r
+\r
+    if (DescNumberOfBytes >= NumberOfBytes) {\r
+\r
+      //\r
+      // If this is the best match so far remember it\r
+      //\r
+      if (DescEnd > Target) {\r
+        Target = DescEnd;\r
+      }\r
+    }\r
+  }          \r
+\r
+  //\r
+  // If this is a grow down, adjust target to be the allocation base\r
+  //\r
+  Target -= NumberOfBytes - 1;\r
+\r
+  //\r
+  // If we didn't find a match, return 0\r
+  //\r
+  if ((Target & EFI_PAGE_MASK) != 0) {\r
+    return 0;\r
+  }\r
+\r
+  return Target;\r
+}\r
+\r
+STATIC\r
+UINT64\r
+FindFreePages (\r
+    IN UINT64           MaxAddress,\r
+    IN UINT64           NoPages,\r
+    IN EFI_MEMORY_TYPE  NewType,\r
+    IN UINTN            Alignment\r
+    )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+    Internal function.  Finds a consecutive free page range below\r
+    the requested address\r
+\r
+Arguments:\r
+\r
+    MaxAddress          - The address that the range must be below\r
+\r
+    NoPages             - Number of pages needed\r
+\r
+    NewType             - The type of memory the range is going to be turned into\r
+\r
+    Alignment           - Bits to align with\r
+\r
+Returns:\r
+\r
+    The base address of the range, or 0 if the range was not found.\r
+\r
+--*/\r
+{\r
+  UINT64  NewMaxAddress;\r
+  UINT64  Start;\r
+\r
+  NewMaxAddress = MaxAddress;\r
+\r
+  if (NewType >= 0 && NewType < EfiMaxMemoryType && NewMaxAddress >= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
+    NewMaxAddress  = mMemoryTypeStatistics[NewType].MaximumAddress;\r
+  } else {\r
+    if (NewMaxAddress > mDefaultMaximumAddress) {\r
+      NewMaxAddress  = mDefaultMaximumAddress;\r
+    }\r
+  }\r
+\r
+  Start = CoreFindFreePagesI (NewMaxAddress, NoPages, NewType, Alignment);\r
+  if (!Start) {\r
+    Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
+    if (!Start) {\r
+      //\r
+      // Here means there may be no enough memory to use, so try to go through\r
+      // all the memory descript to promote the untested memory directly\r
+      //\r
+      PromoteMemoryResource ();\r
+\r
+      //\r
+      // Allocate memory again after the memory resource re-arranged\r
+      //\r
+      Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
+    }\r
+  }\r
+\r
+  return Start;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreAllocatePages (\r
+  IN EFI_ALLOCATE_TYPE      Type,\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN UINTN                  NumberOfPages,\r
+  IN OUT EFI_PHYSICAL_ADDRESS  *Memory\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocates pages from the memory map.\r
+\r
+Arguments:\r
+\r
+  Type          - The type of allocation to perform\r
+\r
+  MemoryType    - The type of memory to turn the allocated pages into\r
+\r
+  NumberOfPages - The number of pages to allocate\r
+\r
+  Memory        - A pointer to receive the base allocated memory address\r
+\r
+Returns:\r
+\r
+  Status. On success, Memory is filled in with the base address allocated\r
+\r
+  EFI_INVALID_PARAMETER     - Parameters violate checking rules defined in spec.\r
+  \r
+  EFI_NOT_FOUND             - Could not allocate pages match the requirement.\r
+  \r
+  EFI_OUT_OF_RESOURCES      - No enough pages to allocate.\r
+  \r
+  EFI_SUCCESS               - Pages successfully allocated.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS      Status;\r
+  UINT64          Start;\r
+  UINT64          MaxAddress;\r
+  UINTN           Alignment;\r
+\r
+  if (Type < AllocateAnyPages || Type >= (UINTN) MaxAllocateType) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if ((MemoryType >= EfiMaxMemoryType && MemoryType <= 0x7fffffff) ||\r
+       MemoryType == EfiConventionalMemory) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
+\r
+  if  (MemoryType == EfiACPIReclaimMemory   ||\r
+       MemoryType == EfiACPIMemoryNVS       ||\r
+       MemoryType == EfiRuntimeServicesCode ||\r
+       MemoryType == EfiRuntimeServicesData) {\r
+\r
+    Alignment = EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT;\r
+  }\r
+\r
+  if (Type == AllocateAddress) {\r
+    if ((*Memory & (Alignment - 1)) != 0) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+  }\r
+\r
+  NumberOfPages += EFI_SIZE_TO_PAGES (Alignment) - 1;\r
+  NumberOfPages &= ~(EFI_SIZE_TO_PAGES (Alignment) - 1);\r
+\r
+  //\r
+  // If this is for below a particular address, then \r
+  //\r
+  Start = *Memory;\r
+  \r
+  //\r
+  // The max address is the max natively addressable address for the processor\r
+  //\r
+  MaxAddress = EFI_MAX_ADDRESS;\r
+  \r
+  if (Type == AllocateMaxAddress) {\r
+    MaxAddress = Start;\r
+  }\r
+\r
+  CoreAcquireMemoryLock ();\r
+  \r
+  //\r
+  // If not a specific address, then find an address to allocate\r
+  //\r
+  if (Type != AllocateAddress) {\r
+    Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment);\r
+    if (Start == 0) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto Done;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Convert pages from FreeMemory to the requested type\r
+  //\r
+  Status = CoreConvertPages (Start, NumberOfPages, MemoryType);\r
+\r
+Done:\r
+  CoreReleaseMemoryLock ();\r
+\r
+  if (!EFI_ERROR (Status)) {\r
+    *Memory = Start;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+\r
+EFI_STATUS \r
+EFIAPI\r
+CoreFreePages (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees previous allocated pages.\r
+\r
+Arguments:\r
+\r
+  Memory        - Base address of memory being freed\r
+\r
+  NumberOfPages - The number of pages to free\r
+\r
+Returns:\r
+\r
+  EFI_NOT_FOUND       - Could not find the entry that covers the range\r
+  \r
+  EFI_INVALID_PARAMETER   - Address not aligned\r
+  \r
+  EFI_SUCCESS         -Pages successfully freed.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS      Status;\r
+  LIST_ENTRY      *Link;\r
+  MEMORY_MAP      *Entry;\r
+  UINTN           Alignment;\r
+\r
+  //\r
+  // Free the range\r
+  //\r
+  CoreAcquireMemoryLock ();\r
+\r
+  //\r
+  // Find the entry that the covers the range\r
+  //\r
+  Entry = NULL;\r
+  for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+    Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+    if (Entry->Start <= Memory && Entry->End > Memory) {\r
+        break;\r
+    }\r
+  }\r
+  if (Link == &gMemoryMap) {\r
+    CoreReleaseMemoryLock ();\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
+\r
+  if  (Entry->Type == EfiACPIReclaimMemory   ||\r
+       Entry->Type == EfiACPIMemoryNVS       ||\r
+       Entry->Type == EfiRuntimeServicesCode ||\r
+       Entry->Type == EfiRuntimeServicesData) {\r
+\r
+    Alignment = EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT;\r
+\r
+  }\r
+\r
+  if ((Memory & (Alignment - 1)) != 0) {\r
+    CoreReleaseMemoryLock ();\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  NumberOfPages += EFI_SIZE_TO_PAGES (Alignment) - 1;\r
+  NumberOfPages &= ~(EFI_SIZE_TO_PAGES (Alignment) - 1);\r
+\r
+  Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
+\r
+  CoreReleaseMemoryLock ();\r
+\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Destroy the contents\r
+  //\r
+  if (Memory < EFI_MAX_ADDRESS) {\r
+    DEBUG_CLEAR_MEMORY ((VOID *)(UINTN)Memory, NumberOfPages << EFI_PAGE_SHIFT);\r
+  }\r
+  \r
+  return Status;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreGetMemoryMap (\r
+  IN OUT UINTN                  *MemoryMapSize,\r
+  IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,\r
+  OUT UINTN                     *MapKey,\r
+  OUT UINTN                     *DescriptorSize,\r
+  OUT UINT32                    *DescriptorVersion\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  This function returns a copy of the current memory map. The map is an array of \r
+  memory descriptors, each of which describes a contiguous block of memory.\r
+\r
+Arguments:\r
+\r
+  MemoryMapSize     - A pointer to the size, in bytes, of the MemoryMap buffer. On\r
+                      input, this is the size of the buffer allocated by the caller. \r
+                      On output, it is the size of the buffer returned by the firmware \r
+                      if the buffer was large enough, or the size of the buffer needed \r
+                      to contain the map if the buffer was too small.\r
+  MemoryMap         - A pointer to the buffer in which firmware places the current memory map.\r
+  MapKey            - A pointer to the location in which firmware returns the key for the\r
+                      current memory map.\r
+  DescriptorSize    - A pointer to the location in which firmware returns the size, in\r
+                      bytes, of an individual EFI_MEMORY_DESCRIPTOR.\r
+  DescriptorVersion - A pointer to the location in which firmware returns the version\r
+                      number associated with the EFI_MEMORY_DESCRIPTOR.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS           - The memory map was returned in the MemoryMap buffer.       \r
+  EFI_BUFFER_TOO_SMALL  - The MemoryMap buffer was too small. The current buffer size\r
+                          needed to hold the memory map is returned in MemoryMapSize.\r
+  EFI_INVALID_PARAMETER - One of the parameters has an invalid value.                \r
+\r
+--*/\r
+{\r
+  EFI_STATUS                        Status;\r
+  UINTN                             Size;  \r
+  UINTN                             BufferSize;  \r
+  UINTN                             NumberOfRuntimeEntries;\r
+  LIST_ENTRY                        *Link;\r
+  MEMORY_MAP                        *Entry;  \r
+  EFI_GCD_MAP_ENTRY                 *GcdMapEntry;  \r
+\r
+  //\r
+  // Make sure the parameters are valid\r
+  //\r
+  if (MemoryMapSize == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  CoreAcquireGcdMemoryLock ();\r
+  \r
+  //\r
+  // Count the number of Reserved and MMIO entries that are marked for runtime use\r
+  //\r
+  NumberOfRuntimeEntries = 0;\r
+  for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
+    GcdMapEntry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
+        (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
+      if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\r
+        NumberOfRuntimeEntries++;\r
+      }\r
+    }\r
+  }\r
+\r
+  Size = sizeof (EFI_MEMORY_DESCRIPTOR);\r
+\r
+  //\r
+  // Make sure Size != sizeof(EFI_MEMORY_DESCRIPTOR). This will\r
+  // prevent people from having pointer math bugs in their code.\r
+  // now you have to use *DescriptorSize to make things work.\r
+  //\r
+  Size += sizeof(UINT64) - (Size % sizeof (UINT64));\r
+\r
+  if (DescriptorSize != NULL) {\r
+    *DescriptorSize = Size;\r
+  }\r
+  \r
+  if (DescriptorVersion != NULL) {\r
+    *DescriptorVersion = EFI_MEMORY_DESCRIPTOR_VERSION;\r
+  }\r
+\r
+  CoreAcquireMemoryLock ();\r
+\r
+  //\r
+  // Compute the buffer size needed to fit the entire map\r
+  //\r
+  BufferSize = Size * NumberOfRuntimeEntries;\r
+  for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+    BufferSize += Size;\r
+  }\r
+\r
+  if (*MemoryMapSize < BufferSize) {\r
+    Status = EFI_BUFFER_TOO_SMALL;\r
+    goto Done;\r
+  }\r
+\r
+  if (MemoryMap == NULL) {\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Build the map\r
+  //\r
+  ZeroMem (MemoryMap, Size);\r
+  for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+    Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+    ASSERT (Entry->VirtualStart == 0);\r
+\r
+    MemoryMap->Type           = Entry->Type;\r
+    MemoryMap->PhysicalStart  = Entry->Start;\r
+    MemoryMap->VirtualStart   = Entry->VirtualStart;\r
+    MemoryMap->NumberOfPages  = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT);\r
+  \r
+    switch (Entry->Type) {\r
+    case EfiRuntimeServicesCode:\r
+    case EfiRuntimeServicesData:\r
+    case EfiPalCode:\r
+      MemoryMap->Attribute = Entry->Attribute | EFI_MEMORY_RUNTIME;\r
+      break;\r
+\r
+    default:\r
+      MemoryMap->Attribute = Entry->Attribute;\r
+      break;\r
+    }\r
+    \r
+    MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+  }\r
+\r
+  for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
+    GcdMapEntry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+    if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
+        (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
+      if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\r
+        \r
+        MemoryMap->PhysicalStart = GcdMapEntry->BaseAddress;\r
+        MemoryMap->VirtualStart  = 0;\r
+        MemoryMap->NumberOfPages = RShiftU64 ((GcdMapEntry->EndAddress - GcdMapEntry->BaseAddress + 1), EFI_PAGE_SHIFT);\r
+        MemoryMap->Attribute     = GcdMapEntry->Attributes & ~EFI_MEMORY_PORT_IO;\r
+\r
+        if (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) {\r
+          MemoryMap->Type = EfiReservedMemoryType;\r
+        } else if (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) {\r
+          if ((GcdMapEntry->Attributes & EFI_MEMORY_PORT_IO) == EFI_MEMORY_PORT_IO) {\r
+            MemoryMap->Type = EfiMemoryMappedIOPortSpace;\r
+          } else {\r
+            MemoryMap->Type = EfiMemoryMappedIO;\r
+          }\r
+        }\r
+\r
+        MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+      }\r
+    }\r
+  }\r
+  \r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\r
+\r
+  CoreReleaseMemoryLock ();\r
+  \r
+  CoreReleaseGcdMemoryLock ();\r
+  \r
+  // \r
+  // Update the map key finally \r
+  // \r
+  if (MapKey != NULL) {\r
+    *MapKey = mMemoryMapKey;\r
+  }\r
+  \r
+  *MemoryMapSize = BufferSize;\r
+  \r
+  return Status;\r
+}\r
+\r
+VOID *\r
+CoreAllocatePoolPages (\r
+  IN EFI_MEMORY_TYPE    PoolType,\r
+  IN UINTN              NumberOfPages,\r
+  IN UINTN              Alignment\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Used by the pool functions to allocate pages\r
+  to back pool allocation requests.\r
+\r
+Arguments:\r
+\r
+  PoolType      - The type of memory for the new pool pages\r
+\r
+  NumberOfPages - No of pages to allocate\r
+\r
+  Alignment     - Bits to align.\r
+\r
+Returns:\r
+\r
+  The allocated memory, or NULL\r
+\r
+--*/\r
+{\r
+  UINT64            Start;\r
+\r
+  //\r
+  // Find the pages to convert\r
+  //\r
+  Start = FindFreePages (EFI_MAX_ADDRESS, NumberOfPages, PoolType, Alignment);\r
+\r
+  //\r
+  // Convert it to boot services data\r
+  //\r
+  if (Start == 0) {\r
+    DEBUG ((EFI_D_ERROR | EFI_D_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", NumberOfPages));\r
+  } else {\r
+    CoreConvertPages (Start, NumberOfPages, PoolType);\r
+  }\r
+\r
+  return (VOID *)(UINTN)Start;\r
+}\r
+\r
+VOID\r
+CoreFreePoolPages (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Frees pool pages allocated via AllocatePoolPages ()\r
+\r
+Arguments:\r
+\r
+  Memory        - The base address to free\r
+\r
+  NumberOfPages - The number of pages to free\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreTerminateMemoryMap (\r
+  IN UINTN          MapKey\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Make sure the memory map is following all the construction rules, \r
+  it is the last time to check memory map error before exit boot services.\r
+\r
+Arguments:\r
+\r
+  MapKey        - Memory map key\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER       - Memory map not consistent with construction rules.\r
+  \r
+  EFI_SUCCESS                 - Valid memory map.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS        Status;\r
+  LIST_ENTRY        *Link;\r
+  MEMORY_MAP        *Entry;\r
+\r
+  Status = EFI_SUCCESS;\r
+\r
+  CoreAcquireMemoryLock ();\r
+\r
+  if (MapKey == mMemoryMapKey) {\r
+\r
+    //\r
+    // Make sure the memory map is following all the construction rules\r
+    // This is the last chance we will be able to display any messages on\r
+    // the  console devices.\r
+    //\r
+\r
+    for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
+      Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+      if (Entry->Attribute & EFI_MEMORY_RUNTIME) { \r
+        if (Entry->Type == EfiACPIReclaimMemory || Entry->Type == EfiACPIMemoryNVS) {\r
+          DEBUG((EFI_D_ERROR, "ExitBootServices: ACPI memory entry has RUNTIME attribute set.\n"));\r
+          CoreReleaseMemoryLock ();\r
+          return EFI_INVALID_PARAMETER;\r
+        }\r
+        if (Entry->Start & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
+          DEBUG((EFI_D_ERROR, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
+          CoreReleaseMemoryLock ();\r
+          return EFI_INVALID_PARAMETER;\r
+        }\r
+        if ((Entry->End + 1) & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
+          DEBUG((EFI_D_ERROR, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
+          CoreReleaseMemoryLock ();\r
+          return EFI_INVALID_PARAMETER;\r
+        }\r
+      }\r
+    }\r
+\r
+    //\r
+    // The map key they gave us matches what we expect. Fall through and\r
+    // return success. In an ideal world we would clear out all of\r
+    // EfiBootServicesCode and EfiBootServicesData. However this function\r
+    // is not the last one called by ExitBootServices(), so we have to\r
+    // preserve the memory contents.\r
+    //\r
+  } else {\r
+    Status = EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreReleaseMemoryLock ();\r
+\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Mem/memdata.c b/MdeModulePkg/Core/Dxe/Mem/memdata.c
new file mode 100644 (file)
index 0000000..83a130d
--- /dev/null
@@ -0,0 +1,41 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  memdata.c\r
+\r
+Abstract:\r
+\r
+  Global data used in memory service\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+//\r
+// MemoryLock - synchronizes access to the memory map and pool lists\r
+//\r
+EFI_LOCK          gMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
+\r
+//\r
+// MemoryMap - the current memory map\r
+//\r
+LIST_ENTRY        gMemoryMap  = INITIALIZE_LIST_HEAD_VARIABLE (gMemoryMap);\r
+\r
+//\r
+// MemoryLastConvert - the last memory descriptor used for a conversion request\r
+//\r
+MEMORY_MAP        *gMemoryLastConvert;\r
diff --git a/MdeModulePkg/Core/Dxe/Mem/pool.c b/MdeModulePkg/Core/Dxe/Mem/pool.c
new file mode 100644 (file)
index 0000000..c024f03
--- /dev/null
@@ -0,0 +1,613 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  pool.c\r
+\r
+Abstract:\r
+\r
+  EFI Memory pool management\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define POOL_FREE_SIGNATURE   EFI_SIGNATURE_32('p','f','r','0')\r
+typedef struct {\r
+  UINT32          Signature;\r
+  UINT32          Index;\r
+  LIST_ENTRY      Link;\r
+} POOL_FREE;\r
+\r
+\r
+#define POOL_HEAD_SIGNATURE   EFI_SIGNATURE_32('p','h','d','0')\r
+typedef struct {\r
+  UINT32          Signature;\r
+  UINT32          Size;\r
+  EFI_MEMORY_TYPE Type;\r
+  UINTN           Reserved;\r
+  CHAR8           Data[1];\r
+} POOL_HEAD;\r
+\r
+#define SIZE_OF_POOL_HEAD EFI_FIELD_OFFSET(POOL_HEAD,Data)\r
+\r
+#define POOL_TAIL_SIGNATURE   EFI_SIGNATURE_32('p','t','a','l')\r
+typedef struct {\r
+  UINT32      Signature;\r
+  UINT32      Size;\r
+} POOL_TAIL;\r
+\r
+\r
+#define POOL_SHIFT  7\r
+\r
+#define POOL_OVERHEAD (SIZE_OF_POOL_HEAD + sizeof(POOL_TAIL))\r
+\r
+#define HEAD_TO_TAIL(a)   \\r
+  ((POOL_TAIL *) (((CHAR8 *) (a)) + (a)->Size - sizeof(POOL_TAIL)));\r
+\r
+\r
+#define SIZE_TO_LIST(a)   ((a) >> POOL_SHIFT)\r
+#define LIST_TO_SIZE(a)   ((a+1) << POOL_SHIFT)\r
+\r
+#define MAX_POOL_LIST       SIZE_TO_LIST(DEFAULT_PAGE_ALLOCATION)\r
+\r
+#define MAX_POOL_SIZE     (MAX_ADDRESS - POOL_OVERHEAD)\r
+\r
+//\r
+// Globals\r
+//\r
+\r
+#define POOL_SIGNATURE  EFI_SIGNATURE_32('p','l','s','t')\r
+typedef struct {\r
+    INTN             Signature;\r
+    UINTN            Used;\r
+    EFI_MEMORY_TYPE  MemoryType;\r
+    LIST_ENTRY       FreeList[MAX_POOL_LIST];\r
+    LIST_ENTRY       Link;\r
+} POOL; \r
+\r
+\r
+POOL            PoolHead[EfiMaxMemoryType];\r
+LIST_ENTRY      PoolHeadList;\r
+\r
+//\r
+//\r
+//\r
+\r
+VOID\r
+CoreInitializePool (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Called to initialize the pool.\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+{\r
+  UINTN  Type;\r
+  UINTN  Index;\r
+\r
+  for (Type=0; Type < EfiMaxMemoryType; Type++) {\r
+    PoolHead[Type].Signature  = 0;\r
+    PoolHead[Type].Used       = 0;\r
+    PoolHead[Type].MemoryType = (EFI_MEMORY_TYPE) Type;\r
+    for (Index=0; Index < MAX_POOL_LIST; Index++) {\r
+        InitializeListHead (&PoolHead[Type].FreeList[Index]);\r
+    }\r
+  }\r
+  InitializeListHead (&PoolHeadList);\r
+}\r
+\r
+STATIC\r
+POOL *\r
+LookupPoolHead (\r
+  IN EFI_MEMORY_TYPE  MemoryType\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Look up pool head for specified memory type.\r
+\r
+Arguments:\r
+\r
+  MemoryType      - Memory type of which pool head is looked for\r
+\r
+Returns:\r
+\r
+  Pointer of Corresponding pool head.\r
+\r
+--*/\r
+{\r
+  LIST_ENTRY      *Link;\r
+  POOL            *Pool;\r
+  UINTN           Index;\r
+\r
+  if (MemoryType >= 0 && MemoryType < EfiMaxMemoryType) {\r
+    return &PoolHead[MemoryType];\r
+  }\r
+\r
+  if (MemoryType < 0) {\r
+\r
+    for (Link = PoolHeadList.ForwardLink; Link != &PoolHeadList; Link = Link->ForwardLink) {\r
+      Pool = CR(Link, POOL, Link, POOL_SIGNATURE);\r
+      if (Pool->MemoryType == MemoryType) {\r
+        return Pool;\r
+      }\r
+    }\r
+\r
+    Pool = CoreAllocatePoolI (EfiBootServicesData, sizeof (POOL));\r
+    if (Pool == NULL) {\r
+      return NULL;\r
+    }\r
+\r
+    Pool->Signature = POOL_SIGNATURE;\r
+    Pool->Used      = 0;\r
+    Pool->MemoryType = MemoryType;\r
+    for (Index=0; Index < MAX_POOL_LIST; Index++) {\r
+      InitializeListHead (&Pool->FreeList[Index]);\r
+    }\r
+\r
+    InsertHeadList (&PoolHeadList, &Pool->Link);\r
+\r
+    return Pool;\r
+  }\r
+\r
+  return NULL;\r
+}\r
+\r
\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreAllocatePool (\r
+  IN EFI_MEMORY_TYPE  PoolType,\r
+  IN UINTN            Size,\r
+  OUT VOID            **Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Allocate pool of a particular type.\r
+\r
+Arguments:\r
+\r
+  PoolType    - Type of pool to allocate\r
+\r
+  Size        - The amount of pool to allocate\r
+\r
+  Buffer      - The address to return a pointer to the allocated pool\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - PoolType not valid\r
+  \r
+  EFI_OUT_OF_RESOURCES      - Size exceeds max pool size or allocation failed.  \r
+  \r
+  EFI_SUCCESS               - Pool successfully allocated.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS    Status;\r
+\r
+  //\r
+  // If it's not a valid type, fail it\r
+  //\r
+  if ((PoolType >= EfiMaxMemoryType && PoolType <= 0x7fffffff) ||\r
+       PoolType == EfiConventionalMemory) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  *Buffer = NULL;\r
+  \r
+  //\r
+  // If size is too large, fail it\r
+  // Base on the EFI spec, return status of EFI_OUT_OF_RESOURCES\r
+  //\r
+  if (Size > MAX_POOL_SIZE) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // Acquire the memory lock and make the allocation\r
+  //\r
+  Status = CoreAcquireLockOrFail (&gMemoryLock);\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  *Buffer = CoreAllocatePoolI (PoolType, Size);\r
+  CoreReleaseMemoryLock ();\r
+  return (*Buffer != NULL) ? EFI_SUCCESS : EFI_OUT_OF_RESOURCES;\r
+}\r
+\r
+\r
+VOID *\r
+CoreAllocatePoolI (\r
+  IN EFI_MEMORY_TYPE  PoolType,\r
+  IN UINTN            Size\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function to allocate pool of a particular type.\r
+\r
+  Caller must have the memory lock held\r
+\r
+\r
+Arguments:\r
+\r
+  PoolType    - Type of pool to allocate\r
+\r
+  Size        - The amount of pool to allocate\r
+\r
+Returns:\r
+\r
+  The allocate pool, or NULL\r
+\r
+--*/\r
+{\r
+  POOL        *Pool;\r
+  POOL_FREE   *Free;\r
+  POOL_HEAD   *Head;\r
+  POOL_TAIL   *Tail;\r
+  CHAR8       *NewPage;\r
+  VOID        *Buffer;\r
+  UINTN       Index;\r
+  UINTN       FSize;\r
+  UINTN       offset;\r
+  UINTN       Adjustment;\r
+  UINTN       NoPages;\r
+\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+\r
+  //\r
+  // Adjust the size by the pool header & tail overhead\r
+  //\r
+  \r
+  //\r
+  // Adjusting the Size to be of proper alignment so that\r
+  // we don't get an unaligned access fault later when\r
+  // pool_Tail is being initialized\r
+  //\r
+  ALIGN_VARIABLE (Size, Adjustment);\r
+\r
+  Size += POOL_OVERHEAD;\r
+  Index = SIZE_TO_LIST(Size);\r
+  Pool = LookupPoolHead (PoolType);\r
+  if (Pool== NULL) {\r
+    return NULL;\r
+  }\r
+  Head = NULL;\r
+\r
+  //\r
+  // If allocation is over max size, just allocate pages for the request\r
+  // (slow)\r
+  //\r
+  if (Index >= MAX_POOL_LIST) {\r
+    NoPages = EFI_SIZE_TO_PAGES(Size) + EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION) - 1;\r
+    NoPages &= ~(EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION) - 1);\r
+    Head = CoreAllocatePoolPages (PoolType, NoPages, DEFAULT_PAGE_ALLOCATION);\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // If there's no free pool in the proper list size, go get some more pages\r
+  //\r
+  if (IsListEmpty (&Pool->FreeList[Index])) {\r
+\r
+    //\r
+    // Get another page\r
+    //\r
+    NewPage = CoreAllocatePoolPages(PoolType, EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION), DEFAULT_PAGE_ALLOCATION);\r
+    if (NewPage == NULL) {\r
+      goto Done;\r
+    }\r
+\r
+    //\r
+    // Carve up new page into free pool blocks\r
+    //\r
+    offset = 0;\r
+    while (offset < DEFAULT_PAGE_ALLOCATION) {\r
+      ASSERT (Index < MAX_POOL_LIST);\r
+      FSize = LIST_TO_SIZE(Index);\r
+\r
+      while (offset + FSize <= DEFAULT_PAGE_ALLOCATION) {\r
+        Free = (POOL_FREE *) &NewPage[offset];          \r
+        Free->Signature = POOL_FREE_SIGNATURE;\r
+        Free->Index     = (UINT32)Index;\r
+        InsertHeadList (&Pool->FreeList[Index], &Free->Link);\r
+        offset += FSize;\r
+      }\r
+\r
+      Index -= 1;\r
+    }\r
+\r
+    ASSERT (offset == DEFAULT_PAGE_ALLOCATION);\r
+    Index = SIZE_TO_LIST(Size);\r
+  }\r
+\r
+  //\r
+  // Remove entry from free pool list\r
+  //\r
+  Free = CR (Pool->FreeList[Index].ForwardLink, POOL_FREE, Link, POOL_FREE_SIGNATURE);\r
+  RemoveEntryList (&Free->Link);\r
+\r
+  Head = (POOL_HEAD *) Free;\r
+\r
+Done:\r
+  Buffer = NULL;\r
+\r
+  if (Head != NULL) {\r
+    \r
+    //\r
+    // If we have a pool buffer, fill in the header & tail info\r
+    //\r
+    Head->Signature = POOL_HEAD_SIGNATURE;\r
+    Head->Size      = (UINT32) Size;\r
+    Head->Type      = (EFI_MEMORY_TYPE) PoolType;\r
+    Tail            = HEAD_TO_TAIL (Head);\r
+    Tail->Signature = POOL_TAIL_SIGNATURE;\r
+    Tail->Size      = (UINT32) Size;\r
+    Buffer          = Head->Data;\r
+    DEBUG_CLEAR_MEMORY (Buffer, Size - POOL_OVERHEAD);\r
+\r
+    DEBUG (\r
+      (EFI_D_POOL,\r
+      "AllcocatePoolI: Type %x, Addr %x (len %x) %,d\n",\r
+       PoolType, \r
+       Buffer, \r
+       Size - POOL_OVERHEAD, \r
+      Pool->Used)\r
+      );\r
+\r
+    //\r
+    // Account the allocation\r
+    //\r
+    Pool->Used += Size;\r
+\r
+  } else {\r
+    DEBUG ((EFI_D_ERROR | EFI_D_POOL, "AllocatePool: failed to allocate %d bytes\n", Size));\r
+  }\r
+\r
+  return Buffer;\r
+}\r
+  \r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreFreePool (\r
+  IN VOID        *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Frees pool.\r
+\r
+Arguments:\r
+\r
+  Buffer      - The allocated pool entry to free\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER   - Buffer is not a valid value.\r
+  \r
+  EFI_SUCCESS             - Pool successfully freed.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS Status;\r
+\r
+  if (NULL == Buffer) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  CoreAcquireMemoryLock ();\r
+  Status = CoreFreePoolI (Buffer);\r
+  CoreReleaseMemoryLock ();\r
+  return Status;\r
+}\r
+\r
+\r
+EFI_STATUS\r
+CoreFreePoolI (\r
+  IN VOID       *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function to free a pool entry.\r
+\r
+  Caller must have the memory lock held\r
+\r
+\r
+Arguments:\r
+\r
+  Buffer      - The allocated pool entry to free\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Buffer not valid\r
+  \r
+  EFI_SUCCESS               - Buffer successfully freed.\r
+\r
+--*/\r
+{\r
+  POOL        *Pool;\r
+  POOL_HEAD   *Head;\r
+  POOL_TAIL   *Tail;\r
+  POOL_FREE   *Free;\r
+  UINTN       Index;\r
+  UINTN       NoPages;\r
+  UINTN       Size;\r
+  CHAR8       *NewPage;\r
+  UINTN       FSize;\r
+  UINTN       offset;\r
+  BOOLEAN     AllFree;\r
+\r
+  ASSERT(NULL != Buffer);\r
+  //\r
+  // Get the head & tail of the pool entry\r
+  //\r
+  Head = CR (Buffer, POOL_HEAD, Data, POOL_HEAD_SIGNATURE);\r
+  ASSERT(NULL != Head);\r
+\r
+  if (Head->Signature != POOL_HEAD_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Tail = HEAD_TO_TAIL (Head);\r
+  ASSERT(NULL != Tail);\r
+\r
+  //\r
+  // Debug\r
+  //\r
+  ASSERT (Tail->Signature == POOL_TAIL_SIGNATURE);\r
+  ASSERT (Head->Size == Tail->Size);\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+\r
+  if (Tail->Signature != POOL_TAIL_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Head->Size != Tail->Size) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Determine the pool type and account for it\r
+  //\r
+  Size = Head->Size;\r
+  Pool = LookupPoolHead (Head->Type);\r
+  if (Pool == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  Pool->Used -= Size;\r
+  DEBUG ((EFI_D_POOL, "FreePool: %x (len %x) %,d\n", Head->Data, Head->Size - POOL_OVERHEAD, Pool->Used));\r
+\r
+  //\r
+  // Determine the pool list \r
+  //\r
+  Index = SIZE_TO_LIST(Size);\r
+  DEBUG_CLEAR_MEMORY (Head, Size);\r
+\r
+  //\r
+  // If it's not on the list, it must be pool pages\r
+  //\r
+  if (Index >= MAX_POOL_LIST) {\r
+\r
+    //\r
+    // Return the memory pages back to free memory\r
+    //\r
+    NoPages = EFI_SIZE_TO_PAGES(Size) + EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION) - 1;\r
+    NoPages &= ~(EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION) - 1);\r
+    CoreFreePoolPages ((EFI_PHYSICAL_ADDRESS) (UINTN) Head, NoPages);\r
+\r
+  } else {\r
+\r
+    //\r
+    // Put the pool entry onto the free pool list\r
+    //\r
+    Free = (POOL_FREE *) Head;\r
+    ASSERT(NULL != Free);\r
+    Free->Signature = POOL_FREE_SIGNATURE;\r
+    Free->Index     = (UINT32)Index;\r
+    InsertHeadList (&Pool->FreeList[Index], &Free->Link);\r
+\r
+    //\r
+    // See if all the pool entries in the same page as Free are freed pool \r
+    // entries\r
+    //\r
+    NewPage = (CHAR8 *)((UINTN)Free & ~((DEFAULT_PAGE_ALLOCATION) -1));\r
+    Free = (POOL_FREE *) &NewPage[0];\r
+    ASSERT(NULL != Free);\r
+\r
+    if (Free->Signature == POOL_FREE_SIGNATURE) {\r
+\r
+      Index = Free->Index;\r
+\r
+      AllFree = TRUE;\r
+      offset = 0;\r
+      \r
+      while ((offset < DEFAULT_PAGE_ALLOCATION) && (AllFree)) {\r
+        FSize = LIST_TO_SIZE(Index);\r
+        while (offset + FSize <= DEFAULT_PAGE_ALLOCATION) {\r
+          Free = (POOL_FREE *) &NewPage[offset];\r
+          ASSERT(NULL != Free);\r
+          if (Free->Signature != POOL_FREE_SIGNATURE) {\r
+            AllFree = FALSE;\r
+          }\r
+          offset += FSize;\r
+        }\r
+        Index -= 1;\r
+      }\r
+\r
+      if (AllFree) {\r
+\r
+        //\r
+        // All of the pool entries in the same page as Free are free pool \r
+        // entries\r
+        // Remove all of these pool entries from the free loop lists.\r
+        //\r
+        Free = (POOL_FREE *) &NewPage[0];\r
+        ASSERT(NULL != Free);\r
+        Index = Free->Index;\r
+        offset = 0;\r
+        \r
+        while (offset < DEFAULT_PAGE_ALLOCATION) {\r
+          FSize = LIST_TO_SIZE(Index);\r
+          while (offset + FSize <= DEFAULT_PAGE_ALLOCATION) {\r
+            Free = (POOL_FREE *) &NewPage[offset];\r
+            ASSERT(NULL != Free);\r
+            RemoveEntryList (&Free->Link);\r
+            offset += FSize;\r
+          }\r
+          Index -= 1;\r
+        }\r
+\r
+        //\r
+        // Free the page\r
+        //\r
+        CoreFreePoolPages ((EFI_PHYSICAL_ADDRESS) (UINTN)NewPage, EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION));\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // If this is an OS specific memory type, then check to see if the last \r
+  // portion of that memory type has been freed.  If it has, then free the\r
+  // list entry for that memory type\r
+  //\r
+  if (Pool->MemoryType < 0 && Pool->Used == 0) {\r
+    RemoveEntryList (&Pool->Link);\r
+    CoreFreePoolI (Pool);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c b/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c
new file mode 100644 (file)
index 0000000..3512477
--- /dev/null
@@ -0,0 +1,260 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  DebugImageInfo.c\r
+    \r
+Abstract:\r
+\r
+  Support functions for managing debug image info table when loading and unloading\r
+  images.\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+static EFI_DEBUG_IMAGE_INFO_TABLE_HEADER  mDebugInfoTableHeader = {\r
+  0,          // volatile UINT32                 UpdateStatus;\r
+  0,          // UINT32                          TableSize;\r
+  NULL        // EFI_DEBUG_IMAGE_INFO            *EfiDebugImageInfoTable;\r
+};\r
+\r
+static EFI_SYSTEM_TABLE_POINTER *mDebugTable = NULL;\r
+\r
+    \r
+VOID\r
+CoreInitializeDebugImageInfoTable (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Creates and initializes the DebugImageInfo Table.  Also creates the configuration\r
+  table and registers it into the system table.\r
+\r
+Arguments:\r
+  None\r
+\r
+Returns:\r
+  NA\r
+\r
+Notes:\r
+  This function allocates memory, frees it, and then allocates memory at an\r
+  address within the initial allocation. Since this function is called early\r
+  in DXE core initialization (before drivers are dispatched), this should not\r
+  be a problem.\r
+\r
+--*/\r
+{ \r
+  EFI_STATUS                          Status;\r
+  EFI_PHYSICAL_ADDRESS                Mem;\r
+  UINTN                               NumberOfPages; \r
+\r
+  //\r
+  // Allocate boot services memory for the structure. It's required to be aligned on\r
+  // a 4M boundary, so allocate a 4M block (plus what we require), free it up, calculate\r
+  // a 4M aligned address within the memory we just freed, and then allocate memory at that\r
+  // address for our initial structure.\r
+  //\r
+  NumberOfPages = FOUR_MEG_PAGES + EFI_SIZE_TO_PAGES(sizeof (EFI_SYSTEM_TABLE_POINTER));  \r
+\r
+  Status = CoreAllocatePages (AllocateAnyPages, EfiBootServicesData, NumberOfPages , &Mem); \r
+  ASSERT_EFI_ERROR (Status);\r
+  if (EFI_ERROR(Status)) {\r
+    return;\r
+  }\r
+  Status = CoreFreePages (Mem, NumberOfPages); \r
+  ASSERT_EFI_ERROR (Status);\r
+  if (EFI_ERROR(Status)) {\r
+    return;\r
+  }\r
+  //\r
+  // Now get a 4M aligned address within the memory range we were given.\r
+  // Then allocate memory at that address\r
+  //\r
+  Mem = (Mem + FOUR_MEG_MASK) & (~FOUR_MEG_MASK);\r
+  \r
+  Status = CoreAllocatePages (AllocateAddress, EfiBootServicesData, NumberOfPages - FOUR_MEG_PAGES, &Mem); \r
+  ASSERT_EFI_ERROR (Status);\r
+  if (EFI_ERROR(Status)) {\r
+    return;\r
+  }\r
+  //\r
+  // We now have a 4M aligned page allocated, so fill in the data structure.\r
+  // Ideally we would update the CRC now as well, but the service may not yet be available.\r
+  // See comments in the CoreUpdateDebugTableCrc32() function below for details.\r
+  //\r
+  mDebugTable = (EFI_SYSTEM_TABLE_POINTER *)(UINTN)Mem;\r
+  mDebugTable->Signature = EFI_SYSTEM_TABLE_SIGNATURE;\r
+  mDebugTable->EfiSystemTableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) gDxeCoreST;\r
+  mDebugTable->Crc32 = 0;\r
+  Status = CoreInstallConfigurationTable (&gEfiDebugImageInfoTableGuid, &mDebugInfoTableHeader);\r
+  ASSERT_EFI_ERROR (Status);\r
+}\r
+\r
+VOID\r
+CoreUpdateDebugTableCrc32 (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Update the CRC32 in the Debug Table.\r
+  Since the CRC32 service is made available by the Runtime driver, we have to\r
+  wait for the Runtime Driver to be installed before the CRC32 can be computed.\r
+  This function is called elsewhere by the core when the runtime architectural\r
+  protocol is produced.\r
+\r
+Arguments:\r
+  None\r
+\r
+Returns:\r
+  NA\r
+\r
+--*/\r
+{\r
+  ASSERT(mDebugTable != NULL);\r
+  mDebugTable->Crc32 = 0;\r
+  gDxeCoreBS->CalculateCrc32 ((VOID *)mDebugTable, sizeof (EFI_SYSTEM_TABLE_POINTER), &mDebugTable->Crc32);\r
+}\r
+\r
+VOID\r
+CoreNewDebugImageInfoEntry (\r
+  IN  UINT32                      ImageInfoType,\r
+  IN  EFI_LOADED_IMAGE_PROTOCOL   *LoadedImage,\r
+  IN  EFI_HANDLE                  ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Adds a new DebugImageInfo structure to the DebugImageInfo Table.  Re-Allocates\r
+  the table if it's not large enough to accomidate another entry.\r
+\r
+Arguments:\r
+\r
+  ImageInfoType     - type of debug image information\r
+  LoadedImage       - pointer to the loaded image protocol for the image being loaded\r
+  ImageHandle       - image handle for the image being loaded\r
+\r
+Returns:\r
+  NA\r
+\r
+--*/\r
+{    \r
+  EFI_DEBUG_IMAGE_INFO      *Table;\r
+  EFI_DEBUG_IMAGE_INFO      *NewTable;\r
+  UINTN                     Index;\r
+  UINTN                     MaxTableIndex;\r
+  UINTN                     TableSize;\r
+\r
+  //\r
+  // Set the flag indicating that we're in the process of updating the table.\r
+  //\r
+  mDebugInfoTableHeader.UpdateStatus |= EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS;\r
+\r
+  Table = mDebugInfoTableHeader.EfiDebugImageInfoTable;\r
+  MaxTableIndex = mDebugInfoTableHeader.TableSize;\r
+\r
+  for (Index = 0; Index < MaxTableIndex; Index++) {\r
+    if (Table[Index].NormalImage == NULL) {\r
+      //\r
+      // We have found a free entry so exit the loop\r
+      //\r
+      break;\r
+    }\r
+  }\r
+  if (Index == MaxTableIndex) {\r
+    //\r
+    //  Table is full, so re-allocate another page for a larger table...\r
+    //\r
+    TableSize = MaxTableIndex * EFI_DEBUG_TABLE_ENTRY_SIZE;\r
+    NewTable = CoreAllocateZeroBootServicesPool (TableSize + EFI_PAGE_SIZE);\r
+    if (NewTable == NULL) {\r
+      mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS;\r
+      return;\r
+    }\r
+    //\r
+    // Copy the old table into the new one\r
+    //\r
+    CopyMem (NewTable, Table, TableSize);\r
+    //\r
+    // Free the old table\r
+    //\r
+    CoreFreePool (Table);\r
+    //\r
+    // Update the table header\r
+    //\r
+    Table = NewTable;\r
+    mDebugInfoTableHeader.EfiDebugImageInfoTable = NewTable;\r
+    mDebugInfoTableHeader.TableSize += EFI_PAGE_SIZE / EFI_DEBUG_TABLE_ENTRY_SIZE;\r
+  }\r
+  //\r
+  // Allocate data for new entry\r
+  //\r
+  Table[Index].NormalImage = CoreAllocateZeroBootServicesPool (sizeof (EFI_DEBUG_IMAGE_INFO_NORMAL));\r
+  if (Table[Index].NormalImage != NULL) {\r
+    //\r
+    // Update the entry\r
+    //\r
+    Table[Index].NormalImage->ImageInfoType               = (UINT32) ImageInfoType;\r
+    Table[Index].NormalImage->LoadedImageProtocolInstance = LoadedImage;\r
+    Table[Index].NormalImage->ImageHandle                 = ImageHandle;\r
+  }\r
+  mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS;\r
+}\r
+\r
+\r
+VOID\r
+CoreRemoveDebugImageInfoEntry (\r
+  EFI_HANDLE ImageHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes and frees an entry from the DebugImageInfo Table.\r
+\r
+Arguments:\r
+\r
+  ImageHandle       - image handle for the image being unloaded\r
+\r
+Returns:\r
+\r
+  NA\r
+\r
+--*/\r
+{    \r
+  EFI_DEBUG_IMAGE_INFO  *Table;\r
+  UINTN                 Index;\r
+\r
+  mDebugInfoTableHeader.UpdateStatus |= EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS;\r
+\r
+  Table = mDebugInfoTableHeader.EfiDebugImageInfoTable;\r
+\r
+  for (Index = 0; Index < mDebugInfoTableHeader.TableSize; Index++) {\r
+    if (Table[Index].NormalImage != NULL && Table[Index].NormalImage->ImageHandle == ImageHandle) {\r
+      //\r
+      // Found a match. Free up the record, then NULL the pointer to indicate the slot\r
+      // is free.\r
+      //\r
+      CoreFreePool (Table[Index].NormalImage);\r
+      Table[Index].NormalImage = NULL;\r
+      break;\r
+    }\r
+  }\r
+  mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS;\r
+}\r
+\r
diff --git a/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c b/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c
new file mode 100644 (file)
index 0000000..677a210
--- /dev/null
@@ -0,0 +1,225 @@
+/*++\r
+\r
+Copyright (c) 2006 - 2007, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  InstallConfigurationTable.c\r
+\r
+\r
+Abstract:\r
+\r
+  Tiano Miscellaneous Services InstallConfigurationTable service\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define CONFIG_TABLE_SIZE_INCREASED 0x10\r
+\r
+UINTN mSystemTableAllocateSize = 0;\r
+\r
+\r
+EFI_STATUS\r
+CoreGetConfigTable (\r
+  IN EFI_GUID *Guid,\r
+  OUT VOID    **Table\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Find a config table by name in system table's ConfigurationTable.\r
+\r
+Arguments:\r
+\r
+  Guid        - The table name to look for\r
+  \r
+  Table       - Pointer of the config table\r
+\r
+Returns: \r
+\r
+  EFI_NOT_FOUND       - Could not find the table in system table's ConfigurationTable.\r
+  \r
+  EFI_SUCCESS         - Table successfully found.\r
+\r
+--*/\r
+{\r
+  UINTN Index;\r
+\r
+  for (Index = 0; Index < gDxeCoreST->NumberOfTableEntries; Index++) {\r
+    if (CompareGuid (Guid, &(gDxeCoreST->ConfigurationTable[Index].VendorGuid))) {\r
+      *Table = gDxeCoreST->ConfigurationTable[Index].VendorTable;\r
+      return EFI_SUCCESS;\r
+    }\r
+  }\r
+\r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInstallConfigurationTable (\r
+  IN EFI_GUID *Guid,\r
+  IN VOID     *Table\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Boot Service called to add, modify, or remove a system configuration table from \r
+  the EFI System Table.\r
+\r
+Arguments:\r
+\r
+  Guid     -  Pointer to the GUID for the entry to add, update, or remove\r
+  Table    -  Pointer to the configuration table for the entry to add, update, or\r
+              remove, may be NULL.\r
+\r
+Returns:\r
+  \r
+  EFI_SUCCESS               Guid, Table pair added, updated, or removed.\r
+  EFI_INVALID_PARAMETER     Input GUID not valid.\r
+  EFI_NOT_FOUND             Attempted to delete non-existant entry\r
+  EFI_OUT_OF_RESOURCES      Not enough memory available\r
+\r
+--*/\r
+{\r
+  UINTN                   Index;\r
+  EFI_CONFIGURATION_TABLE *EfiConfigurationTable;\r
+\r
+  //\r
+  // If Guid is NULL, then this operation cannot be performed\r
+  //\r
+  if (Guid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  EfiConfigurationTable = gDxeCoreST->ConfigurationTable;\r
+\r
+  //\r
+  // Search all the table for an entry that matches Guid\r
+  //\r
+  for (Index = 0; Index < gDxeCoreST->NumberOfTableEntries; Index++) {\r
+    if (CompareGuid (Guid, &(gDxeCoreST->ConfigurationTable[Index].VendorGuid))) {\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (Index < gDxeCoreST->NumberOfTableEntries) {\r
+    //\r
+    // A match was found, so this is either a modify or a delete operation\r
+    //\r
+    if (Table != NULL) {\r
+      //\r
+      // If Table is not NULL, then this is a modify operation.\r
+      // Modify the table enty and return.\r
+      //\r
+      gDxeCoreST->ConfigurationTable[Index].VendorTable = Table;\r
+\r
+      //\r
+      // Signal Configuration Table change\r
+      //\r
+      CoreNotifySignalList (Guid);\r
+\r
+      return EFI_SUCCESS;\r
+    }\r
+\r
+    //\r
+    // A match was found and Table is NULL, so this is a delete operation.\r
+    //\r
+    gDxeCoreST->NumberOfTableEntries--;\r
+\r
+    //\r
+    // Copy over deleted entry\r
+    //\r
+    CopyMem (\r
+      &(EfiConfigurationTable[Index]),\r
+      &(gDxeCoreST->ConfigurationTable[Index + 1]),\r
+      (gDxeCoreST->NumberOfTableEntries - Index) * sizeof (EFI_CONFIGURATION_TABLE)\r
+      );\r
+\r
+  } else {\r
+\r
+    //\r
+    // No matching GUIDs were found, so this is an add operation.\r
+    //\r
+\r
+    if (Table == NULL) {\r
+      //\r
+      // If Table is NULL on an add operation, then return an error.\r
+      //\r
+      return EFI_NOT_FOUND;\r
+    }\r
+\r
+    //\r
+    // Assume that Index == gDxeCoreST->NumberOfTableEntries\r
+    //\r
+    if ((Index * sizeof (EFI_CONFIGURATION_TABLE)) >= mSystemTableAllocateSize) {\r
+      //\r
+      // Allocate a table with one additional entry.\r
+      //\r
+      mSystemTableAllocateSize += (CONFIG_TABLE_SIZE_INCREASED * sizeof (EFI_CONFIGURATION_TABLE));\r
+      EfiConfigurationTable = CoreAllocateRuntimePool (mSystemTableAllocateSize);\r
+      if (EfiConfigurationTable == NULL) {\r
+        //\r
+        // If a new table could not be allocated, then return an error.\r
+        //\r
+        return EFI_OUT_OF_RESOURCES;\r
+      }\r
+\r
+      if (gDxeCoreST->ConfigurationTable != NULL) {\r
+        //\r
+        // Copy the old table to the new table.\r
+        //\r
+        CopyMem (\r
+          EfiConfigurationTable,\r
+          gDxeCoreST->ConfigurationTable,\r
+          Index * sizeof (EFI_CONFIGURATION_TABLE)\r
+          );\r
+\r
+        //\r
+        // Free Old Table\r
+        //\r
+        CoreFreePool (gDxeCoreST->ConfigurationTable);\r
+      }\r
+\r
+      //\r
+      // Update System Table\r
+      //\r
+      gDxeCoreST->ConfigurationTable = EfiConfigurationTable;\r
+    }\r
+\r
+    //\r
+    // Fill in the new entry\r
+    //\r
+    CopyMem ((VOID *)&EfiConfigurationTable[Index].VendorGuid, Guid, sizeof (EFI_GUID));\r
+    EfiConfigurationTable[Index].VendorTable  = Table;\r
+\r
+    //\r
+    // This is an add operation, so increment the number of table entries\r
+    //\r
+    gDxeCoreST->NumberOfTableEntries++;\r
+  }\r
+\r
+  //\r
+  // Fix up the CRC-32 in the EFI System Table\r
+  //\r
+  CalculateEfiHdrCrc (&gDxeCoreST->Hdr);\r
+\r
+  //\r
+  // Signal Configuration Table change\r
+  //\r
+  CoreNotifySignalList (Guid);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c b/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c
new file mode 100644 (file)
index 0000000..c11c926
--- /dev/null
@@ -0,0 +1,83 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+    SetWatchdogTimer.c\r
+\r
+Abstract:\r
+\r
+    Tiano Miscellaneous Services SetWatchdogTimer service implementation\r
+\r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+#define WATCHDOG_TIMER_CALIBRATE_PER_SECOND 10000000\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreSetWatchdogTimer (\r
+  IN UINTN    Timeout,\r
+  IN UINT64   WatchdogCode,\r
+  IN UINTN    DataSize,\r
+  IN CHAR16   *WatchdogData OPTIONAL\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Sets the system's watchdog timer.\r
+\r
+Arguments:\r
+\r
+  Timeout         The number of seconds.  Zero disables the timer.\r
+\r
+  ///////following  three parameters are left for platform specific using  \r
+  \r
+  WatchdogCode    The numberic code to log.  0x0 to 0xffff are firmware\r
+  DataSize        Size of the optional data\r
+  WatchdogData    Optional Null terminated unicode string followed by binary \r
+                  data.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS               Timeout has been set\r
+  EFI_NOT_AVAILABLE_YET     WatchdogTimer is not available yet \r
+  EFI_UNSUPPORTED           System does not have a timer (currently not used)\r
+  EFI_DEVICE_ERROR          Could not complete due to hardware error\r
+\r
+--*/\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  //\r
+  // Check our architectural protocol\r
+  //\r
+  if (gWatchdogTimer == NULL) {\r
+    return EFI_NOT_AVAILABLE_YET;\r
+  }\r
+\r
+  //\r
+  // Attempt to set the timeout\r
+  //\r
+  Status = gWatchdogTimer->SetTimerPeriod (gWatchdogTimer, MultU64x32 (Timeout, WATCHDOG_TIMER_CALIBRATE_PER_SECOND));\r
+\r
+  //\r
+  // Check for errors\r
+  //\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_DEVICE_ERROR;\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/Misc/Stall.c b/MdeModulePkg/Core/Dxe/Misc/Stall.c
new file mode 100644 (file)
index 0000000..c251f31
--- /dev/null
@@ -0,0 +1,82 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation\r
+All rights reserved. This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+Module Name:\r
+\r
+    Stall.c\r
+\r
+Abstract:\r
+\r
+    Tiano Miscellaneous Services Stall service implementation\r
+\r
+--*/\r
+\r
+//\r
+// Include statements\r
+//\r
+\r
+#include <DxeMain.h>\r
+\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+CoreStall (\r
+  IN UINTN            Microseconds\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Introduces a fine-grained stall.\r
+\r
+Arguments:\r
+\r
+  Microseconds      The number of microseconds to stall execution\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS            - Execution was stalled for at least the requested amount\r
+                           of microseconds.\r
+\r
+  EFI_NOT_AVAILABLE_YET  - gMetronome is not available yet\r
+\r
+--*/\r
+{\r
+  UINT32  Counter;\r
+  UINT32  Remainder;\r
+\r
+  if (gMetronome == NULL) {\r
+    return EFI_NOT_AVAILABLE_YET;\r
+  }\r
+\r
+  //\r
+  // Calculate the number of ticks by dividing the number of microseconds by\r
+  // the TickPeriod.\r
+  // Calcullation is based on 100ns unit.\r
+  //\r
+  Counter = (UINT32) DivU64x32Remainder (\r
+                       Microseconds * 10,\r
+                       gMetronome->TickPeriod,\r
+                       &Remainder\r
+                       );\r
+\r
+  //\r
+  // Call WaitForTick for Counter + 1 ticks to try to guarantee Counter tick\r
+  // periods, thus attempting to ensure Microseconds of stall time.\r
+  //\r
+  if (Remainder != 0) {\r
+    Counter++;\r
+  }\r
+\r
+  gMetronome->WaitForTick (gMetronome, Counter);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c b/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c
new file mode 100644 (file)
index 0000000..1c328be
--- /dev/null
@@ -0,0 +1,1341 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  CoreSectionExtraction.c\r
+  \r
+Abstract:\r
+\r
+  Section Extraction Protocol implementation.\r
+  \r
+  Stream database is implemented as a linked list of section streams,\r
+  where each stream contains a linked list of children, which may be leaves or\r
+  encapsulations.  \r
+  \r
+  Children that are encapsulations generate new stream entries\r
+  when they are created.  Streams can also be created by calls to \r
+  SEP->OpenSectionStream().\r
+  \r
+  The database is only created far enough to return the requested data from\r
+  any given stream, or to determine that the requested data is not found.\r
+  \r
+  If a GUIDed encapsulation is encountered, there are three possiblilites.\r
+  \r
+  1) A support protocol is found, in which the stream is simply processed with\r
+     the support protocol.\r
+     \r
+  2) A support protocol is not found, but the data is available to be read\r
+     without processing.  In this case, the database is built up through the\r
+     recursions to return the data, and a RPN event is set that will enable\r
+     the stream in question to be refreshed if and when the required section\r
+     extraction protocol is published.This insures the AuthenticationStatus \r
+     does not become stale in the cache.\r
+     \r
+  3) A support protocol is not found, and the data is not available to be read\r
+     without it.  This results in EFI_PROTOCOL_ERROR.\r
+  \r
+--*/\r
+\r
+#include <DxeMain.h>\r
+\r
+//\r
+// Local defines and typedefs\r
+//\r
+#define CORE_SECTION_CHILD_SIGNATURE  EFI_SIGNATURE_32('S','X','C','S')\r
+#define CHILD_SECTION_NODE_FROM_LINK(Node) \\r
+  CR (Node, CORE_SECTION_CHILD_NODE, Link, CORE_SECTION_CHILD_SIGNATURE)\r
+\r
+typedef struct {\r
+  UINT32                      Signature;\r
+  LIST_ENTRY                  Link;\r
+  UINT32                      Type;\r
+  UINT32                      Size;\r
+  //\r
+  // StreamBase + OffsetInStream == pointer to section header in stream.  The\r
+  // stream base is always known when walking the sections within.\r
+  //\r
+  UINT32                      OffsetInStream;\r
+  //\r
+  // Then EncapsulatedStreamHandle below is always 0 if the section is NOT an\r
+  // encapsulating section.  Otherwise, it contains the stream handle\r
+  // of the encapsulated stream.  This handle is ALWAYS produced any time an\r
+  // encapsulating child is encountered, irrespective of whether the\r
+  // encapsulated stream is processed further.\r
+  //\r
+  UINTN                       EncapsulatedStreamHandle;\r
+  EFI_GUID                    *EncapsulationGuid;\r
+} CORE_SECTION_CHILD_NODE;\r
+\r
+#define CORE_SECTION_STREAM_SIGNATURE EFI_SIGNATURE_32('S','X','S','S')\r
+#define STREAM_NODE_FROM_LINK(Node) \\r
+  CR (Node, CORE_SECTION_STREAM_NODE, Link, CORE_SECTION_STREAM_SIGNATURE)\r
+\r
+typedef struct {\r
+  UINT32                      Signature;\r
+  LIST_ENTRY                  Link;\r
+  UINTN                       StreamHandle;\r
+  UINT8                       *StreamBuffer;\r
+  UINTN                       StreamLength;\r
+  LIST_ENTRY                  Children;\r
+  //\r
+  // Authentication status is from GUIDed encapsulations.\r
+  //\r
+  UINT32                      AuthenticationStatus;\r
+} CORE_SECTION_STREAM_NODE;\r
+\r
+#define NULL_STREAM_HANDLE    0\r
+\r
+typedef struct {\r
+  CORE_SECTION_CHILD_NODE     *ChildNode;\r
+  CORE_SECTION_STREAM_NODE    *ParentStream;\r
+  VOID                        *Registration;\r
+  EFI_EVENT                   Event;\r
+} RPN_EVENT_CONTEXT;\r
+  \r
+  \r
+\r
+//\r
+// Local prototypes\r
+//\r
+\r
+STATIC\r
+BOOLEAN\r
+ChildIsType (\r
+  IN CORE_SECTION_STREAM_NODE                 *Stream,\r
+  IN CORE_SECTION_CHILD_NODE                  *Child,\r
+  IN EFI_SECTION_TYPE                         SearchType,\r
+  IN EFI_GUID                                 *SectionDefinitionGuid\r
+  );\r
+\r
+STATIC\r
+VOID\r
+EFIAPI\r
+NotifyGuidedExtraction (\r
+  IN  EFI_EVENT                             Event,\r
+  IN  VOID                                  *RpnContext\r
+  );\r
+\r
+STATIC\r
+VOID\r
+CreateGuidedExtractionRpnEvent (\r
+  IN CORE_SECTION_STREAM_NODE                 *ParentStream,\r
+  IN CORE_SECTION_CHILD_NODE                  *ChildNode\r
+  );\r
+\r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+OpenSectionStream (\r
+  IN     EFI_SECTION_EXTRACTION_PROTOCOL      *This,\r
+  IN     UINTN                                SectionStreamLength,\r
+  IN     VOID                                 *SectionStream,\r
+     OUT UINTN                                *SectionStreamHandle\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+GetSection (\r
+  IN EFI_SECTION_EXTRACTION_PROTOCOL          *This,\r
+  IN UINTN                                    SectionStreamHandle,\r
+  IN EFI_SECTION_TYPE                         *SectionType,\r
+  IN EFI_GUID                                 *SectionDefinitionGuid,\r
+  IN UINTN                                    SectionInstance,\r
+  IN VOID                                     **Buffer,\r
+  IN OUT UINTN                                *BufferSize,\r
+  OUT UINT32                                  *AuthenticationStatus\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+CloseSectionStream (\r
+  IN  EFI_SECTION_EXTRACTION_PROTOCOL         *This,\r
+  IN  UINTN                                   StreamHandleToClose\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+FindStreamNode (\r
+  IN  UINTN                                   SearchHandle,\r
+  OUT CORE_SECTION_STREAM_NODE                **FoundStream\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+FindChildNode (\r
+  IN     CORE_SECTION_STREAM_NODE             *SourceStream,\r
+  IN     EFI_SECTION_TYPE                     SearchType,\r
+  IN     UINTN                                *SectionInstance,\r
+  IN     EFI_GUID                             *SectionDefinitionGuid,\r
+  OUT    CORE_SECTION_CHILD_NODE              **FoundChild,\r
+  OUT    CORE_SECTION_STREAM_NODE             **FoundStream,\r
+  OUT    UINT32                               *AuthenticationStatus\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+CreateChildNode (\r
+  IN     CORE_SECTION_STREAM_NODE             *Stream,\r
+  IN     UINT32                               ChildOffset,\r
+  OUT    CORE_SECTION_CHILD_NODE              **ChildNode\r
+  );\r
+  \r
+STATIC\r
+VOID\r
+FreeChildNode (\r
+  IN  CORE_SECTION_CHILD_NODE                 *ChildNode\r
+  );\r
+  \r
+STATIC\r
+EFI_STATUS\r
+OpenSectionStreamEx (\r
+  IN     UINTN                                SectionStreamLength,\r
+  IN     VOID                                 *SectionStream,\r
+  IN     BOOLEAN                              AllocateBuffer,\r
+  IN     UINT32                               AuthenticationStatus,   \r
+     OUT UINTN                                *SectionStreamHandle\r
+  );\r
+  \r
+STATIC\r
+BOOLEAN\r
+IsValidSectionStream (\r
+  IN  VOID                                    *SectionStream,\r
+  IN  UINTN                                   SectionStreamLength\r
+  );\r
+  \r
+//\r
+// Module globals\r
+//\r
+LIST_ENTRY mStreamRoot = INITIALIZE_LIST_HEAD_VARIABLE (mStreamRoot);\r
+\r
+EFI_HANDLE mSectionExtractionHandle = NULL;\r
+\r
+EFI_SECTION_EXTRACTION_PROTOCOL mSectionExtraction = { \r
+  OpenSectionStream, \r
+  GetSection, \r
+  CloseSectionStream\r
+};\r
+\r
+                                             \r
+EFI_STATUS\r
+EFIAPI\r
+InitializeSectionExtraction (\r
+  IN EFI_HANDLE                   ImageHandle,\r
+  IN EFI_SYSTEM_TABLE             *SystemTable\r
+  )\r
+/*++\r
+\r
+Routine Description: \r
+  Entry point of the section extraction code. Initializes an instance of the \r
+  section extraction interface and installs it on a new handle.\r
+\r
+Arguments:  \r
+  ImageHandle   EFI_HANDLE: A handle for the image that is initializing this driver\r
+  SystemTable   EFI_SYSTEM_TABLE: A pointer to the EFI system table        \r
+\r
+Returns:  \r
+  EFI_SUCCESS:  Driver initialized successfully\r
+  EFI_OUT_OF_RESOURCES:   Could not allocate needed resources\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                         Status;\r
+\r
+  //\r
+  // Install SEP to a new handle\r
+  //\r
+  Status = CoreInstallProtocolInterface (\r
+            &mSectionExtractionHandle,\r
+            &gEfiSectionExtractionProtocolGuid,\r
+            EFI_NATIVE_INTERFACE,\r
+            &mSectionExtraction\r
+            );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  return Status;\r
+}\r
+\r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+OpenSectionStream (\r
+  IN     EFI_SECTION_EXTRACTION_PROTOCOL           *This,\r
+  IN     UINTN                                     SectionStreamLength,\r
+  IN     VOID                                      *SectionStream,\r
+     OUT UINTN                                     *SectionStreamHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  SEP member function.  This function creates and returns a new section stream\r
+  handle to represent the new section stream.\r
+\r
+Arguments:\r
+  This                - Indicates the calling context.\r
+  SectionStreamLength - Size in bytes of the section stream.\r
+  SectionStream       - Buffer containing the new section stream.\r
+  SectionStreamHandle - A pointer to a caller allocated UINTN that on output\r
+                        contains the new section stream handle.\r
+\r
+Returns:\r
+  EFI_SUCCESS\r
+  EFI_OUT_OF_RESOURCES - memory allocation failed.\r
+  EFI_INVALID_PARAMETER - section stream does not end concident with end of\r
+                          last section.\r
+\r
+--*/\r
+{\r
+  //\r
+  // Check to see section stream looks good...\r
+  //\r
+  if (!IsValidSectionStream (SectionStream, SectionStreamLength)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  return OpenSectionStreamEx ( \r
+          SectionStreamLength, \r
+          SectionStream,\r
+          TRUE,\r
+          0,\r
+          SectionStreamHandle\r
+          );\r
+}\r
+  \r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+GetSection (\r
+  IN EFI_SECTION_EXTRACTION_PROTOCOL                    *This,\r
+  IN UINTN                                              SectionStreamHandle,\r
+  IN EFI_SECTION_TYPE                                   *SectionType,\r
+  IN EFI_GUID                                           *SectionDefinitionGuid,\r
+  IN UINTN                                              SectionInstance,\r
+  IN VOID                                               **Buffer,\r
+  IN OUT UINTN                                          *BufferSize,\r
+  OUT UINT32                                            *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  SEP member function.  Retrieves requested section from section stream.\r
+\r
+Arguments:  \r
+  This:                 Pointer to SEP instance.\r
+  SectionStreamHandle:  The section stream from which to extract the requested\r
+                          section.\r
+  SectionType:         A pointer to the type of section to search for.\r
+  SectionDefinitionGuid: If the section type is EFI_SECTION_GUID_DEFINED, then\r
+                        SectionDefinitionGuid indicates which of these types\r
+                          of sections to search for.\r
+  SectionInstance:      Indicates which instance of the requested section to\r
+                          return.\r
+  Buffer:               Double indirection to buffer.  If *Buffer is non-null on\r
+                          input, then the buffer is caller allocated.  If\r
+                          *Buffer is NULL, then the buffer is callee allocated.\r
+                          In either case, the requried buffer size is returned\r
+                          in *BufferSize.\r
+  BufferSize:           On input, indicates the size of *Buffer if *Buffer is\r
+                          non-null on input.  On output, indicates the required\r
+                          size (allocated size if callee allocated) of *Buffer.\r
+  AuthenticationStatus: Indicates the authentication status of the retrieved\r
+                          section.\r
+\r
+Returns:  \r
+  EFI_SUCCESS:        Section was retrieved successfully\r
+  EFI_PROTOCOL_ERROR: A GUID defined section was encountered in the section \r
+                        stream with its EFI_GUIDED_SECTION_PROCESSING_REQUIRED\r
+                        bit set, but there was no corresponding GUIDed Section \r
+                        Extraction Protocol in the handle database.  *Buffer is \r
+                        unmodified.\r
+  EFI_NOT_FOUND:      An error was encountered when parsing the SectionStream.\r
+                        This indicates the SectionStream  is not correctly \r
+                        formatted.\r
+  EFI_NOT_FOUND:      The requested section does not exist.\r
+  EFI_OUT_OF_RESOURCES: The system has insufficient resources to process the \r
+                        request.\r
+  EFI_INVALID_PARAMETER: The SectionStreamHandle does not exist.\r
+  EFI_WARN_TOO_SMALL: The size of the caller allocated input buffer is \r
+                        insufficient to contain the requested section.  The \r
+                        input buffer is filled and contents are section contents\r
+                        are truncated.\r
+\r
+--*/\r
+{\r
+  CORE_SECTION_STREAM_NODE                              *StreamNode;\r
+  EFI_TPL                                               OldTpl;\r
+  EFI_STATUS                                            Status;\r
+  CORE_SECTION_CHILD_NODE                               *ChildNode;\r
+  CORE_SECTION_STREAM_NODE                              *ChildStreamNode;\r
+  UINTN                                                 CopySize;\r
+  UINT32                                                ExtractedAuthenticationStatus;\r
+  UINTN                                                 Instance;\r
+  UINT8                                                 *CopyBuffer;\r
+  UINTN                                                 SectionSize;\r
+  \r
+\r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY);\r
+  Instance = SectionInstance + 1;\r
+  \r
+  //\r
+  // Locate target stream\r
+  //\r
+  Status = FindStreamNode (SectionStreamHandle, &StreamNode);\r
+  if (EFI_ERROR (Status)) {\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto GetSection_Done;\r
+  }\r
+  \r
+  //\r
+  // Found the stream, now locate and return the appropriate section\r
+  //\r
+  if (SectionType == NULL) {\r
+    //\r
+    // SectionType == NULL means return the WHOLE section stream...\r
+    //\r
+    CopySize = StreamNode->StreamLength;\r
+    CopyBuffer = StreamNode->StreamBuffer;\r
+    *AuthenticationStatus = StreamNode->AuthenticationStatus;\r
+  } else {\r
+    //\r
+    // There's a requested section type, so go find it and return it...\r
+    //\r
+    Status = FindChildNode (\r
+                      StreamNode, \r
+                      *SectionType, \r
+                      &Instance, \r
+                      SectionDefinitionGuid,\r
+                      &ChildNode,\r
+                      &ChildStreamNode, \r
+                      &ExtractedAuthenticationStatus\r
+                      );\r
+    if (EFI_ERROR (Status)) {\r
+      goto GetSection_Done;\r
+    }\r
+    CopySize = ChildNode->Size - sizeof (EFI_COMMON_SECTION_HEADER);\r
+    CopyBuffer = ChildStreamNode->StreamBuffer + ChildNode->OffsetInStream + sizeof (EFI_COMMON_SECTION_HEADER);\r
+    *AuthenticationStatus = ExtractedAuthenticationStatus;\r
+  }   \r
+    \r
+  SectionSize = CopySize;  \r
+  if (*Buffer != NULL) {\r
+    //\r
+    // Caller allocated buffer.  Fill to size and return required size...\r
+    //\r
+    if (*BufferSize < CopySize) {\r
+      Status = EFI_WARN_BUFFER_TOO_SMALL;\r
+      CopySize = *BufferSize;\r
+    }\r
+  } else {\r
+    //\r
+    // Callee allocated buffer.  Allocate buffer and return size.\r
+    //\r
+    *Buffer = CoreAllocateBootServicesPool (CopySize);\r
+    if (*Buffer == NULL) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto GetSection_Done;\r
+    }\r
+  }\r
+  CopyMem (*Buffer, CopyBuffer, CopySize);\r
+  *BufferSize = SectionSize;\r
+  \r
+GetSection_Done:\r
+  CoreRestoreTpl (OldTpl);\r
+  return Status;\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+EFIAPI\r
+CloseSectionStream (\r
+  IN  EFI_SECTION_EXTRACTION_PROTOCOL           *This,\r
+  IN  UINTN                                     StreamHandleToClose\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  SEP member function.  Deletes an existing section stream\r
+\r
+Arguments:\r
+  This                - Indicates the calling context.\r
+  StreamHandleToClose - Indicates the stream to close\r
+\r
+Returns:\r
+  EFI_SUCCESS\r
+  EFI_OUT_OF_RESOURCES - memory allocation failed.\r
+  EFI_INVALID_PARAMETER - section stream does not end concident with end of\r
+                          last section.\r
+\r
+--*/\r
+{\r
+  CORE_SECTION_STREAM_NODE                      *StreamNode;\r
+  EFI_TPL                                       OldTpl;\r
+  EFI_STATUS                                    Status;\r
+  LIST_ENTRY                                    *Link;\r
+  CORE_SECTION_CHILD_NODE                       *ChildNode;\r
+  \r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY);\r
+  \r
+  //\r
+  // Locate target stream\r
+  //\r
+  Status = FindStreamNode (StreamHandleToClose, &StreamNode);\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // Found the stream, so close it\r
+    //\r
+    RemoveEntryList (&StreamNode->Link);\r
+    while (!IsListEmpty (&StreamNode->Children)) {\r
+      Link = GetFirstNode (&StreamNode->Children);\r
+      ChildNode = CHILD_SECTION_NODE_FROM_LINK (Link);\r
+      FreeChildNode (ChildNode);\r
+    }\r
+    CoreFreePool (StreamNode->StreamBuffer);\r
+    CoreFreePool (StreamNode);\r
+    Status = EFI_SUCCESS;\r
+  } else {\r
+    Status = EFI_INVALID_PARAMETER;\r
+  }\r
+  \r
+  CoreRestoreTpl (OldTpl);\r
+  return Status;\r
+}\r
+\r
+\r
+STATIC\r
+BOOLEAN\r
+ChildIsType (\r
+  IN CORE_SECTION_STREAM_NODE *Stream,\r
+  IN CORE_SECTION_CHILD_NODE  *Child,\r
+  IN EFI_SECTION_TYPE         SearchType,\r
+  IN EFI_GUID                 *SectionDefinitionGuid\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Worker function.  Determine if the input stream:child matches the input type.\r
+\r
+Arguments:\r
+  Stream              - Indicates the section stream associated with the child\r
+  Child               - Indicates the child to check\r
+  SearchType          - Indicates the type of section to check against for\r
+  SectionDefinitionGuid - Indicates the GUID to check against if the type is\r
+                        EFI_SECTION_GUID_DEFINED\r
+Returns:\r
+  TRUE                - The child matches\r
+  FALSE               - The child doesn't match\r
+\r
+--*/\r
+{\r
+  EFI_GUID_DEFINED_SECTION    *GuidedSection;\r
+  \r
+  if (SearchType == EFI_SECTION_ALL) {\r
+    return TRUE;\r
+  }\r
+  if (Child->Type != SearchType) {\r
+    return FALSE;\r
+  }\r
+  if (SearchType != EFI_SECTION_GUID_DEFINED) {\r
+    return TRUE;\r
+  }\r
+  GuidedSection = (EFI_GUID_DEFINED_SECTION * )(Stream->StreamBuffer + Child->OffsetInStream);\r
+  return CompareGuid (&GuidedSection->SectionDefinitionGuid, SectionDefinitionGuid);\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+FindChildNode (\r
+  IN     CORE_SECTION_STREAM_NODE                   *SourceStream,\r
+  IN     EFI_SECTION_TYPE                           SearchType,\r
+  IN OUT UINTN                                      *SectionInstance,\r
+  IN     EFI_GUID                                   *SectionDefinitionGuid,\r
+  OUT    CORE_SECTION_CHILD_NODE                    **FoundChild,\r
+  OUT    CORE_SECTION_STREAM_NODE                   **FoundStream,\r
+  OUT    UINT32                                     *AuthenticationStatus\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Worker function  Recursively searches / builds section stream database\r
+  looking for requested section.\r
+\r
+Arguments:\r
+  SourceStream        - Indicates the section stream in which to do the search.\r
+  SearchType          - Indicates the type of section to search for.\r
+  SectionInstance     - Indicates which instance of section to find.  This is\r
+                        an in/out parameter to deal with recursions.\r
+  SectionDefinitionGuid  - Guid of section definition\r
+  FoundChild          - Output indicating the child node that is found.\r
+  FoundStream         - Output indicating which section stream the child was\r
+                        found in.  If this stream was generated as a result of\r
+                        an encapsulation section, the streamhandle is visible\r
+                        within the SEP driver only.\r
+  AuthenticationStatus- Indicates the authentication status of the found section.\r
+\r
+Returns:\r
+  EFI_SUCCESS         - Child node was found and returned.\r
+  EFI_OUT_OF_RESOURCES- Memory allocation failed.\r
+  EFI_NOT_FOUND       - Requested child node does not exist.\r
+  EFI_PROTOCOL_ERROR  - a required GUIDED section extraction protocol does not\r
+                        exist\r
+\r
+--*/\r
+{\r
+  CORE_SECTION_CHILD_NODE                       *CurrentChildNode;\r
+  CORE_SECTION_CHILD_NODE                       *RecursedChildNode;\r
+  CORE_SECTION_STREAM_NODE                      *RecursedFoundStream;\r
+  UINT32                                        NextChildOffset;\r
+  EFI_STATUS                                    ErrorStatus;\r
+  EFI_STATUS                                    Status;\r
+  \r
+  CurrentChildNode = NULL;\r
+  ErrorStatus = EFI_NOT_FOUND;\r
+  \r
+  if (SourceStream->StreamLength == 0) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+  \r
+  if (IsListEmpty (&SourceStream->Children) && \r
+                   SourceStream->StreamLength > sizeof (EFI_COMMON_SECTION_HEADER)) {\r
+    //\r
+    // This occurs when a section stream exists, but no child sections\r
+    // have been parsed out yet.  Therefore, extract the first child and add it\r
+    // to the list of children so we can get started.\r
+    //\r
+    Status = CreateChildNode (SourceStream, 0, &CurrentChildNode);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+  }\r
+  \r
+  //\r
+  // At least one child has been parsed out of the section stream.  So, walk\r
+  // through the sections that have already been parsed out looking for the\r
+  // requested section, if necessary, continue parsing section stream and\r
+  // adding children until either the requested section is found, or we run\r
+  // out of data\r
+  //\r
+  CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetFirstNode(&SourceStream->Children));\r
+\r
+  for (;;) {\r
+    if (ChildIsType (SourceStream, CurrentChildNode, SearchType, SectionDefinitionGuid)) {\r
+      //\r
+      // The type matches, so check the instance count to see if it's the one we want\r
+      //\r
+      (*SectionInstance)--;\r
+      if (*SectionInstance == 0) {\r
+        //\r
+        // Got it!\r
+        //\r
+        *FoundChild = CurrentChildNode;\r
+        *FoundStream = SourceStream;\r
+        *AuthenticationStatus = SourceStream->AuthenticationStatus;\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+    \r
+    if (CurrentChildNode->EncapsulatedStreamHandle != NULL_STREAM_HANDLE) {\r
+      //\r
+      // If the current node is an encapsulating node, recurse into it...\r
+      //\r
+      Status = FindChildNode (\r
+                (CORE_SECTION_STREAM_NODE *)CurrentChildNode->EncapsulatedStreamHandle,\r
+                SearchType,\r
+                SectionInstance,\r
+                SectionDefinitionGuid,\r
+                &RecursedChildNode,\r
+                &RecursedFoundStream,\r
+                AuthenticationStatus\r
+                );\r
+      //\r
+      // If the status is not EFI_SUCCESS, just save the error code and continue\r
+      // to find the request child node in the rest stream.\r
+      //\r
+      if (*SectionInstance == 0) {\r
+        ASSERT_EFI_ERROR (Status);\r
+        *FoundChild = RecursedChildNode;\r
+        *FoundStream = RecursedFoundStream;\r
+        return EFI_SUCCESS;\r
+      } else {\r
+        ErrorStatus = Status;\r
+      }\r
+    }\r
+    \r
+    if (!IsNodeAtEnd (&SourceStream->Children, &CurrentChildNode->Link)) {\r
+      //\r
+      // We haven't found the child node we're interested in yet, but there's\r
+      // still more nodes that have already been parsed so get the next one\r
+      // and continue searching..\r
+      //\r
+      CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetNextNode (&SourceStream->Children, &CurrentChildNode->Link));\r
+    } else {\r
+      //\r
+      // We've exhausted children that have already been parsed, so see if\r
+      // there's any more data and continue parsing out more children if there\r
+      // is.\r
+      //\r
+      NextChildOffset = CurrentChildNode->OffsetInStream + CurrentChildNode->Size;\r
+      //\r
+      // Round up to 4 byte boundary\r
+      //\r
+      NextChildOffset += 3;\r
+      NextChildOffset &= ~(UINTN)3;\r
+      if (NextChildOffset <= SourceStream->StreamLength - sizeof (EFI_COMMON_SECTION_HEADER)) {\r
+        //\r
+        // There's an unparsed child remaining in the stream, so create a new child node\r
+        //\r
+        Status = CreateChildNode (SourceStream, NextChildOffset, &CurrentChildNode);\r
+        if (EFI_ERROR (Status)) {\r
+          return Status;\r
+        }\r
+      } else {\r
+        ASSERT (EFI_ERROR (ErrorStatus));\r
+        return ErrorStatus;\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+CreateChildNode (\r
+  IN     CORE_SECTION_STREAM_NODE              *Stream,\r
+  IN     UINT32                                ChildOffset,\r
+     OUT CORE_SECTION_CHILD_NODE               **ChildNode\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Worker function.  Constructor for new child nodes.\r
+\r
+Arguments:\r
+  Stream              - Indicates the section stream in which to add the child.\r
+  ChildOffset         - Indicates the offset in Stream that is the beginning\r
+                        of the child section.\r
+  ChildNode           - Indicates the Callee allocated and initialized child.\r
+\r
+Returns:\r
+  EFI_SUCCESS         - Child node was found and returned.\r
+  EFI_OUT_OF_RESOURCES- Memory allocation failed.\r
+  EFI_PROTOCOL_ERROR  - Encapsulation sections produce new stream handles when\r
+                        the child node is created.  If the section type is GUID\r
+                        defined, and the extraction GUID does not exist, and\r
+                        producing the stream requires the GUID, then a protocol\r
+                        error is generated and no child is produced.\r
+  Values returned by OpenSectionStreamEx.\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                                   Status;\r
+  EFI_COMMON_SECTION_HEADER                    *SectionHeader;\r
+  EFI_COMPRESSION_SECTION                      *CompressionHeader;\r
+  EFI_GUID_DEFINED_SECTION                     *GuidedHeader;\r
+  EFI_TIANO_DECOMPRESS_PROTOCOL                *Decompress;\r
+  EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL       *GuidedExtraction;\r
+  VOID                                         *NewStreamBuffer;\r
+  VOID                                         *ScratchBuffer;\r
+  UINT32                                       ScratchSize;\r
+  UINTN                                        NewStreamBufferSize;\r
+  UINT32                                       AuthenticationStatus;\r
+  UINT32                                       SectionLength;\r
+    \r
+  CORE_SECTION_CHILD_NODE                      *Node;\r
+\r
+  SectionHeader = (EFI_COMMON_SECTION_HEADER *) (Stream->StreamBuffer + ChildOffset);\r
+\r
+  //\r
+  // Allocate a new node\r
+  //\r
+  *ChildNode = CoreAllocateBootServicesPool (sizeof (CORE_SECTION_CHILD_NODE));\r
+  Node = *ChildNode;\r
+  if (Node == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+  \r
+  //\r
+  // Now initialize it\r
+  //\r
+  Node->Signature = CORE_SECTION_CHILD_SIGNATURE;\r
+  Node->Type = SectionHeader->Type;\r
+  Node->Size = SECTION_SIZE (SectionHeader);\r
+  Node->OffsetInStream = ChildOffset;\r
+  Node->EncapsulatedStreamHandle = NULL_STREAM_HANDLE;\r
+  Node->EncapsulationGuid = NULL;\r
+  \r
+  //\r
+  // If it's an encapsulating section, then create the new section stream also\r
+  //\r
+  switch (Node->Type) {\r
+    case EFI_SECTION_COMPRESSION:\r
+      //\r
+      // Get the CompressionSectionHeader\r
+      //\r
+      ASSERT (Node->Size >= sizeof (EFI_COMPRESSION_SECTION));\r
+      \r
+      CompressionHeader = (EFI_COMPRESSION_SECTION *) SectionHeader;\r
+      \r
+      //\r
+      // Allocate space for the new stream\r
+      //\r
+      if (CompressionHeader->UncompressedLength > 0) {\r
+        NewStreamBufferSize = CompressionHeader->UncompressedLength;\r
+        NewStreamBuffer = CoreAllocateBootServicesPool (NewStreamBufferSize);\r
+        if (NewStreamBuffer == NULL) {\r
+          CoreFreePool (Node);\r
+          return EFI_OUT_OF_RESOURCES;\r
+        }\r
+        \r
+        if (CompressionHeader->CompressionType == EFI_NOT_COMPRESSED) {\r
+          //\r
+          // stream is not actually compressed, just encapsulated.  So just copy it.\r
+          //\r
+          CopyMem (NewStreamBuffer, CompressionHeader + 1, NewStreamBufferSize);\r
+        } else if (CompressionHeader->CompressionType == EFI_STANDARD_COMPRESSION) {\r
+          //\r
+          // Only support the EFI_SATNDARD_COMPRESSION algorithm.\r
+          // \r
+\r
+          //\r
+          // Decompress the stream\r
+          //\r
+          Status = CoreLocateProtocol (&gEfiDecompressProtocolGuid, NULL, (VOID **)&Decompress);\r
+          \r
+          ASSERT_EFI_ERROR (Status);\r
+          \r
+          Status = Decompress->GetInfo (\r
+                                 Decompress,\r
+                                 CompressionHeader + 1,\r
+                                 Node->Size - sizeof (EFI_COMPRESSION_SECTION),\r
+                                 (UINT32 *)&NewStreamBufferSize,\r
+                                 &ScratchSize\r
+                                 );\r
+          ASSERT_EFI_ERROR (Status);\r
+          ASSERT (NewStreamBufferSize == CompressionHeader->UncompressedLength);\r
+\r
+          ScratchBuffer = CoreAllocateBootServicesPool (ScratchSize);\r
+          if (ScratchBuffer == NULL) {\r
+            CoreFreePool (Node);\r
+            CoreFreePool (NewStreamBuffer);\r
+            return EFI_OUT_OF_RESOURCES;\r
+          }\r
+\r
+          Status = Decompress->Decompress (\r
+                                 Decompress,\r
+                                 CompressionHeader + 1,\r
+                                 Node->Size - sizeof (EFI_COMPRESSION_SECTION),\r
+                                 NewStreamBuffer,\r
+                                 (UINT32)NewStreamBufferSize,\r
+                                 ScratchBuffer,\r
+                                 ScratchSize\r
+                                 );\r
+          ASSERT_EFI_ERROR (Status);\r
+          CoreFreePool (ScratchBuffer);                                           \r
+        }\r
+      } else {\r
+        NewStreamBuffer = NULL;\r
+        NewStreamBufferSize = 0;\r
+      }\r
+      \r
+      Status = OpenSectionStreamEx (\r
+                 NewStreamBufferSize,\r
+                 NewStreamBuffer,\r
+                 FALSE,\r
+                 Stream->AuthenticationStatus,\r
+                 &Node->EncapsulatedStreamHandle\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        CoreFreePool (Node);\r
+        CoreFreePool (NewStreamBuffer);\r
+        return Status;\r
+      }\r
+      break;\r
+\r
+    case EFI_SECTION_GUID_DEFINED:\r
+      GuidedHeader = (EFI_GUID_DEFINED_SECTION *) SectionHeader;\r
+      Node->EncapsulationGuid = &GuidedHeader->SectionDefinitionGuid;\r
+      Status = CoreLocateProtocol (Node->EncapsulationGuid, NULL, (VOID **)&GuidedExtraction);\r
+      if (!EFI_ERROR (Status)) {\r
+        //\r
+        // NewStreamBuffer is always allocated by ExtractSection... No caller\r
+        // allocation here.\r
+        //\r
+        Status = GuidedExtraction->ExtractSection (\r
+                                     GuidedExtraction,\r
+                                     GuidedHeader,\r
+                                     &NewStreamBuffer,\r
+                                     &NewStreamBufferSize,\r
+                                     &AuthenticationStatus\r
+                                     );\r
+        if (EFI_ERROR (Status)) {\r
+          CoreFreePool (*ChildNode);\r
+          return EFI_PROTOCOL_ERROR;\r
+        }\r
+        \r
+        //\r
+        // Make sure we initialize the new stream with the correct \r
+        // authentication status for both aggregate and local status fields.\r
+        //\r
+        if (GuidedHeader->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) {\r
+          //\r
+          // OR in the parent stream's aggregate status.\r
+          //\r
+          AuthenticationStatus |= Stream->AuthenticationStatus & EFI_AGGREGATE_AUTH_STATUS_ALL;\r
+        } else {\r
+          //\r
+          // since there's no authentication data contributed by the section,\r
+          // just inherit the full value from our immediate parent.\r
+          //\r
+          AuthenticationStatus = Stream->AuthenticationStatus;\r
+        }\r
+        \r
+        Status = OpenSectionStreamEx (\r
+                   NewStreamBufferSize,\r
+                   NewStreamBuffer,\r
+                   FALSE,\r
+                   AuthenticationStatus,\r
+                   &Node->EncapsulatedStreamHandle\r
+                   );\r
+        if (EFI_ERROR (Status)) {\r
+          CoreFreePool (*ChildNode);\r
+          CoreFreePool (NewStreamBuffer);\r
+          return Status;\r
+        }\r
+      } else {\r
+        //\r
+        // There's no GUIDed section extraction protocol available.\r
+        //\r
+        if (GuidedHeader->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) {\r
+          //\r
+          // If the section REQUIRES an extraction protocol, then we're toast\r
+          //\r
+          CoreFreePool (*ChildNode);\r
+          return EFI_PROTOCOL_ERROR;\r
+        }\r
+        \r
+        //\r
+        // Figure out the proper authentication status\r
+        //\r
+        AuthenticationStatus = Stream->AuthenticationStatus;\r
+        if (GuidedHeader->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) {\r
+          //\r
+          //  The local status of the new stream is contained in \r
+          //  AuthenticaionStatus.  This value needs to be ORed into the\r
+          //  Aggregate bits also...\r
+          //\r
+          \r
+          //\r
+          // Clear out and initialize the local status\r
+          //\r
+          AuthenticationStatus &= ~EFI_LOCAL_AUTH_STATUS_ALL;\r
+          AuthenticationStatus |= EFI_LOCAL_AUTH_STATUS_IMAGE_SIGNED | EFI_LOCAL_AUTH_STATUS_NOT_TESTED;\r
+          //\r
+          // OR local status into aggregate status\r
+          //\r
+          AuthenticationStatus |= AuthenticationStatus >> 16;\r
+        }\r
+        \r
+        SectionLength = SECTION_SIZE (GuidedHeader);\r
+        Status = OpenSectionStreamEx (\r
+                   SectionLength - GuidedHeader->DataOffset,\r
+                   (UINT8 *) GuidedHeader + GuidedHeader->DataOffset,\r
+                   TRUE,\r
+                   AuthenticationStatus,\r
+                   &Node->EncapsulatedStreamHandle\r
+                   );\r
+        if (EFI_ERROR (Status)) {\r
+          CoreFreePool (Node);\r
+          return Status;\r
+        }\r
+      }\r
+      \r
+      if ((AuthenticationStatus & EFI_LOCAL_AUTH_STATUS_ALL) == \r
+            (EFI_LOCAL_AUTH_STATUS_IMAGE_SIGNED | EFI_LOCAL_AUTH_STATUS_NOT_TESTED)) {\r
+        //\r
+        // Need to register for RPN for when the required GUIDed extraction\r
+        // protocol becomes available.  This will enable us to refresh the\r
+        // AuthenticationStatus cached in the Stream if it's ever requested\r
+        // again.\r
+        //\r
+        CreateGuidedExtractionRpnEvent (Stream, Node);\r
+      }\r
+      \r
+      break;\r
+\r
+    default:\r
+      \r
+      //\r
+      // Nothing to do if it's a leaf\r
+      //\r
+      break;\r
+  }\r
+  \r
+  //\r
+  // Last, add the new child node to the stream\r
+  //\r
+  InsertTailList (&Stream->Children, &Node->Link);\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+STATIC\r
+VOID\r
+CreateGuidedExtractionRpnEvent (\r
+  IN CORE_SECTION_STREAM_NODE       *ParentStream,\r
+  IN CORE_SECTION_CHILD_NODE        *ChildNode\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Worker function.  Constructor for RPN event if needed to keep AuthenticationStatus\r
+  cache correct when a missing GUIDED_SECTION_EXTRACTION_PROTOCOL appears...\r
+\r
+Arguments:\r
+  ParentStream        - Indicates the parent of the ecnapsulation section (child)\r
+  ChildNode           - Indicates the child node that is the encapsulation section.\r
+\r
+Returns:\r
+  None\r
+\r
+--*/\r
+{\r
+  RPN_EVENT_CONTEXT *Context;\r
+  \r
+  //\r
+  // Allocate new event structure and context\r
+  //\r
+  Context = CoreAllocateBootServicesPool (sizeof (RPN_EVENT_CONTEXT));\r
+  ASSERT (Context != NULL);\r
+  \r
+  Context->ChildNode = ChildNode;\r
+  Context->ParentStream = ParentStream;\r
\r
+  Context->Event = CoreCreateProtocolNotifyEvent (\r
+                    Context->ChildNode->EncapsulationGuid,\r
+                    TPL_NOTIFY,\r
+                    NotifyGuidedExtraction,\r
+                    Context,\r
+                    &Context->Registration,\r
+                    FALSE\r
+                    );\r
+}\r
+  \r
+  \r
+STATIC\r
+VOID\r
+EFIAPI\r
+NotifyGuidedExtraction (\r
+  IN   EFI_EVENT   Event,\r
+  IN   VOID        *RpnContext\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  RPN callback function.  Removes a stale section stream and re-initializes it\r
+  with an updated AuthenticationStatus.\r
+\r
+Arguments:\r
+  Event               - The event that fired\r
+  RpnContext          - A pointer to the context that allows us to identify\r
+                        the relevent encapsulation...\r
+\r
+Returns:\r
+  None\r
+\r
+--*/\r
+{\r
+  EFI_STATUS                              Status;\r
+  EFI_GUID_DEFINED_SECTION                *GuidedHeader;\r
+  EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL  *GuidedExtraction;\r
+  VOID                                    *NewStreamBuffer;\r
+  UINTN                                   NewStreamBufferSize;\r
+  UINT32                                  AuthenticationStatus;\r
+  RPN_EVENT_CONTEXT                       *Context;\r
+  \r
+  Context = RpnContext;\r
+  \r
+  Status = CloseSectionStream (&mSectionExtraction, Context->ChildNode->EncapsulatedStreamHandle);\r
+  if (!EFI_ERROR (Status)) {\r
+    //\r
+    // The stream closed successfully, so re-open the stream with correct AuthenticationStatus\r
+    //\r
+  \r
+    GuidedHeader = (EFI_GUID_DEFINED_SECTION *) \r
+      (Context->ParentStream->StreamBuffer + Context->ChildNode->OffsetInStream);\r
+    ASSERT (GuidedHeader->CommonHeader.Type == EFI_SECTION_GUID_DEFINED);\r
+    \r
+    Status = CoreLocateProtocol (Context->ChildNode->EncapsulationGuid, NULL, (VOID **)&GuidedExtraction);\r
+    ASSERT_EFI_ERROR (Status);\r
+\r
+    \r
+    Status = GuidedExtraction->ExtractSection (\r
+                                 GuidedExtraction,\r
+                                 GuidedHeader,\r
+                                 &NewStreamBuffer,\r
+                                 &NewStreamBufferSize,\r
+                                 &AuthenticationStatus\r
+                                 );\r
+    ASSERT_EFI_ERROR (Status);\r
+    //\r
+    // OR in the parent stream's aggregagate status.\r
+    //\r
+    AuthenticationStatus |= Context->ParentStream->AuthenticationStatus & EFI_AGGREGATE_AUTH_STATUS_ALL;\r
+    Status = OpenSectionStreamEx (\r
+               NewStreamBufferSize,\r
+               NewStreamBuffer,\r
+               FALSE,\r
+               AuthenticationStatus,\r
+               &Context->ChildNode->EncapsulatedStreamHandle\r
+               );\r
+    ASSERT_EFI_ERROR (Status);\r
+  }\r
+\r
+  //\r
+  //  If above, the stream  did not close successfully, it indicates it's\r
+  //  alread been closed by someone, so just destroy the event and be done with\r
+  //  it.\r
+  //\r
+  \r
+  CoreCloseEvent (Event);\r
+  CoreFreePool (Context);\r
+}  \r
+  \r
+\r
+STATIC\r
+VOID\r
+FreeChildNode (\r
+  IN  CORE_SECTION_CHILD_NODE                   *ChildNode\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Worker function.  Destructor for child nodes.\r
+\r
+Arguments:\r
+  ChildNode           - Indicates the node to destroy\r
+\r
+Returns:\r
+  none\r
+\r
+--*/\r
+{\r
+  ASSERT (ChildNode->Signature == CORE_SECTION_CHILD_SIGNATURE);\r
+  //\r
+  // Remove the child from it's list\r
+  //\r
+  RemoveEntryList (&ChildNode->Link);\r
+  \r
+  if (ChildNode->EncapsulatedStreamHandle != NULL_STREAM_HANDLE) {\r
+    //\r
+    // If it's an encapsulating section, we close the resulting section stream.\r
+    // CloseSectionStream will free all memory associated with the stream.\r
+    //\r
+    CloseSectionStream (&mSectionExtraction, ChildNode->EncapsulatedStreamHandle);\r
+  }\r
+  //\r
+  // Last, free the child node itself\r
+  //\r
+  CoreFreePool (ChildNode);\r
+}  \r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+OpenSectionStreamEx (\r
+  IN     UINTN                                     SectionStreamLength,\r
+  IN     VOID                                      *SectionStream,\r
+  IN     BOOLEAN                                   AllocateBuffer,\r
+  IN     UINT32                                    AuthenticationStatus,   \r
+     OUT UINTN                                     *SectionStreamHandle\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+    Worker function.  Constructor for section streams.\r
+\r
+  Arguments:\r
+    SectionStreamLength - Size in bytes of the section stream.\r
+    SectionStream       - Buffer containing the new section stream.\r
+    AllocateBuffer      - Indicates whether the stream buffer is to be copied\r
+                          or the input buffer is to be used in place.\r
+    AuthenticationStatus- Indicates the default authentication status for the\r
+                          new stream.\r
+    SectionStreamHandle - A pointer to a caller allocated section stream handle.\r
+\r
+  Returns:\r
+    EFI_SUCCESS         - Stream was added to stream database.\r
+    EFI_OUT_OF_RESOURCES - memory allocation failed.\r
+\r
+--*/\r
+{\r
+  CORE_SECTION_STREAM_NODE    *NewStream;\r
+  EFI_TPL                     OldTpl;\r
+  \r
+  //\r
+  // Allocate a new stream\r
+  //\r
+  NewStream = CoreAllocateBootServicesPool (sizeof (CORE_SECTION_STREAM_NODE));\r
+  if (NewStream == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+  \r
+  if (AllocateBuffer) { \r
+    //\r
+    // if we're here, we're double buffering, allocate the buffer and copy the\r
+    // data in\r
+    //\r
+    if (SectionStreamLength > 0) {\r
+      NewStream->StreamBuffer = CoreAllocateBootServicesPool (SectionStreamLength); \r
+      if (NewStream->StreamBuffer == NULL) {\r
+        CoreFreePool (NewStream);\r
+        return EFI_OUT_OF_RESOURCES;\r
+      }\r
+      //\r
+      // Copy in stream data\r
+      //\r
+      CopyMem (NewStream->StreamBuffer, SectionStream, SectionStreamLength);\r
+    } else {\r
+      //\r
+      // It's possible to have a zero length section stream.\r
+      //\r
+      NewStream->StreamBuffer = NULL;\r
+    }\r
+  } else {\r
+    //\r
+    // If were here, the caller has supplied the buffer (it's an internal call)\r
+    // so just assign the buffer.  This happens when we open section streams\r
+    // as a result of expanding an encapsulating section.\r
+    //\r
+    NewStream->StreamBuffer = SectionStream;\r
+  }\r
+  \r
+  //\r
+  // Initialize the rest of the section stream\r
+  //\r
+  NewStream->Signature = CORE_SECTION_STREAM_SIGNATURE;\r
+  NewStream->StreamHandle = (UINTN) NewStream;\r
+  NewStream->StreamLength = SectionStreamLength;\r
+  InitializeListHead (&NewStream->Children);\r
+  NewStream->AuthenticationStatus = AuthenticationStatus;\r
+  \r
+  //\r
+  // Add new stream to stream list\r
+  //\r
+  OldTpl = CoreRaiseTpl (TPL_NOTIFY);\r
+  InsertTailList (&mStreamRoot, &NewStream->Link);\r
+  CoreRestoreTpl (OldTpl);\r
+\r
+  *SectionStreamHandle = NewStream->StreamHandle;\r
+  \r
+  return EFI_SUCCESS;\r
+}\r
+\r
+\r
+STATIC\r
+EFI_STATUS\r
+FindStreamNode (\r
+  IN  UINTN                                     SearchHandle,\r
+  OUT CORE_SECTION_STREAM_NODE                  **FoundStream\r
+  )\r
+/*++\r
+\r
+  Routine Description:\r
+    Worker function.  Search stream database for requested stream handle.\r
+\r
+  Arguments:\r
+    SearchHandle        - Indicates which stream to look for.\r
+    FoundStream         - Output pointer to the found stream.\r
+\r
+  Returns:\r
+    EFI_SUCCESS         - StreamHandle was found and *FoundStream contains\r
+                          the stream node.\r
+    EFI_NOT_FOUND       - SearchHandle was not found in the stream database.\r
+\r
+--*/\r
+{  \r
+  CORE_SECTION_STREAM_NODE                      *StreamNode;\r
+  \r
+  if (!IsListEmpty (&mStreamRoot)) {\r
+    StreamNode = STREAM_NODE_FROM_LINK (GetFirstNode (&mStreamRoot));\r
+    for (;;) {\r
+      if (StreamNode->StreamHandle == SearchHandle) {\r
+        *FoundStream = StreamNode;\r
+        return EFI_SUCCESS;\r
+      } else if (IsNodeAtEnd (&mStreamRoot, &StreamNode->Link)) {\r
+        break;\r
+      } else {\r
+        StreamNode = STREAM_NODE_FROM_LINK (GetNextNode (&mStreamRoot, &StreamNode->Link));\r
+      }\r
+    }\r
+  }\r
+  \r
+  return EFI_NOT_FOUND;\r
+}\r
+\r
+\r
+STATIC\r
+BOOLEAN\r
+IsValidSectionStream (\r
+  IN  VOID              *SectionStream,\r
+  IN  UINTN             SectionStreamLength\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Check if a stream is valid.\r
+\r
+Arguments:\r
+  SectionStream         - The section stream to be checked\r
+  SectionStreamLength   - The length of section stream\r
+\r
+Returns:\r
+  TRUE\r
+  FALSE\r
+\r
+--*/\r
+{\r
+  UINTN                       TotalLength;\r
+  UINTN                       SectionLength;\r
+  EFI_COMMON_SECTION_HEADER   *SectionHeader;\r
+  EFI_COMMON_SECTION_HEADER   *NextSectionHeader;\r
+\r
+  TotalLength = 0;\r
+  SectionHeader = (EFI_COMMON_SECTION_HEADER *)SectionStream;\r
+  \r
+  while (TotalLength < SectionStreamLength) {\r
+    SectionLength = SECTION_SIZE (SectionHeader);\r
+    TotalLength += SectionLength;\r
+\r
+    if (TotalLength == SectionStreamLength) {\r
+      return TRUE;    \r
+    }\r
+\r
+    //\r
+    // Move to the next byte following the section...\r
+    //\r
+    SectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) SectionHeader + SectionLength);\r
+    \r
+    //\r
+    // Figure out where the next section begins\r
+    //\r
+    NextSectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINTN) SectionHeader + 3);\r
+    NextSectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINTN) NextSectionHeader & ~(UINTN)3);\r
+    TotalLength += (UINTN) NextSectionHeader - (UINTN) SectionHeader;\r
+    SectionHeader = NextSectionHeader;\r
+  }\r
+\r
+  ASSERT (FALSE);\r
+  return FALSE;\r
+}\r
diff --git a/MdeModulePkg/Core/Dxe/gcd.h b/MdeModulePkg/Core/Dxe/gcd.h
new file mode 100644 (file)
index 0000000..445821e
--- /dev/null
@@ -0,0 +1,51 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+    gcd.h\r
+\r
+Abstract:\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#ifndef _GCD_H\r
+#define _GCD_H\r
+\r
+//\r
+// GCD Operations\r
+//\r
+#define GCD_MEMORY_SPACE_OPERATION 0x20\r
+#define GCD_IO_SPACE_OPERATION     0x40\r
+\r
+#define GCD_ADD_MEMORY_OPERATION             (GCD_MEMORY_SPACE_OPERATION | 0)\r
+#define GCD_ALLOCATE_MEMORY_OPERATION        (GCD_MEMORY_SPACE_OPERATION | 1)\r
+#define GCD_FREE_MEMORY_OPERATION            (GCD_MEMORY_SPACE_OPERATION | 2)\r
+#define GCD_REMOVE_MEMORY_OPERATION          (GCD_MEMORY_SPACE_OPERATION | 3)\r
+#define GCD_SET_ATTRIBUTES_MEMORY_OPERATION  (GCD_MEMORY_SPACE_OPERATION | 4)\r
+\r
+#define GCD_ADD_IO_OPERATION                 (GCD_IO_SPACE_OPERATION | 0)\r
+#define GCD_ALLOCATE_IO_OPERATION            (GCD_IO_SPACE_OPERATION | 1)\r
+#define GCD_FREE_IO_OPERATION                (GCD_IO_SPACE_OPERATION | 2)\r
+#define GCD_REMOVE_IO_OPERATION              (GCD_IO_SPACE_OPERATION | 3)\r
+\r
+//\r
+// The data structure used to convert from GCD attributes to EFI Memory Map attributes\r
+//\r
+typedef struct {\r
+  UINT64   Attribute;\r
+  UINT64   Capability;\r
+  BOOLEAN  Memory;\r
+} GCD_ATTRIBUTE_CONVERSION_ENTRY;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/hand.h b/MdeModulePkg/Core/Dxe/hand.h
new file mode 100644 (file)
index 0000000..c61af16
--- /dev/null
@@ -0,0 +1,337 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  hand.h\r
+\r
+Abstract:\r
+\r
+  EFI internal protocol definitions\r
+\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#ifndef  _HAND_H_\r
+#define  _HAND_H_\r
+\r
+\r
+//\r
+// IHANDLE - contains a list of protocol handles\r
+//\r
+\r
+#define EFI_HANDLE_SIGNATURE            EFI_SIGNATURE_32('h','n','d','l')\r
+typedef struct {\r
+  UINTN               Signature;\r
+  LIST_ENTRY          AllHandles;     // All handles list of IHANDLE\r
+  LIST_ENTRY          Protocols;      // List of PROTOCOL_INTERFACE's for this handle\r
+  UINTN               LocateRequest;  // \r
+  UINT64              Key;            // The Handle Database Key value when this handle was last created or modified\r
+} IHANDLE;\r
+\r
+#define ASSERT_IS_HANDLE(a)  ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE)\r
+\r
+\r
+//\r
+// PROTOCOL_ENTRY - each different protocol has 1 entry in the protocol \r
+// database.  Each handler that supports this protocol is listed, along\r
+// with a list of registered notifies.\r
+//\r
+\r
+#define PROTOCOL_ENTRY_SIGNATURE        EFI_SIGNATURE_32('p','r','t','e')\r
+typedef struct {\r
+  UINTN               Signature;\r
+  LIST_ENTRY          AllEntries;             // All entries\r
+  EFI_GUID            ProtocolID;             // ID of the protocol\r
+  LIST_ENTRY          Protocols;              // All protocol interfaces\r
+  LIST_ENTRY          Notify;                 // Registerd notification handlers\r
+} PROTOCOL_ENTRY;\r
+\r
+//\r
+// PROTOCOL_INTERFACE - each protocol installed on a handle is tracked\r
+// with a protocol interface structure\r
+//\r
+\r
+#define PROTOCOL_INTERFACE_SIGNATURE  EFI_SIGNATURE_32('p','i','f','c')\r
+typedef struct {\r
+  UINTN                       Signature;\r
+  EFI_HANDLE                  Handle;     // Back pointer\r
+  LIST_ENTRY                  Link;       // Link on IHANDLE.Protocols\r
+  LIST_ENTRY                  ByProtocol; // Link on PROTOCOL_ENTRY.Protocols\r
+  PROTOCOL_ENTRY              *Protocol;  // The protocol ID\r
+  VOID                        *Interface; // The interface value\r
+                                          \r
+  LIST_ENTRY                  OpenList;       // OPEN_PROTOCOL_DATA list.\r
+  UINTN                       OpenListCount;  \r
+  \r
+  EFI_HANDLE                  ControllerHandle;\r
+\r
+} PROTOCOL_INTERFACE;\r
+\r
+#define OPEN_PROTOCOL_DATA_SIGNATURE  EFI_SIGNATURE_32('p','o','d','l')\r
+\r
+typedef struct {\r
+  UINTN                       Signature;\r
+  LIST_ENTRY                  Link;\r
+\r
+  EFI_HANDLE                  AgentHandle;\r
+  EFI_HANDLE                  ControllerHandle;\r
+  UINT32                      Attributes;\r
+  UINT32                      OpenCount;\r
+} OPEN_PROTOCOL_DATA;\r
+\r
+\r
+//\r
+// PROTOCOL_NOTIFY - used for each register notification for a protocol\r
+//\r
+\r
+#define PROTOCOL_NOTIFY_SIGNATURE       EFI_SIGNATURE_32('p','r','t','n')\r
+typedef struct {\r
+  UINTN               Signature;\r
+  PROTOCOL_ENTRY      *Protocol;\r
+  LIST_ENTRY          Link;                   // All notifications for this protocol\r
+  EFI_EVENT           Event;                  // Event to notify\r
+  LIST_ENTRY          *Position;              // Last position notified\r
+} PROTOCOL_NOTIFY;\r
+\r
+//\r
+// Internal prototypes\r
+//\r
+\r
+\r
+PROTOCOL_ENTRY  *\r
+CoreFindProtocolEntry (\r
+  IN EFI_GUID     *Protocol,\r
+  IN BOOLEAN      Create\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Finds the protocol entry for the requested protocol.\r
+  \r
+  The gProtocolDatabaseLock must be owned\r
+\r
+Arguments:\r
+  \r
+  Protocol  - The ID of the protocol \r
+\r
+  Create    - Create a new entry if not found\r
+\r
+Returns:\r
+\r
+  Protocol entry\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreNotifyProtocolEntry (\r
+  IN PROTOCOL_ENTRY       *ProtEntry\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Signal event for every protocol in protocol entry.\r
+\r
+Arguments:\r
+\r
+  ProtEntry     - Protocol entry\r
+\r
+Returns:\r
+\r
+--*/\r
+;\r
+\r
+PROTOCOL_INTERFACE *\r
+CoreFindProtocolInterface (\r
+  IN IHANDLE              *Handle,\r
+  IN EFI_GUID             *Protocol,\r
+  IN VOID                 *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Finds the protocol instance for the requested handle and protocol.\r
+  \r
+  Note: This function doesn't do parameters checking, it's caller's responsibility \r
+        to pass in valid parameters.\r
+  \r
+Arguments:\r
+  \r
+  Handle    - The handle to search the protocol on\r
+  \r
+  Protocol  - GUID of the protocol\r
+\r
+  Interface - The interface for the protocol being searched\r
+\r
+Returns:\r
+\r
+  Protocol instance (NULL: Not found)\r
+\r
+--*/\r
+;\r
+\r
+PROTOCOL_INTERFACE *\r
+CoreRemoveInterfaceFromProtocol (\r
+  IN IHANDLE              *Handle,\r
+  IN EFI_GUID             *Protocol,\r
+  IN VOID                 *Interface\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes Protocol from the protocol list (but not the handle list).\r
+\r
+Arguments:\r
+\r
+  Handle -  The handle to remove protocol on.\r
+\r
+  Protocol  -  GUID of the protocol to be moved\r
+\r
+  Interface - The interface of the protocol\r
+\r
+Returns:\r
+\r
+  Protocol Entry\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreUnregisterProtocolNotify (\r
+  IN EFI_EVENT            Event\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Removes all the events in the protocol database that match Event.\r
+\r
+Arguments:\r
+  \r
+  Event   - The event to search for in the protocol database.\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS when done searching the entire database.\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreDisconnectControllersUsingProtocolInterface (\r
+  IN EFI_HANDLE           UserHandle,\r
+  IN PROTOCOL_INTERFACE   *Prot\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Attempts to disconnect all drivers that are using the protocol interface being queried.\r
+  If failed, reconnect all drivers disconnected.\r
+  \r
+  Note: This function doesn't do parameters checking, it's caller's responsibility \r
+        to pass in valid parameters.\r
+\r
+Arguments:\r
+\r
+  UserHandle  - The handle on which the protocol is installed \r
+  Prot        - The protocol to disconnect drivers from\r
+\r
+Returns:\r
+\r
+  EFI_SUCCESS       - Drivers using the protocol interface are all disconnected\r
+  EFI_ACCESS_DENIED - Failed to disconnect one or all of the drivers\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreAcquireProtocolLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Acquire lock on gProtocolDatabaseLock.\r
+  \r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreReleaseProtocolLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Release lock on gProtocolDatabaseLock.\r
+  \r
+Arguments:\r
+\r
+  None\r
+  \r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+EFI_STATUS\r
+CoreValidateHandle (\r
+  IN  EFI_HANDLE                UserHandle\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Check whether a handle is a valid EFI_HANDLE\r
+  \r
+Arguments:\r
+\r
+  UserHandle           -       The handle to check\r
+  \r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER                -       The handle is NULL or not a valid EFI_HANDLE.\r
+  \r
+  EFI_SUCCESS                                                  -       The handle is valid EFI_HANDLE.\r
+\r
+--*/\r
+;\r
+\r
+//\r
+// Externs\r
+//\r
+\r
+extern EFI_LOCK         gProtocolDatabaseLock;\r
+extern LIST_ENTRY       gHandleList;\r
+extern UINT64           gHandleDatabaseKey;\r
+\r
+#endif\r
diff --git a/MdeModulePkg/Core/Dxe/imem.h b/MdeModulePkg/Core/Dxe/imem.h
new file mode 100644 (file)
index 0000000..3337700
--- /dev/null
@@ -0,0 +1,227 @@
+/*++\r
+\r
+Copyright (c) 2006, Intel Corporation                                                         \r
+All rights reserved. This program and the accompanying materials                          \r
+are licensed and made available under the terms and conditions of the BSD License         \r
+which accompanies this distribution.  The full text of the license may be found at        \r
+http://opensource.org/licenses/bsd-license.php                                            \r
+                                                                                          \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,                     \r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.             \r
+\r
+Module Name:\r
+\r
+  imem.h\r
+\r
+Abstract:\r
+\r
+  Head file to imem.h\r
+\r
+\r
+Revision History\r
+\r
+--*/\r
+\r
+#ifndef _IMEM_H_\r
+#define _IMEM_H_\r
+\r
+#if defined (MDE_CPU_IPF)\r
+//\r
+// For Itanium machines make the default allocations 8K aligned\r
+//\r
+#define EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE * 2)\r
+#define DEFAULT_PAGE_ALLOCATION                     (EFI_PAGE_SIZE * 2)\r
+\r
+#else\r
+//\r
+// For genric EFI machines make the default allocations 4K aligned\r
+//\r
+#define EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
+#define DEFAULT_PAGE_ALLOCATION                     (EFI_PAGE_SIZE)\r
+\r
+#endif\r
+\r
+\r
+//\r
+// MEMORY_MAP_ENTRY\r
+//\r
+\r
+#define MEMORY_MAP_SIGNATURE   EFI_SIGNATURE_32('m','m','a','p')\r
+typedef struct {\r
+  UINTN           Signature;\r
+  LIST_ENTRY      Link;\r
+  BOOLEAN         FromPages;\r
+\r
+  EFI_MEMORY_TYPE Type;\r
+  UINT64          Start;\r
+  UINT64          End;\r
+\r
+  UINT64          VirtualStart;\r
+  UINT64          Attribute;\r
+} MEMORY_MAP;\r
+\r
+//\r
+// Internal prototypes\r
+//\r
+\r
+VOID *\r
+CoreAllocatePoolPages (\r
+  IN EFI_MEMORY_TYPE   PoolType,\r
+  IN UINTN             NumberOfPages,\r
+  IN UINTN             Alignment\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Used by the pool functions to allocate pages\r
+  to back pool allocation requests.\r
+\r
+Arguments:\r
+\r
+  PoolType      - The type of memory for the new pool pages\r
+\r
+  NumberOfPages - No of pages to allocate\r
+  \r
+  Alignment     - Bits to align.\r
+\r
+Returns:\r
+\r
+  The allocated memory, or NULL\r
+\r
+--*/\r
+;\r
+\r
+\r
+VOID\r
+CoreFreePoolPages (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function.  Frees pool pages allocated via AllocatePoolPages ()\r
+\r
+Arguments:\r
+\r
+  Memory        - The base address to free\r
+\r
+  NumberOfPages - The number of pages to free\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+VOID *\r
+CoreAllocatePoolI (\r
+  IN EFI_MEMORY_TYPE  PoolType,\r
+  IN UINTN            Size\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function to allocate pool of a particular type.\r
+\r
+  Caller must have the memory lock held\r
+\r
+\r
+Arguments:\r
+\r
+  PoolType    - Type of pool to allocate\r
+\r
+  Size        - The amount of pool to allocate\r
+\r
+Returns:\r
+\r
+  The allocate pool, or NULL\r
+\r
+--*/\r
+;\r
+\r
+\r
+EFI_STATUS\r
+CoreFreePoolI (\r
+  IN VOID           *Buffer\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Internal function to free a pool entry.\r
+\r
+  Caller must have the memory lock held\r
+\r
+\r
+Arguments:\r
+\r
+  Buffer      - The allocated pool entry to free\r
+\r
+Returns:\r
+\r
+  EFI_INVALID_PARAMETER     - Buffer not valid\r
+  \r
+  EFI_SUCCESS               - Buffer successfully freed.\r
+\r
+--*/\r
+;\r
+\r
+\r
+VOID\r
+CoreAcquireMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Enter critical section by gaining lock on gMemoryLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+VOID\r
+CoreReleaseMemoryLock (\r
+  VOID\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+\r
+  Exit critical section by releasing lock on gMemoryLock\r
+\r
+Arguments:\r
+\r
+  None\r
+\r
+Returns:\r
+\r
+  None\r
+\r
+--*/\r
+;\r
+\r
+\r
+//\r
+// Internal Global data\r
+//\r
+\r
+extern EFI_LOCK           gMemoryLock; \r
+extern LIST_ENTRY         gMemoryMap;\r
+extern MEMORY_MAP         *gMemoryLastConvert;\r
+extern LIST_ENTRY         mGcdMemorySpaceMap;\r
+#endif\r