]> git.proxmox.com Git - mirror_edk2.git/commitdiff
StandaloneMmPkg/Core: Implementation of Standalone MM Core Module.
authorSupreeth Venkatesh <supreeth.venkatesh@arm.com>
Fri, 13 Jul 2018 15:05:27 +0000 (23:05 +0800)
committerJiewen Yao <jiewen.yao@intel.com>
Fri, 20 Jul 2018 02:55:51 +0000 (10:55 +0800)
Management Mode (MM) is a generic term used to describe a secure
execution environment provided by the CPU and related silicon that is
entered when the CPU detects a MMI. For x86 systems, this can be
implemented with System Management Mode (SMM). For ARM systems, this can
be implemented with TrustZone (TZ).
A MMI can be a CPU instruction or interrupt. Upon detection of a MMI, a
CPU will jump to the MM Entry Point and save some portion of its state
(the "save state") such that execution can be resumed.
The MMI can be generated synchronously by software or asynchronously by
a hardware event. Each MMI source can be detected, cleared and disabled.
Some systems provide for special memory (Management Mode RAM or MMRAM)
which is set aside for software running in MM. Usually the MMRAM is
hidden during normal CPU execution, but this is not required. Usually,
after MMRAM is hidden it cannot be exposed until the next system reset.

The MM Core Interface Specification describes three pieces of the PI
Management Mode architecture:
1. MM Dispatch
   During DXE, the DXE Foundation works with the MM Foundation to
   schedule MM drivers for execution in the discovered firmware volumes.
2. MM Initialization
   MM related code opens MMRAM, creates the MMRAM memory map, and
   launches the MM Foundation, which provides the necessary services to
   launch MM-related drivers. Then, sometime before boot, MMRAM is
   closed and locked. This piece may be completed during the
   SEC, PEI or DXE phases.
3. MMI Management
   When an MMI generated, the MM environment is created and then the MMI

   sources are detected and MMI handlers called.

This patch implements the MM Core.

Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Sughosh Ganu <sughosh.ganu@arm.com>
Signed-off-by: Supreeth Venkatesh <supreeth.venkatesh@arm.com>
Reviewed-by: Jiewen Yao <jiewen.yao@intel.com>
17 files changed:
StandaloneMmPkg/Core/Dependency.c [new file with mode: 0644]
StandaloneMmPkg/Core/Dispatcher.c [new file with mode: 0644]
StandaloneMmPkg/Core/FwVol.c [new file with mode: 0644]
StandaloneMmPkg/Core/Handle.c [new file with mode: 0644]
StandaloneMmPkg/Core/InstallConfigurationTable.c [new file with mode: 0644]
StandaloneMmPkg/Core/Locate.c [new file with mode: 0644]
StandaloneMmPkg/Core/Mmi.c [new file with mode: 0644]
StandaloneMmPkg/Core/Notify.c [new file with mode: 0644]
StandaloneMmPkg/Core/Page.c [new file with mode: 0644]
StandaloneMmPkg/Core/Pool.c [new file with mode: 0644]
StandaloneMmPkg/Core/StandaloneMmCore.c [new file with mode: 0644]
StandaloneMmPkg/Core/StandaloneMmCore.h [new file with mode: 0644]
StandaloneMmPkg/Core/StandaloneMmCore.inf [new file with mode: 0644]
StandaloneMmPkg/Core/StandaloneMmCorePrivateData.h [new file with mode: 0644]
StandaloneMmPkg/Include/Guid/MmFvDispatch.h [new file with mode: 0644]
StandaloneMmPkg/Include/Library/StandaloneMmCoreEntryPoint.h [new file with mode: 0644]
StandaloneMmPkg/Include/StandaloneMm.h [new file with mode: 0644]

diff --git a/StandaloneMmPkg/Core/Dependency.c b/StandaloneMmPkg/Core/Dependency.c
new file mode 100644 (file)
index 0000000..365007d
--- /dev/null
@@ -0,0 +1,389 @@
+/** @file\r
+  MM Driver 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
+  Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+///\r
+/// EFI_DEP_REPLACE_TRUE - Used to dynamically patch the dependency expression\r
+///                        to save time.  A EFI_DEP_PUSH is evaluated one an\r
+///                        replaced with EFI_DEP_REPLACE_TRUE. If PI spec's Vol 2\r
+///                        Driver Execution Environment Core Interface use 0xff\r
+///                        as new DEPEX opcode. EFI_DEP_REPLACE_TRUE should be\r
+///                        defined to a new value that is not conflicting with PI spec.\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
+//\r
+// Global stack used to evaluate dependency expressions\r
+//\r
+BOOLEAN  *mDepexEvaluationStack        = NULL;\r
+BOOLEAN  *mDepexEvaluationStackEnd     = NULL;\r
+BOOLEAN  *mDepexEvaluationStackPointer = NULL;\r
+\r
+/**\r
+  Grow size of the Depex stack\r
+\r
+  @retval EFI_SUCCESS           Stack successfully growed.\r
+  @retval EFI_OUT_OF_RESOURCES  There is not enough system memory to grow the stack.\r
+\r
+**/\r
+EFI_STATUS\r
+GrowDepexStack (\r
+  VOID\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 = AllocatePool (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
+    FreePool (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
+  Push an element onto the Boolean Stack.\r
+\r
+  @param  Value                 BOOLEAN to push.\r
+\r
+  @retval EFI_SUCCESS           The value was pushed onto the stack.\r
+  @retval EFI_OUT_OF_RESOURCES  There is not enough system memory to grow the stack.\r
+\r
+**/\r
+EFI_STATUS\r
+PushBool (\r
+  IN BOOLEAN  Value\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
+  Pop an element from the Boolean stack.\r
+\r
+  @param  Value                 BOOLEAN to pop.\r
+\r
+  @retval EFI_SUCCESS           The value was popped onto the stack.\r
+  @retval EFI_ACCESS_DENIED     The pop operation underflowed the stack.\r
+\r
+**/\r
+EFI_STATUS\r
+PopBool (\r
+  OUT BOOLEAN  *Value\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
+  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. POSTFIX means all the math is done on top of the stack.\r
+\r
+  @param  DriverEntry           DriverEntry element to update.\r
+\r
+  @retval TRUE                  If driver is ready to run.\r
+  @retval FALSE                 If driver is not ready to run or some fatal error\r
+                                was found.\r
+\r
+**/\r
+BOOLEAN\r
+MmIsSchedulable (\r
+  IN  EFI_MM_DRIVER_ENTRY   *DriverEntry\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+  UINT8       *Iterator;\r
+  BOOLEAN     Operator;\r
+  BOOLEAN     Operator2;\r
+  EFI_GUID    DriverGuid;\r
+  VOID        *Interface;\r
+\r
+  Operator = FALSE;\r
+  Operator2 = FALSE;\r
+\r
+  if (DriverEntry->After || DriverEntry->Before) {\r
+    //\r
+    // If Before or After Depex skip as MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter ()\r
+    // processes them.\r
+    //\r
+    return FALSE;\r
+  }\r
+\r
+  DEBUG ((DEBUG_DISPATCH, "Evaluate MM DEPEX for FFS(%g)\n", &DriverEntry->FileName));\r
+\r
+  if (DriverEntry->Depex == NULL) {\r
+    //\r
+    // A NULL Depex means that the MM driver is not built correctly.\r
+    // All MM drivers must have a valid depex expressiion.\r
+    //\r
+    DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Depex is empty)\n"));\r
+    ASSERT (FALSE);\r
+    return FALSE;\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
+      DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Attempt to fetch past end of depex)\n"));\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
+      DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected BEFORE or AFTER opcode)\n"));\r
+      ASSERT (FALSE);\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 = MmLocateProtocol (&DriverGuid, NULL, &Interface);\r
+      if (EFI_ERROR (Status) && (mEfiSystemTable != NULL)) {\r
+        //\r
+        // For MM Driver, it may depend on uefi protocols\r
+        //\r
+        Status = mEfiSystemTable->BootServices->LocateProtocol (&DriverGuid, NULL, &Interface);\r
+      }\r
+\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  PUSH GUID(%g) = FALSE\n", &DriverGuid));\r
+        Status = PushBool (FALSE);\r
+      } else {\r
+        DEBUG ((DEBUG_DISPATCH, "  PUSH GUID(%g) = TRUE\n", &DriverGuid));\r
+        *Iterator = EFI_DEP_REPLACE_TRUE;\r
+        Status = PushBool (TRUE);\r
+      }\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Iterator += sizeof (EFI_GUID);\r
+      break;\r
+\r
+    case EFI_DEP_AND:\r
+      DEBUG ((DEBUG_DISPATCH, "  AND\n"));\r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PopBool (&Operator2);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(Operator && Operator2));\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_OR:\r
+      DEBUG ((DEBUG_DISPATCH, "  OR\n"));\r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PopBool (&Operator2);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(Operator || Operator2));\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_NOT:\r
+      DEBUG ((DEBUG_DISPATCH, "  NOT\n"));\r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Status = PushBool ((BOOLEAN)(!Operator));\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_TRUE:\r
+      DEBUG ((DEBUG_DISPATCH, "  TRUE\n"));\r
+      Status = PushBool (TRUE);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_FALSE:\r
+      DEBUG ((DEBUG_DISPATCH, "  FALSE\n"));\r
+      Status = PushBool (FALSE);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      break;\r
+\r
+    case EFI_DEP_END:\r
+      DEBUG ((DEBUG_DISPATCH, "  END\n"));\r
+      Status = PopBool (&Operator);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+      DEBUG ((DEBUG_DISPATCH, "  RESULT = %a\n", Operator ? "TRUE" : "FALSE"));\r
+      return Operator;\r
+\r
+    case EFI_DEP_REPLACE_TRUE:\r
+      CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID));\r
+      DEBUG ((DEBUG_DISPATCH, "  PUSH GUID(%g) = TRUE\n", &DriverGuid));\r
+      Status = PushBool (TRUE);\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unexpected error)\n"));\r
+        return FALSE;\r
+      }\r
+\r
+      Iterator += sizeof (EFI_GUID);\r
+      break;\r
+\r
+    default:\r
+      DEBUG ((DEBUG_DISPATCH, "  RESULT = FALSE (Unknown opcode)\n"));\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
diff --git a/StandaloneMmPkg/Core/Dispatcher.c b/StandaloneMmPkg/Core/Dispatcher.c
new file mode 100644 (file)
index 0000000..8d009b4
--- /dev/null
@@ -0,0 +1,1071 @@
+/** @file\r
+  MM Driver 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 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 similar to the DXE dispatcher.\r
+\r
+  The rules for DXE 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
+\r
+  Copyright (c) 2014, Hewlett-Packard Development Company, L.P.\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+//\r
+// MM Dispatcher Data structures\r
+//\r
+#define KNOWN_HANDLE_SIGNATURE  SIGNATURE_32('k','n','o','w')\r
+\r
+typedef struct {\r
+  UINTN           Signature;\r
+  LIST_ENTRY      Link;         // mFvHandleList\r
+  EFI_HANDLE      Handle;\r
+} KNOWN_HANDLE;\r
+\r
+//\r
+// Function Prototypes\r
+//\r
+\r
+EFI_STATUS\r
+MmCoreFfsFindMmDriver (\r
+  IN  EFI_FIRMWARE_VOLUME_HEADER  *FwVolHeader\r
+  );\r
+\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
+  @param  InsertedDriverEntry   The driver to insert on the ScheduledLink Queue\r
+\r
+**/\r
+VOID\r
+MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (\r
+  IN  EFI_MM_DRIVER_ENTRY   *InsertedDriverEntry\r
+  );\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_MM_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_MM_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);\r
+\r
+//\r
+// Flag for the MM Dispacher.  TRUE if dispatcher is execuing.\r
+//\r
+BOOLEAN  gDispatcherRunning = FALSE;\r
+\r
+//\r
+// Flag for the MM Dispacher.  TRUE if there is one or more MM drivers ready to be dispatched\r
+//\r
+BOOLEAN  gRequestDispatch = FALSE;\r
+\r
+//\r
+// The global variable is defined for Loading modules at fixed address feature to track the MM code\r
+// memory range usage. It is a bit mapped array in which every bit indicates the correspoding\r
+// memory page available or not.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED    UINT64                *mMmCodeMemoryRangeUsageBitMap=NULL;\r
+\r
+/**\r
+  To check memory usage bit map array to figure out if the memory range in which the image will be loaded\r
+  is available or not. If memory range is avaliable, the function will mark the correponding bits to 1\r
+  which indicates the memory range is used. The function is only invoked when load modules at fixed address\r
+  feature is enabled.\r
+\r
+  @param  ImageBase                The base addres the image will be loaded at.\r
+  @param  ImageSize                The size of the image\r
+\r
+  @retval EFI_SUCCESS              The memory range the image will be loaded in is available\r
+  @retval EFI_NOT_FOUND            The memory range the image will be loaded in is not available\r
+**/\r
+EFI_STATUS\r
+CheckAndMarkFixLoadingMemoryUsageBitMap (\r
+  IN  EFI_PHYSICAL_ADDRESS          ImageBase,\r
+  IN  UINTN                         ImageSize\r
+  )\r
+{\r
+  UINT32                             MmCodePageNumber;\r
+  UINT64                             MmCodeSize;\r
+  EFI_PHYSICAL_ADDRESS               MmCodeBase;\r
+  UINTN                              BaseOffsetPageNumber;\r
+  UINTN                              TopOffsetPageNumber;\r
+  UINTN                              Index;\r
+\r
+  //\r
+  // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressMmCodePageNumber\r
+  //\r
+  MmCodePageNumber = 0;\r
+  MmCodeSize = EFI_PAGES_TO_SIZE (MmCodePageNumber);\r
+  MmCodeBase = gLoadModuleAtFixAddressMmramBase;\r
+\r
+  //\r
+  // If the memory usage bit map is not initialized,  do it. Every bit in the array\r
+  // indicate the status of the corresponding memory page, available or not\r
+  //\r
+  if (mMmCodeMemoryRangeUsageBitMap == NULL) {\r
+    mMmCodeMemoryRangeUsageBitMap = AllocateZeroPool (((MmCodePageNumber / 64) + 1) * sizeof (UINT64));\r
+  }\r
+\r
+  //\r
+  // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND\r
+  //\r
+  if (mMmCodeMemoryRangeUsageBitMap == NULL) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // see if the memory range for loading the image is in the MM code range.\r
+  //\r
+  if (MmCodeBase + MmCodeSize <  ImageBase + ImageSize || MmCodeBase >  ImageBase) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // Test if the memory is avalaible or not.\r
+  //\r
+  BaseOffsetPageNumber = (UINTN)EFI_SIZE_TO_PAGES ((UINT32)(ImageBase - MmCodeBase));\r
+  TopOffsetPageNumber  = (UINTN)EFI_SIZE_TO_PAGES ((UINT32)(ImageBase + ImageSize - MmCodeBase));\r
+  for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {\r
+    if ((mMmCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64 (1, (Index % 64))) != 0) {\r
+      //\r
+      // This page is already used.\r
+      //\r
+      return EFI_NOT_FOUND;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Being here means the memory range is available.  So mark the bits for the memory range\r
+  //\r
+  for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {\r
+    mMmCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64 (1, (Index % 64));\r
+  }\r
+  return  EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Get the fixed loading address from image header assigned by build tool. This function only be called\r
+  when Loading module at Fixed address feature enabled.\r
+\r
+  @param  ImageContext              Pointer to the image context structure that describes the PE/COFF\r
+                                    image that needs to be examined by this function.\r
+  @retval EFI_SUCCESS               An fixed loading address is assigned to this image by build tools .\r
+  @retval EFI_NOT_FOUND             The image has no assigned fixed loadding address.\r
+\r
+**/\r
+EFI_STATUS\r
+GetPeCoffImageFixLoadingAssignedAddress(\r
+  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT  *ImageContext\r
+  )\r
+{\r
+  UINTN                              SectionHeaderOffset;\r
+  EFI_STATUS                         Status;\r
+  EFI_IMAGE_SECTION_HEADER           SectionHeader;\r
+  EFI_IMAGE_OPTIONAL_HEADER_UNION    *ImgHdr;\r
+  EFI_PHYSICAL_ADDRESS               FixLoadingAddress;\r
+  UINT16                             Index;\r
+  UINTN                              Size;\r
+  UINT16                             NumberOfSections;\r
+  UINT64                             ValueInSectionHeader;\r
+\r
+  FixLoadingAddress = 0;\r
+  Status = EFI_NOT_FOUND;\r
+\r
+  //\r
+  // Get PeHeader pointer\r
+  //\r
+  ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);\r
+  SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) +\r
+    ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;\r
+  NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;\r
+\r
+  //\r
+  // Get base address from the first section header that doesn't point to code section.\r
+  //\r
+  for (Index = 0; Index < NumberOfSections; Index++) {\r
+    //\r
+    // Read section header from file\r
+    //\r
+    Size = sizeof (EFI_IMAGE_SECTION_HEADER);\r
+    Status = ImageContext->ImageRead (\r
+                             ImageContext->Handle,\r
+                             SectionHeaderOffset,\r
+                             &Size,\r
+                             &SectionHeader\r
+                             );\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+\r
+    Status = EFI_NOT_FOUND;\r
+\r
+    if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {\r
+      //\r
+      // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields\r
+      // in the first section header that doesn't point to code section in image header. So there\r
+      // is an assumption that when the feature is enabled, if a module with a loading address\r
+      // assigned by tools, the PointerToRelocations & PointerToLineNumbers fields should not be\r
+      // Zero, or else, these 2 fields should be set to Zero\r
+      //\r
+      ValueInSectionHeader = ReadUnaligned64 ((UINT64*)&SectionHeader.PointerToRelocations);\r
+      if (ValueInSectionHeader != 0) {\r
+        //\r
+        // Found first section header that doesn't point to code section in which build tool saves the\r
+        // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields\r
+        //\r
+        FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressMmramBase + (INT64)ValueInSectionHeader);\r
+        //\r
+        // Check if the memory range is available.\r
+        //\r
+        Status = CheckAndMarkFixLoadingMemoryUsageBitMap (FixLoadingAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment));\r
+        if (!EFI_ERROR(Status)) {\r
+          //\r
+          // The assigned address is valid. Return the specified loading address\r
+          //\r
+          ImageContext->ImageAddress = FixLoadingAddress;\r
+        }\r
+      }\r
+      break;\r
+    }\r
+    SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);\r
+  }\r
+  DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r\n",\r
+          FixLoadingAddress, Status));\r
+  return Status;\r
+}\r
+/**\r
+  Loads an EFI image into SMRAM.\r
+\r
+  @param  DriverEntry             EFI_MM_DRIVER_ENTRY instance\r
+\r
+  @return EFI_STATUS\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLoadImage (\r
+  IN OUT EFI_MM_DRIVER_ENTRY  *DriverEntry\r
+  )\r
+{\r
+  VOID                           *Buffer;\r
+  UINTN                          PageCount;\r
+  EFI_STATUS                     Status;\r
+  EFI_PHYSICAL_ADDRESS           DstBuffer;\r
+  PE_COFF_LOADER_IMAGE_CONTEXT   ImageContext;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmLoadImage - %g\n", &DriverEntry->FileName));\r
+\r
+  Buffer = AllocateCopyPool (DriverEntry->Pe32DataSize, DriverEntry->Pe32Data);\r
+  if (Buffer == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  Status               = EFI_SUCCESS;\r
+\r
+  //\r
+  // Initialize ImageContext\r
+  //\r
+  ImageContext.Handle = Buffer;\r
+  ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;\r
+\r
+  //\r
+  // Get information about the image being loaded\r
+  //\r
+  Status = PeCoffLoaderGetImageInfo (&ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    if (Buffer != NULL) {\r
+      MmFreePool (Buffer);\r
+    }\r
+    return Status;\r
+  }\r
+\r
+  PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);\r
+  DstBuffer = (UINTN)(-1);\r
+\r
+  Status = MmAllocatePages (\r
+             AllocateMaxAddress,\r
+             EfiRuntimeServicesCode,\r
+             PageCount,\r
+             &DstBuffer\r
+             );\r
+  if (EFI_ERROR (Status)) {\r
+    if (Buffer != NULL) {\r
+      MmFreePool (Buffer);\r
+    }\r
+    return Status;\r
+  }\r
+\r
+  ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;\r
+\r
+  //\r
+  // Align buffer on section boundry\r
+  //\r
+  ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;\r
+  ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)(ImageContext.SectionAlignment - 1));\r
+\r
+  //\r
+  // Load the image to our new buffer\r
+  //\r
+  Status = PeCoffLoaderLoadImage (&ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    if (Buffer != NULL) {\r
+      MmFreePool (Buffer);\r
+    }\r
+    MmFreePages (DstBuffer, PageCount);\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Relocate the image in our new buffer\r
+  //\r
+  Status = PeCoffLoaderRelocateImage (&ImageContext);\r
+  if (EFI_ERROR (Status)) {\r
+    if (Buffer != NULL) {\r
+      MmFreePool (Buffer);\r
+    }\r
+    MmFreePages (DstBuffer, PageCount);\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Flush the instruction cache so the image data are written before we execute it\r
+  //\r
+  InvalidateInstructionCacheRange ((VOID *)(UINTN) ImageContext.ImageAddress, (UINTN) ImageContext.ImageSize);\r
+\r
+  //\r
+  // Save Image EntryPoint in DriverEntry\r
+  //\r
+  DriverEntry->ImageEntryPoint  = ImageContext.EntryPoint;\r
+  DriverEntry->ImageBuffer      = DstBuffer;\r
+  DriverEntry->NumberOfPage     = PageCount;\r
+\r
+  if (mEfiSystemTable != NULL) {\r
+    Status = mEfiSystemTable->BootServices->AllocatePool (\r
+                                              EfiBootServicesData,\r
+                                              sizeof (EFI_LOADED_IMAGE_PROTOCOL),\r
+                                              (VOID **)&DriverEntry->LoadedImage\r
+                                              );\r
+    if (EFI_ERROR (Status)) {\r
+      if (Buffer != NULL) {\r
+        MmFreePool (Buffer);\r
+      }\r
+      MmFreePages (DstBuffer, PageCount);\r
+      return Status;\r
+    }\r
+\r
+    ZeroMem (DriverEntry->LoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL));\r
+    //\r
+    // Fill in the remaining fields of the Loaded Image Protocol instance.\r
+    // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed.\r
+    //\r
+    DriverEntry->LoadedImage->Revision      = EFI_LOADED_IMAGE_PROTOCOL_REVISION;\r
+    DriverEntry->LoadedImage->ParentHandle  = NULL;\r
+    DriverEntry->LoadedImage->SystemTable   = mEfiSystemTable;\r
+    DriverEntry->LoadedImage->DeviceHandle  = NULL;\r
+    DriverEntry->LoadedImage->FilePath      = NULL;\r
+\r
+    DriverEntry->LoadedImage->ImageBase     = (VOID *)(UINTN)DriverEntry->ImageBuffer;\r
+    DriverEntry->LoadedImage->ImageSize     = ImageContext.ImageSize;\r
+    DriverEntry->LoadedImage->ImageCodeType = EfiRuntimeServicesCode;\r
+    DriverEntry->LoadedImage->ImageDataType = EfiRuntimeServicesData;\r
+\r
+    //\r
+    // Create a new image handle in the UEFI handle database for the MM Driver\r
+    //\r
+    DriverEntry->ImageHandle = NULL;\r
+    Status = mEfiSystemTable->BootServices->InstallMultipleProtocolInterfaces (\r
+                                              &DriverEntry->ImageHandle,\r
+                                              &gEfiLoadedImageProtocolGuid,\r
+                                              DriverEntry->LoadedImage,\r
+                                              NULL\r
+                                              );\r
+  }\r
+\r
+  //\r
+  // Print the load address and the PDB file name if it is available\r
+  //\r
+  DEBUG_CODE_BEGIN ();\r
+\r
+  UINTN Index;\r
+  UINTN StartIndex;\r
+  CHAR8 EfiFileName[256];\r
+\r
+  DEBUG ((DEBUG_INFO | DEBUG_LOAD,\r
+          "Loading MM driver at 0x%11p EntryPoint=0x%11p ",\r
+          (VOID *)(UINTN) ImageContext.ImageAddress,\r
+          FUNCTION_ENTRY_POINT (ImageContext.EntryPoint)));\r
+\r
+  //\r
+  // Print Module Name by Pdb file path.\r
+  // Windows and Unix style file path are all trimmed correctly.\r
+  //\r
+  if (ImageContext.PdbPointer != NULL) {\r
+    StartIndex = 0;\r
+    for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) {\r
+      if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) {\r
+        StartIndex = Index + 1;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Copy the PDB file name to our temporary string, and replace .pdb with .efi\r
+    // The PDB file name is limited in the range of 0~255.\r
+    // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary.\r
+    //\r
+    for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {\r
+      EfiFileName[Index] = 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
+\r
+    if (Index == sizeof (EfiFileName) - 4) {\r
+      EfiFileName[Index] = 0;\r
+    }\r
+    DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName));\r
+  }\r
+  DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));\r
+\r
+  DEBUG_CODE_END ();\r
+\r
+  //\r
+  // Free buffer allocated by Fv->ReadSection.\r
+  //\r
+  // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection\r
+  // used the UEFI Boot Services AllocatePool() function\r
+  //\r
+  MmFreePool (Buffer);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Preprocess dependency expression and update DriverEntry to reflect the\r
+  state of  Before and After dependencies. If DriverEntry->Before\r
+  or DriverEntry->After is set it will never be cleared.\r
+\r
+  @param  DriverEntry           DriverEntry element to update .\r
+\r
+  @retval EFI_SUCCESS           It always works.\r
+\r
+**/\r
+EFI_STATUS\r
+MmPreProcessDepex (\r
+  IN EFI_MM_DRIVER_ENTRY  *DriverEntry\r
+  )\r
+{\r
+  UINT8  *Iterator;\r
+\r
+  Iterator = DriverEntry->Depex;\r
+  DriverEntry->Dependent = TRUE;\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
+  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
+  @param  DriverEntry           Driver to work on.\r
+\r
+  @retval EFI_SUCCESS           Depex read and preprossesed\r
+  @retval EFI_PROTOCOL_ERROR    The section extraction protocol returned an error\r
+                                and  Depex reading needs to be retried.\r
+  @retval Error                 DEPEX not found.\r
+\r
+**/\r
+EFI_STATUS\r
+MmGetDepexSectionAndPreProccess (\r
+  IN EFI_MM_DRIVER_ENTRY  *DriverEntry\r
+  )\r
+{\r
+  EFI_STATUS                     Status;\r
+\r
+  //\r
+  // Data already read\r
+  //\r
+  if (DriverEntry->Depex == NULL) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else {\r
+    Status = EFI_SUCCESS;\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 depend on all architectural protocols\r
+      //\r
+      DriverEntry->Depex = NULL;\r
+      DriverEntry->Dependent = TRUE;\r
+      DriverEntry->DepexProtocolError = FALSE;\r
+    }\r
+  } else {\r
+    //\r
+    // Set Before and After state information based on Depex\r
+    // Driver will be put in Dependent state\r
+    //\r
+    MmPreProcessDepex (DriverEntry);\r
+    DriverEntry->DepexProtocolError = FALSE;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+  This is the main Dispatcher for MM 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.\r
+\r
+  @retval EFI_SUCCESS           All of the MM Drivers that could be dispatched\r
+                                have been run and the MM Entry Point has been\r
+                                registered.\r
+  @retval EFI_NOT_READY         The MM Driver that registered the MM Entry Point\r
+                                was just dispatched.\r
+  @retval EFI_NOT_FOUND         There are no MM Drivers available to be dispatched.\r
+  @retval EFI_ALREADY_STARTED   The MM Dispatcher is already running\r
+\r
+**/\r
+EFI_STATUS\r
+MmDispatcher (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS            Status;\r
+  LIST_ENTRY            *Link;\r
+  EFI_MM_DRIVER_ENTRY  *DriverEntry;\r
+  BOOLEAN               ReadyToRun;\r
+  BOOLEAN               PreviousMmEntryPointRegistered;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmDispatcher\n"));\r
+\r
+  if (!gRequestDispatch) {\r
+    DEBUG ((DEBUG_INFO, "  !gRequestDispatch\n"));\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  if (gDispatcherRunning) {\r
+    DEBUG ((DEBUG_INFO, "  gDispatcherRunning\n"));\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
+  do {\r
+    //\r
+    // Drain the Scheduled Queue\r
+    //\r
+    DEBUG ((DEBUG_INFO, "  Drain the Scheduled Queue\n"));\r
+    while (!IsListEmpty (&mScheduledQueue)) {\r
+      DriverEntry = CR (\r
+                      mScheduledQueue.ForwardLink,\r
+                      EFI_MM_DRIVER_ENTRY,\r
+                      ScheduledLink,\r
+                      EFI_MM_DRIVER_ENTRY_SIGNATURE\r
+                      );\r
+      DEBUG ((DEBUG_INFO, "  DriverEntry (Scheduled) - %g\n", &DriverEntry->FileName));\r
+\r
+      //\r
+      // Load the MM 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 = MmLoadImage (DriverEntry);\r
+\r
+        //\r
+        // Update the driver state to reflect that it's been loaded\r
+        //\r
+        if (EFI_ERROR (Status)) {\r
+          //\r
+          // The MM Driver could not be loaded, and do not attempt to load or start it again.\r
+          // Take driver from Scheduled to Initialized.\r
+          //\r
+          DriverEntry->Initialized  = TRUE;\r
+          DriverEntry->Scheduled = FALSE;\r
+          RemoveEntryList (&DriverEntry->ScheduledLink);\r
+\r
+          //\r
+          // If it's an error don't try the StartImage\r
+          //\r
+          continue;\r
+        }\r
+      }\r
+\r
+      DriverEntry->Scheduled    = FALSE;\r
+      DriverEntry->Initialized  = TRUE;\r
+      RemoveEntryList (&DriverEntry->ScheduledLink);\r
+\r
+      //\r
+      // Cache state of MmEntryPointRegistered before calling entry point\r
+      //\r
+      PreviousMmEntryPointRegistered = gMmCorePrivate->MmEntryPointRegistered;\r
+\r
+      //\r
+      // For each MM driver, pass NULL as ImageHandle\r
+      //\r
+      if (mEfiSystemTable == NULL) {\r
+        DEBUG ((DEBUG_INFO, "StartImage - 0x%x (Standalone Mode)\n", DriverEntry->ImageEntryPoint));\r
+        Status = ((MM_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint) (DriverEntry->ImageHandle, &gMmCoreMmst);\r
+      } else {\r
+        DEBUG ((DEBUG_INFO, "StartImage - 0x%x (Tradition Mode)\n", DriverEntry->ImageEntryPoint));\r
+        Status = ((EFI_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint) (\r
+                                                               DriverEntry->ImageHandle,\r
+                                                               mEfiSystemTable\r
+                                                               );\r
+      }\r
+      if (EFI_ERROR(Status)) {\r
+        DEBUG ((DEBUG_INFO, "StartImage Status - %r\n", Status));\r
+        MmFreePages(DriverEntry->ImageBuffer, DriverEntry->NumberOfPage);\r
+      }\r
+\r
+      if (!PreviousMmEntryPointRegistered && gMmCorePrivate->MmEntryPointRegistered) {\r
+        //\r
+        // Return immediately if the MM Entry Point was registered by the MM\r
+        // Driver that was just dispatched.  The MM IPL will reinvoke the MM\r
+        // Core Dispatcher.  This is required so MM Mode may be enabled as soon\r
+        // as all the dependent MM Drivers for MM Mode have been dispatched.\r
+        // Once the MM Entry Point has been registered, then MM Mode will be\r
+        // used.\r
+        //\r
+        gRequestDispatch = TRUE;\r
+        gDispatcherRunning = FALSE;\r
+        return EFI_NOT_READY;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Search DriverList for items to place on Scheduled Queue\r
+    //\r
+    DEBUG ((DEBUG_INFO, "  Search DriverList for items to place on Scheduled Queue\n"));\r
+    ReadyToRun = FALSE;\r
+    for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+      DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);\r
+      DEBUG ((DEBUG_INFO, "  DriverEntry (Discovered) - %g\n", &DriverEntry->FileName));\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 = MmGetDepexSectionAndPreProccess (DriverEntry);\r
+      }\r
+\r
+      if (DriverEntry->Dependent) {\r
+        if (MmIsSchedulable (DriverEntry)) {\r
+          MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);\r
+          ReadyToRun = TRUE;\r
+        }\r
+      }\r
+    }\r
+  } while (ReadyToRun);\r
+\r
+  //\r
+  // If there is no more MM driver to dispatch, stop the dispatch request\r
+  //\r
+  DEBUG ((DEBUG_INFO, "  no more MM driver to dispatch, stop the dispatch request\n"));\r
+  gRequestDispatch = FALSE;\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);\r
+    DEBUG ((DEBUG_INFO, "  DriverEntry (Discovered) - %g\n", &DriverEntry->FileName));\r
+\r
+    if (!DriverEntry->Initialized) {\r
+      //\r
+      // We have MM driver pending to dispatch\r
+      //\r
+      gRequestDispatch = TRUE;\r
+      break;\r
+    }\r
+  }\r
+\r
+  gDispatcherRunning = FALSE;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\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
+  @param  InsertedDriverEntry   The driver to insert on the ScheduledLink Queue\r
+\r
+**/\r
+VOID\r
+MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (\r
+  IN  EFI_MM_DRIVER_ENTRY   *InsertedDriverEntry\r
+  )\r
+{\r
+  LIST_ENTRY            *Link;\r
+  EFI_MM_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_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {\r
+      DEBUG ((DEBUG_DISPATCH, "Evaluate MM DEPEX for FFS(%g)\n", &DriverEntry->FileName));\r
+      DEBUG ((DEBUG_DISPATCH, "  BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid));\r
+      if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {\r
+        //\r
+        // Recursively process BEFORE\r
+        //\r
+        DEBUG ((DEBUG_DISPATCH, "TRUE\n  END\n  RESULT = TRUE\n"));\r
+        MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);\r
+      } else {\r
+        DEBUG ((DEBUG_DISPATCH, "FALSE\n  END\n  RESULT = FALSE\n"));\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Convert driver from Dependent to Scheduled state\r
+  //\r
+\r
+  InsertedDriverEntry->Dependent = FALSE;\r
+  InsertedDriverEntry->Scheduled = TRUE;\r
+  InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink);\r
+\r
+\r
+  //\r
+  // Process After Dependency\r
+  //\r
+  for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR(Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {\r
+      DEBUG ((DEBUG_DISPATCH, "Evaluate MM DEPEX for FFS(%g)\n", &DriverEntry->FileName));\r
+      DEBUG ((DEBUG_DISPATCH, "  AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid));\r
+      if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {\r
+        //\r
+        // Recursively process AFTER\r
+        //\r
+        DEBUG ((DEBUG_DISPATCH, "TRUE\n  END\n  RESULT = TRUE\n"));\r
+        MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);\r
+      } else {\r
+        DEBUG ((DEBUG_DISPATCH, "FALSE\n  END\n  RESULT = FALSE\n"));\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+  Return TRUE if the Fv has been processed, FALSE if not.\r
+\r
+  @param  FvHandle              The handle of a FV that's being tested\r
+\r
+  @retval TRUE                  Fv protocol on FvHandle has been processed\r
+  @retval FALSE                 Fv protocol on FvHandle has not yet been\r
+                                processed\r
+\r
+**/\r
+BOOLEAN\r
+FvHasBeenProcessed (\r
+  IN EFI_HANDLE  FvHandle\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
+/**\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
+  @param  FvHandle              The handle of a FV that has been processed\r
+\r
+**/\r
+VOID\r
+FvIsBeingProcesssed (\r
+  IN EFI_HANDLE  FvHandle\r
+  )\r
+{\r
+  KNOWN_HANDLE  *KnownHandle;\r
+\r
+  DEBUG ((DEBUG_INFO, "FvIsBeingProcesssed - 0x%08x\n", FvHandle));\r
+\r
+  KnownHandle = AllocatePool (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
+  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 Before and After state.\r
+  The Discovered list is never free'ed and contains booleans that represent the\r
+  other possible MM driver states.\r
+\r
+  @param  Fv                    Fv protocol, needed to read Depex info out of\r
+                                FLASH.\r
+  @param  FvHandle              Handle for Fv, needed in the\r
+                                EFI_MM_DRIVER_ENTRY so that the PE image can be\r
+                                read out of the FV at a later time.\r
+  @param  DriverName            Name of driver to add to mDiscoveredList.\r
+\r
+  @retval EFI_SUCCESS           If driver was added to the mDiscoveredList.\r
+  @retval EFI_ALREADY_STARTED   The driver has already been started. Only one\r
+                                DriverName may be active in the system at any one\r
+                                time.\r
+\r
+**/\r
+EFI_STATUS\r
+MmAddToDriverList (\r
+  IN EFI_HANDLE   FvHandle,\r
+  IN VOID         *Pe32Data,\r
+  IN UINTN        Pe32DataSize,\r
+  IN VOID         *Depex,\r
+  IN UINTN        DepexSize,\r
+  IN EFI_GUID     *DriverName\r
+  )\r
+{\r
+  EFI_MM_DRIVER_ENTRY  *DriverEntry;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmAddToDriverList - %g (0x%08x)\n", DriverName, Pe32Data));\r
+\r
+  //\r
+  // Create the Driver Entry for the list. ZeroPool initializes lots of variables to\r
+  // NULL or FALSE.\r
+  //\r
+  DriverEntry = AllocateZeroPool (sizeof (EFI_MM_DRIVER_ENTRY));\r
+  ASSERT (DriverEntry != NULL);\r
+\r
+  DriverEntry->Signature        = EFI_MM_DRIVER_ENTRY_SIGNATURE;\r
+  CopyGuid (&DriverEntry->FileName, DriverName);\r
+  DriverEntry->FvHandle         = FvHandle;\r
+  DriverEntry->Pe32Data         = Pe32Data;\r
+  DriverEntry->Pe32DataSize     = Pe32DataSize;\r
+  DriverEntry->Depex            = Depex;\r
+  DriverEntry->DepexSize        = DepexSize;\r
+\r
+  MmGetDepexSectionAndPreProccess (DriverEntry);\r
+\r
+  InsertTailList (&mDiscoveredList, &DriverEntry->Link);\r
+  gRequestDispatch = TRUE;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\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 MmLocateHandle () to see how many protocols were added and\r
+  do the following to each FV:\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
+  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 MM driver transitions to..\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
+  @param  DispatchHandle  The unique handle assigned to this handler by SmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmDriverDispatchHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_STATUS                            Status;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmDriverDispatchHandler\n"));\r
+\r
+  //\r
+  // Execute the MM Dispatcher on any newly discovered FVs and previously\r
+  // discovered MM drivers that have been discovered but not dispatched.\r
+  //\r
+  Status = MmDispatcher ();\r
+\r
+  //\r
+  // Check to see if CommBuffer and CommBufferSize are valid\r
+  //\r
+  if (CommBuffer != NULL && CommBufferSize != NULL) {\r
+    if (*CommBufferSize > 0) {\r
+      if (Status == EFI_NOT_READY) {\r
+        //\r
+        // If a the MM Core Entry Point was just registered, then set flag to\r
+        // request the MM Dispatcher to be restarted.\r
+        //\r
+        *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_RESTART;\r
+      } else if (!EFI_ERROR (Status)) {\r
+        //\r
+        // Set the flag to show that the MM Dispatcher executed without errors\r
+        //\r
+        *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_SUCCESS;\r
+      } else {\r
+        //\r
+        // Set the flag to show that the MM Dispatcher encountered an error\r
+        //\r
+        *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_ERROR;\r
+      }\r
+    }\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by SmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFvDispatchHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_STATUS                            Status;\r
+  EFI_MM_COMMUNICATE_FV_DISPATCH_DATA  *CommunicationFvDispatchData;\r
+  EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmFvDispatchHandler\n"));\r
+\r
+  CommunicationFvDispatchData = CommBuffer;\r
+\r
+  DEBUG ((DEBUG_INFO, "  Dispatch - 0x%016lx - 0x%016lx\n", CommunicationFvDispatchData->Address,\r
+          CommunicationFvDispatchData->Size));\r
+\r
+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)CommunicationFvDispatchData->Address;\r
+\r
+  MmCoreFfsFindMmDriver (FwVolHeader);\r
+\r
+  //\r
+  // Execute the MM Dispatcher on any newly discovered FVs and previously\r
+  // discovered MM drivers that have been discovered but not dispatched.\r
+  //\r
+  Status = MmDispatcher ();\r
+\r
+  return Status;\r
+}\r
+\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
+**/\r
+VOID\r
+MmDisplayDiscoveredNotDispatched (\r
+  VOID\r
+  )\r
+{\r
+  LIST_ENTRY                   *Link;\r
+  EFI_MM_DRIVER_ENTRY         *DriverEntry;\r
+\r
+  for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) {\r
+    DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);\r
+    if (DriverEntry->Dependent) {\r
+      DEBUG ((DEBUG_LOAD, "MM Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName));\r
+    }\r
+  }\r
+}\r
diff --git a/StandaloneMmPkg/Core/FwVol.c b/StandaloneMmPkg/Core/FwVol.c
new file mode 100644 (file)
index 0000000..5abf98c
--- /dev/null
@@ -0,0 +1,104 @@
+/**@file\r
+\r
+Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+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 "StandaloneMmCore.h"\r
+#include <Library/FvLib.h>\r
+\r
+//\r
+// List of file types supported by dispatcher\r
+//\r
+EFI_FV_FILETYPE mMmFileTypes[] = {\r
+  EFI_FV_FILETYPE_MM,\r
+  0xE, //EFI_FV_FILETYPE_MM_STANDALONE,\r
+       //\r
+       // Note: DXE core will process the FV image file, so skip it in MM core\r
+       // EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE\r
+       //\r
+};\r
+\r
+EFI_STATUS\r
+MmAddToDriverList (\r
+  IN EFI_HANDLE   FvHandle,\r
+  IN VOID         *Pe32Data,\r
+  IN UINTN        Pe32DataSize,\r
+  IN VOID         *Depex,\r
+  IN UINTN        DepexSize,\r
+  IN EFI_GUID     *DriverName\r
+  );\r
+\r
+BOOLEAN\r
+FvHasBeenProcessed (\r
+  IN EFI_HANDLE  FvHandle\r
+  );\r
+\r
+VOID\r
+FvIsBeingProcesssed (\r
+  IN EFI_HANDLE  FvHandle\r
+  );\r
+\r
+EFI_STATUS\r
+MmCoreFfsFindMmDriver (\r
+  IN  EFI_FIRMWARE_VOLUME_HEADER  *FwVolHeader\r
+  )\r
+/*++\r
+\r
+Routine Description:\r
+  Given the pointer to the Firmware Volume Header find the\r
+  MM driver and return it's PE32 image.\r
+\r
+Arguments:\r
+  FwVolHeader - Pointer to memory mapped FV\r
+\r
+Returns:\r
+  other       - Failure\r
+\r
+--*/\r
+{\r
+  EFI_STATUS          Status;\r
+  EFI_STATUS          DepexStatus;\r
+  EFI_FFS_FILE_HEADER *FileHeader;\r
+  EFI_FV_FILETYPE     FileType;\r
+  VOID                *Pe32Data;\r
+  UINTN               Pe32DataSize;\r
+  VOID                *Depex;\r
+  UINTN               DepexSize;\r
+  UINTN               Index;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmCoreFfsFindMmDriver - 0x%x\n", FwVolHeader));\r
+\r
+  if (FvHasBeenProcessed (FwVolHeader)) {\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  FvIsBeingProcesssed (FwVolHeader);\r
+\r
+  for (Index = 0; Index < sizeof (mMmFileTypes) / sizeof (mMmFileTypes[0]); Index++) {\r
+    DEBUG ((DEBUG_INFO, "Check MmFileTypes - 0x%x\n", mMmFileTypes[Index]));\r
+    FileType = mMmFileTypes[Index];\r
+    FileHeader = NULL;\r
+    do {\r
+      Status = FfsFindNextFile (FileType, FwVolHeader, &FileHeader);\r
+      if (!EFI_ERROR (Status)) {\r
+        Status = FfsFindSectionData (EFI_SECTION_PE32, FileHeader, &Pe32Data, &Pe32DataSize);\r
+        DEBUG ((DEBUG_INFO, "Find PE data - 0x%x\n", Pe32Data));\r
+        DepexStatus = FfsFindSectionData (EFI_SECTION_MM_DEPEX, FileHeader, &Depex, &DepexSize);\r
+        if (!EFI_ERROR (DepexStatus)) {\r
+          MmAddToDriverList (FwVolHeader, Pe32Data, Pe32DataSize, Depex, DepexSize, &FileHeader->Name);\r
+        }\r
+      }\r
+    } while (!EFI_ERROR (Status));\r
+  }\r
+\r
+  return Status;\r
+}\r
diff --git a/StandaloneMmPkg/Core/Handle.c b/StandaloneMmPkg/Core/Handle.c
new file mode 100644 (file)
index 0000000..70d59fe
--- /dev/null
@@ -0,0 +1,533 @@
+/** @file\r
+  SMM handle & protocol handling.\r
+\r
+  Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\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
+//\r
+LIST_ENTRY  mProtocolDatabase  = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase);\r
+LIST_ENTRY  gHandleList        = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList);\r
+\r
+/**\r
+  Check whether a handle is a valid EFI_HANDLE\r
+\r
+  @param  UserHandle             The handle to check\r
+\r
+  @retval EFI_INVALID_PARAMETER  The handle is NULL or not a valid EFI_HANDLE.\r
+  @retval EFI_SUCCESS            The handle is valid EFI_HANDLE.\r
+\r
+**/\r
+EFI_STATUS\r
+MmValidateHandle (\r
+  IN EFI_HANDLE  UserHandle\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
+  Finds the protocol entry for the requested protocol.\r
+\r
+  @param  Protocol               The ID of the protocol\r
+  @param  Create                 Create a new entry if not found\r
+\r
+  @return Protocol entry\r
+\r
+**/\r
+PROTOCOL_ENTRY  *\r
+MmFindProtocolEntry (\r
+  IN EFI_GUID   *Protocol,\r
+  IN BOOLEAN    Create\r
+  )\r
+{\r
+  LIST_ENTRY          *Link;\r
+  PROTOCOL_ENTRY      *Item;\r
+  PROTOCOL_ENTRY      *ProtEntry;\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
+      // This is the protocol entry\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 = AllocatePool (sizeof(PROTOCOL_ENTRY));\r
+    if (ProtEntry != NULL) {\r
+      //\r
+      // Initialize new protocol entry structure\r
+      //\r
+      ProtEntry->Signature = PROTOCOL_ENTRY_SIGNATURE;\r
+      CopyGuid ((VOID *)&ProtEntry->ProtocolID, Protocol);\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
+  return ProtEntry;\r
+}\r
+\r
+/**\r
+  Finds the protocol instance for the requested handle and protocol.\r
+  Note: This function doesn't do parameters checking, it's caller's responsibility\r
+  to pass in valid parameters.\r
+\r
+  @param  Handle                 The handle to search the protocol on\r
+  @param  Protocol               GUID of the protocol\r
+  @param  Interface              The interface for the protocol being searched\r
+\r
+  @return Protocol instance (NULL: Not found)\r
+\r
+**/\r
+PROTOCOL_INTERFACE *\r
+MmFindProtocolInterface (\r
+  IN IHANDLE   *Handle,\r
+  IN EFI_GUID  *Protocol,\r
+  IN VOID      *Interface\r
+  )\r
+{\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  LIST_ENTRY          *Link;\r
+\r
+  Prot = NULL;\r
+\r
+  //\r
+  // Lookup the protocol entry for this protocol ID\r
+  //\r
+  ProtEntry = MmFindProtocolEntry (Protocol, FALSE);\r
+  if (ProtEntry != NULL) {\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
+      // 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
+      Prot = NULL;\r
+    }\r
+  }\r
+  return Prot;\r
+}\r
+\r
+/**\r
+  Wrapper function to MmInstallProtocolInterfaceNotify.  This is the public API which\r
+  Calls the private one which contains a BOOLEAN parameter for notifications\r
+\r
+  @param  UserHandle             The handle to install the protocol handler on,\r
+                                 or NULL if a new handle is to be allocated\r
+  @param  Protocol               The protocol to add to the handle\r
+  @param  InterfaceType          Indicates whether Interface is supplied in\r
+                                 native form.\r
+  @param  Interface              The interface for the protocol being added\r
+\r
+  @return Status code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInstallProtocolInterface (\r
+  IN OUT EFI_HANDLE      *UserHandle,\r
+  IN EFI_GUID            *Protocol,\r
+  IN EFI_INTERFACE_TYPE  InterfaceType,\r
+  IN VOID                *Interface\r
+  )\r
+{\r
+  return MmInstallProtocolInterfaceNotify (\r
+           UserHandle,\r
+           Protocol,\r
+           InterfaceType,\r
+           Interface,\r
+           TRUE\r
+           );\r
+}\r
+\r
+/**\r
+  Installs a protocol interface into the boot services environment.\r
+\r
+  @param  UserHandle             The handle to install the protocol handler on,\r
+                                 or NULL if a new handle is to be allocated\r
+  @param  Protocol               The protocol to add to the handle\r
+  @param  InterfaceType          Indicates whether Interface is supplied in\r
+                                 native form.\r
+  @param  Interface              The interface for the protocol being added\r
+  @param  Notify                 indicates whether notify the notification list\r
+                                 for this protocol\r
+\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_OUT_OF_RESOURCES   No enough buffer to allocate\r
+  @retval EFI_SUCCESS            Protocol interface successfully installed\r
+\r
+**/\r
+EFI_STATUS\r
+MmInstallProtocolInterfaceNotify (\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
+  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 ((DEBUG_LOAD | DEBUG_INFO, "MmInstallProtocolInterface: %g %p\n", Protocol, Interface));\r
+\r
+  Status = EFI_OUT_OF_RESOURCES;\r
+  Prot = NULL;\r
+  Handle = NULL;\r
+\r
+  if (*UserHandle != NULL) {\r
+    Status = MmHandleProtocol (*UserHandle, Protocol, (VOID **)&ExistingInterface);\r
+    if (!EFI_ERROR (Status)) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+  }\r
+\r
+  //\r
+  // Lookup the Protocol Entry for the requested protocol\r
+  //\r
+  ProtEntry = MmFindProtocolEntry (Protocol, TRUE);\r
+  if (ProtEntry == NULL) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Allocate a new protocol interface structure\r
+  //\r
+  Prot = AllocateZeroPool (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 = AllocateZeroPool (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
+    // 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 = MmValidateHandle (Handle);\r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+  //\r
+  // Each interface that is added must be unique\r
+  //\r
+  ASSERT (MmFindProtocolInterface (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
+  // 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
+    MmNotifyProtocol (Prot);\r
+  }\r
+  Status = EFI_SUCCESS;\r
+\r
+Done:\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
+      FreePool (Prot);\r
+    }\r
+  }\r
+  return Status;\r
+}\r
+\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
+  @param  UserHandle             The handle to remove the protocol handler from\r
+  @param  Protocol               The protocol, of protocol:interface, to remove\r
+  @param  Interface              The interface, of protocol:interface, to remove\r
+\r
+  @retval EFI_INVALID_PARAMETER  Protocol is NULL.\r
+  @retval EFI_SUCCESS            Protocol interface successfully uninstalled.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmUninstallProtocolInterface (\r
+  IN EFI_HANDLE  UserHandle,\r
+  IN EFI_GUID    *Protocol,\r
+  IN VOID        *Interface\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 = MmValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Check that Protocol exists on UserHandle, and Interface matches the interface in the database\r
+  //\r
+  Prot = MmFindProtocolInterface (UserHandle, Protocol, Interface);\r
+  if (Prot == NULL) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  //\r
+  // Remove the protocol interface from the protocol\r
+  //\r
+  Status = EFI_NOT_FOUND;\r
+  Handle = (IHANDLE *)UserHandle;\r
+  Prot   = MmRemoveInterfaceFromProtocol (Handle, Protocol, Interface);\r
+\r
+  if (Prot != NULL) {\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
+    FreePool (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
+    FreePool (Handle);\r
+  }\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Locate a certain GUID protocol interface in a Handle's protocols.\r
+\r
+  @param  UserHandle             The handle to obtain the protocol interface on\r
+  @param  Protocol               The GUID of the protocol\r
+\r
+  @return The requested protocol interface for the handle\r
+\r
+**/\r
+PROTOCOL_INTERFACE  *\r
+MmGetProtocolInterface (\r
+  IN EFI_HANDLE  UserHandle,\r
+  IN EFI_GUID    *Protocol\r
+  )\r
+{\r
+  EFI_STATUS          Status;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  IHANDLE             *Handle;\r
+  LIST_ENTRY          *Link;\r
+\r
+  Status = MmValidateHandle (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
+  Queries a handle to determine if it supports a specified protocol.\r
+\r
+  @param  UserHandle             The handle being queried.\r
+  @param  Protocol               The published unique identifier of the protocol.\r
+  @param  Interface              Supplies the address where a pointer to the\r
+                                 corresponding Protocol Interface is returned.\r
+\r
+  @retval EFI_SUCCESS            The interface information for the specified protocol was returned.\r
+  @retval EFI_UNSUPPORTED        The device does not support the specified protocol.\r
+  @retval EFI_INVALID_PARAMETER  Handle is not a valid EFI_HANDLE..\r
+  @retval EFI_INVALID_PARAMETER  Protocol is NULL.\r
+  @retval EFI_INVALID_PARAMETER  Interface is NULL.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmHandleProtocol (\r
+  IN  EFI_HANDLE  UserHandle,\r
+  IN  EFI_GUID    *Protocol,\r
+  OUT VOID        **Interface\r
+  )\r
+{\r
+  EFI_STATUS          Status;\r
+  PROTOCOL_INTERFACE  *Prot;\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 (Interface == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  } else {\r
+    *Interface = NULL;\r
+  }\r
+\r
+  //\r
+  // Check for invalid UserHandle\r
+  //\r
+  Status = MmValidateHandle (UserHandle);\r
+  if (EFI_ERROR (Status)) {\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Look at each protocol interface for a match\r
+  //\r
+  Prot = MmGetProtocolInterface (UserHandle, Protocol);\r
+  if (Prot == NULL) {\r
+    return EFI_UNSUPPORTED;\r
+  }\r
+\r
+  //\r
+  // This is the protocol interface entry for this protocol\r
+  //\r
+  *Interface = Prot->Interface;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/StandaloneMmPkg/Core/InstallConfigurationTable.c b/StandaloneMmPkg/Core/InstallConfigurationTable.c
new file mode 100644 (file)
index 0000000..2392be9
--- /dev/null
@@ -0,0 +1,178 @@
+/** @file\r
+  System Management System Table Services MmInstallConfigurationTable service\r
+\r
+  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+#define CONFIG_TABLE_SIZE_INCREASED 0x10\r
+\r
+UINTN  mMmSystemTableAllocateSize = 0;\r
+\r
+/**\r
+  The MmInstallConfigurationTable() function is used to maintain the list\r
+  of configuration tables that are stored in the System Management System\r
+  Table.  The list is stored as an array of (GUID, Pointer) pairs.  The list\r
+  must be allocated from pool memory with PoolType set to EfiRuntimeServicesData.\r
+\r
+  @param  SystemTable      A pointer to the SMM System Table (SMST).\r
+  @param  Guid             A pointer to the GUID for the entry to add, update, or remove.\r
+  @param  Table            A pointer to the buffer of the table to add.\r
+  @param  TableSize        The size of the table to install.\r
+\r
+  @retval EFI_SUCCESS           The (Guid, Table) pair was added, updated, or removed.\r
+  @retval EFI_INVALID_PARAMETER Guid is not valid.\r
+  @retval EFI_NOT_FOUND         An attempt was made to delete a non-existent entry.\r
+  @retval EFI_OUT_OF_RESOURCES  There is not enough memory available to complete the operation.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInstallConfigurationTable (\r
+  IN  CONST EFI_MM_SYSTEM_TABLE    *SystemTable,\r
+  IN  CONST EFI_GUID               *Guid,\r
+  IN  VOID                         *Table,\r
+  IN  UINTN                        TableSize\r
+  )\r
+{\r
+  UINTN                    Index;\r
+  EFI_CONFIGURATION_TABLE  *ConfigurationTable;\r
+  EFI_CONFIGURATION_TABLE  *OldTable;\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
+  ConfigurationTable = gMmCoreMmst.MmConfigurationTable;\r
+\r
+  //\r
+  // Search all the table for an entry that matches Guid\r
+  //\r
+  for (Index = 0; Index < gMmCoreMmst.NumberOfTableEntries; Index++) {\r
+    if (CompareGuid (Guid, &(ConfigurationTable[Index].VendorGuid))) {\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (Index < gMmCoreMmst.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 entry and return.\r
+      //\r
+      ConfigurationTable[Index].VendorTable = Table;\r
+      return EFI_SUCCESS;\r
+    }\r
+\r
+    //\r
+    // A match was found and Table is NULL, so this is a delete operation.\r
+    //\r
+    gMmCoreMmst.NumberOfTableEntries--;\r
+\r
+    //\r
+    // Copy over deleted entry\r
+    //\r
+    CopyMem (\r
+      &(ConfigurationTable[Index]),\r
+      &(ConfigurationTable[Index + 1]),\r
+      (gMmCoreMmst.NumberOfTableEntries - Index) * sizeof (EFI_CONFIGURATION_TABLE)\r
+      );\r
+\r
+  } else {\r
+    //\r
+    // No matching GUIDs were found, so this is an add operation.\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 == gMmCoreMmst.NumberOfTableEntries\r
+    //\r
+    if ((Index * sizeof (EFI_CONFIGURATION_TABLE)) >= mMmSystemTableAllocateSize) {\r
+      //\r
+      // Allocate a table with one additional entry.\r
+      //\r
+      mMmSystemTableAllocateSize += (CONFIG_TABLE_SIZE_INCREASED * sizeof (EFI_CONFIGURATION_TABLE));\r
+      ConfigurationTable = AllocatePool (mMmSystemTableAllocateSize);\r
+      if (ConfigurationTable == 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 (gMmCoreMmst.MmConfigurationTable != NULL) {\r
+        //\r
+        // Copy the old table to the new table.\r
+        //\r
+        CopyMem (\r
+          ConfigurationTable,\r
+          gMmCoreMmst.MmConfigurationTable,\r
+          Index * sizeof (EFI_CONFIGURATION_TABLE)\r
+          );\r
+\r
+        //\r
+        // Record the old table pointer.\r
+        //\r
+        OldTable = gMmCoreMmst.MmConfigurationTable;\r
+\r
+        //\r
+        // As the MmInstallConfigurationTable() may be re-entered by FreePool() in\r
+        // its calling stack, updating System table to the new table pointer must\r
+        // be done before calling FreePool() to free the old table.\r
+        // It can make sure the gMmCoreMmst.MmConfigurationTable point to the new\r
+        // table and avoid the errors of use-after-free to the old table by the\r
+        // reenter of MmInstallConfigurationTable() in FreePool()'s calling stack.\r
+        //\r
+        gMmCoreMmst.MmConfigurationTable = ConfigurationTable;\r
+\r
+        //\r
+        // Free the old table after updating System Table to the new table pointer.\r
+        //\r
+        FreePool (OldTable);\r
+      } else {\r
+        //\r
+        // Update System Table\r
+        //\r
+        gMmCoreMmst.MmConfigurationTable = ConfigurationTable;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Fill in the new entry\r
+    //\r
+    CopyGuid ((VOID *)&ConfigurationTable[Index].VendorGuid, Guid);\r
+    ConfigurationTable[Index].VendorTable = Table;\r
+\r
+    //\r
+    // This is an add operation, so increment the number of table entries\r
+    //\r
+    gMmCoreMmst.NumberOfTableEntries++;\r
+  }\r
+\r
+  //\r
+  // CRC-32 field is ignorable for SMM System Table and should be set to zero\r
+  //\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/StandaloneMmPkg/Core/Locate.c b/StandaloneMmPkg/Core/Locate.c
new file mode 100644 (file)
index 0000000..9129718
--- /dev/null
@@ -0,0 +1,496 @@
+/** @file\r
+  Locate handle functions\r
+\r
+  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.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
+/**\r
+  Routine to get the next Handle, when you are searching for all handles.\r
+\r
+  @param  Position               Information about which Handle to seach for.\r
+  @param  Interface              Return the interface structure for the matching\r
+                                 protocol.\r
+\r
+  @return An pointer to IHANDLE if the next Position is not the end of the list.\r
+          Otherwise,NULL is returned.\r
+\r
+**/\r
+IHANDLE *\r
+MmGetNextLocateAllHandles (\r
+  IN OUT LOCATE_POSITION  *Position,\r
+  OUT    VOID             **Interface\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;\r
+  *Interface  = NULL;\r
+  if (Position->Position != &gHandleList) {\r
+    Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE);\r
+  }\r
+  return Handle;\r
+}\r
+\r
+/**\r
+  Routine to get the next Handle, when you are searching for register protocol\r
+  notifies.\r
+\r
+  @param  Position               Information about which Handle to seach for.\r
+  @param  Interface              Return the interface structure for the matching\r
+                                 protocol.\r
+\r
+  @return An pointer to IHANDLE if the next Position is not the end of the list.\r
+          Otherwise,NULL is returned.\r
+\r
+**/\r
+IHANDLE *\r
+MmGetNextLocateByRegisterNotify (\r
+  IN OUT LOCATE_POSITION  *Position,\r
+  OUT    VOID             **Interface\r
+  )\r
+{\r
+  IHANDLE             *Handle;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  LIST_ENTRY          *Link;\r
+\r
+  Handle      = NULL;\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 = Prot->Handle;\r
+      *Interface = Prot->Interface;\r
+    }\r
+  }\r
+  return Handle;\r
+}\r
+\r
+/**\r
+  Routine to get the next Handle, when you are searching for a given protocol.\r
+\r
+  @param  Position               Information about which Handle to seach for.\r
+  @param  Interface              Return the interface structure for the matching\r
+                                 protocol.\r
+\r
+  @return An pointer to IHANDLE if the next Position is not the end of the list.\r
+          Otherwise,NULL is returned.\r
+\r
+**/\r
+IHANDLE *\r
+MmGetNextLocateByProtocol (\r
+  IN OUT LOCATE_POSITION  *Position,\r
+  OUT    VOID             **Interface\r
+  )\r
+{\r
+  IHANDLE             *Handle;\r
+  LIST_ENTRY          *Link;\r
+  PROTOCOL_INTERFACE  *Prot;\r
+\r
+  Handle      = NULL;\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;\r
+      break;\r
+    }\r
+\r
+    //\r
+    // Get the handle\r
+    //\r
+    Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE);\r
+    Handle = 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
+  return Handle;\r
+}\r
+\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
+  @param  Protocol               The protocol to search for\r
+  @param  Registration           Optional Registration Key returned from\r
+                                 RegisterProtocolNotify()\r
+  @param  Interface              Return the Protocol interface (instance).\r
+\r
+  @retval EFI_SUCCESS            If a valid Interface is returned\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_NOT_FOUND          Protocol interface not found\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLocateProtocol (\r
+  IN  EFI_GUID  *Protocol,\r
+  IN  VOID      *Registration OPTIONAL,\r
+  OUT VOID      **Interface\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  LOCATE_POSITION         Position;\r
+  PROTOCOL_NOTIFY         *ProtNotify;\r
+  IHANDLE                 *Handle;\r
+\r
+  if ((Interface == NULL) || (Protocol == NULL)) {\r
+    return EFI_INVALID_PARAMETER;\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
+  mEfiLocateHandleRequest += 1;\r
+\r
+  if (Registration == NULL) {\r
+    //\r
+    // Look up the protocol entry and set the head pointer\r
+    //\r
+    Position.ProtEntry = MmFindProtocolEntry (Protocol, FALSE);\r
+    if (Position.ProtEntry == NULL) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+    Position.Position = &Position.ProtEntry->Protocols;\r
+\r
+    Handle = MmGetNextLocateByProtocol (&Position, Interface);\r
+  } else {\r
+    Handle = MmGetNextLocateByRegisterNotify (&Position, Interface);\r
+  }\r
+\r
+  if (Handle == NULL) {\r
+    Status = EFI_NOT_FOUND;\r
+  } else if (Registration != NULL) {\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
+  return Status;\r
+}\r
+\r
+/**\r
+  Locates the requested handle(s) and returns them in Buffer.\r
+\r
+  @param  SearchType             The type of search to perform to locate the\r
+                                 handles\r
+  @param  Protocol               The protocol to search for\r
+  @param  SearchKey              Dependant on SearchType\r
+  @param  BufferSize             On input the size of Buffer.  On output the\r
+                                 size of data returned.\r
+  @param  Buffer                 The buffer to return the results in\r
+\r
+  @retval EFI_BUFFER_TOO_SMALL   Buffer too small, required buffer size is\r
+                                 returned in BufferSize.\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_SUCCESS            Successfully found the requested handle(s) and\r
+                                 returns them in Buffer.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLocateHandle (\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
+  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
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if ((*BufferSize > 0) && (Buffer == NULL)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  GetNext = NULL;\r
+\r
+  //\r
+  // Set initial position\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
+  // Get the search function based on type\r
+  //\r
+  switch (SearchType) {\r
+  case AllHandles:\r
+    GetNext = MmGetNextLocateAllHandles;\r
+    break;\r
+\r
+  case ByRegisterNotify:\r
+    GetNext = MmGetNextLocateByRegisterNotify;\r
+    //\r
+    // Must have SearchKey for locate ByRegisterNotify\r
+    //\r
+    if (SearchKey == NULL) {\r
+      Status = EFI_INVALID_PARAMETER;\r
+    }\r
+    break;\r
+\r
+  case ByProtocol:\r
+    GetNext = MmGetNextLocateByProtocol;\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 = MmFindProtocolEntry (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
+    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
+      ASSERT (SearchKey != NULL);\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
+  return Status;\r
+}\r
+\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 MmLocateHandle()\r
+  that allocates a buffer for the caller.\r
+\r
+  @param  SearchType             Specifies which handle(s) are to be returned.\r
+  @param  Protocol               Provides the protocol to search by.    This\r
+                                 parameter is only valid for SearchType\r
+                                 ByProtocol.\r
+  @param  SearchKey              Supplies the search key depending on the\r
+                                 SearchType.\r
+  @param  NumberHandles          The number of handles returned in Buffer.\r
+  @param  Buffer                 A pointer to the buffer to return the requested\r
+                                 array of  handles that support Protocol.\r
+\r
+  @retval EFI_SUCCESS            The result array of handles was returned.\r
+  @retval EFI_NOT_FOUND          No handles match the search.\r
+  @retval EFI_OUT_OF_RESOURCES   There is not enough pool memory to store the\r
+                                 matching results.\r
+  @retval EFI_INVALID_PARAMETER  One or more parameters are not valid.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLocateHandleBuffer (\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
+  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 = MmLocateHandle (\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 MmLocateHandle().\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 = AllocatePool (BufferSize);\r
+  if (*Buffer == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  Status = MmLocateHandle (\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
diff --git a/StandaloneMmPkg/Core/Mmi.c b/StandaloneMmPkg/Core/Mmi.c
new file mode 100644 (file)
index 0000000..7193ebc
--- /dev/null
@@ -0,0 +1,337 @@
+/** @file\r
+  MMI management.\r
+\r
+  Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+//\r
+// MM_HANDLER_STATE_NOTIFIER\r
+//\r
+\r
+//\r
+// MM_HANDLER - used for each MM handler\r
+//\r
+\r
+#define MMI_ENTRY_SIGNATURE  SIGNATURE_32('m','m','i','e')\r
+\r
+typedef struct {\r
+  UINTN       Signature;\r
+  LIST_ENTRY  AllEntries;  // All entries\r
+\r
+  EFI_GUID    HandlerType; // Type of interrupt\r
+  LIST_ENTRY  MmiHandlers; // All handlers\r
+} MMI_ENTRY;\r
+\r
+#define MMI_HANDLER_SIGNATURE  SIGNATURE_32('m','m','i','h')\r
+\r
+typedef struct {\r
+  UINTN                         Signature;\r
+  LIST_ENTRY                    Link;        // Link on MMI_ENTRY.MmiHandlers\r
+  EFI_MM_HANDLER_ENTRY_POINT    Handler;     // The mm handler's entry point\r
+  MMI_ENTRY                     *MmiEntry;\r
+} MMI_HANDLER;\r
+\r
+LIST_ENTRY  mRootMmiHandlerList = INITIALIZE_LIST_HEAD_VARIABLE (mRootMmiHandlerList);\r
+LIST_ENTRY  mMmiEntryList       = INITIALIZE_LIST_HEAD_VARIABLE (mMmiEntryList);\r
+\r
+/**\r
+  Finds the MMI entry for the requested handler type.\r
+\r
+  @param  HandlerType            The type of the interrupt\r
+  @param  Create                 Create a new entry if not found\r
+\r
+  @return MMI entry\r
+\r
+**/\r
+MMI_ENTRY  *\r
+EFIAPI\r
+MmCoreFindMmiEntry (\r
+  IN EFI_GUID  *HandlerType,\r
+  IN BOOLEAN   Create\r
+  )\r
+{\r
+  LIST_ENTRY  *Link;\r
+  MMI_ENTRY   *Item;\r
+  MMI_ENTRY   *MmiEntry;\r
+\r
+  //\r
+  // Search the MMI entry list for the matching GUID\r
+  //\r
+  MmiEntry = NULL;\r
+  for (Link = mMmiEntryList.ForwardLink;\r
+       Link != &mMmiEntryList;\r
+       Link = Link->ForwardLink) {\r
+\r
+    Item = CR (Link, MMI_ENTRY, AllEntries, MMI_ENTRY_SIGNATURE);\r
+    if (CompareGuid (&Item->HandlerType, HandlerType)) {\r
+      //\r
+      // This is the MMI entry\r
+      //\r
+      MmiEntry = 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 ((MmiEntry == NULL) && Create) {\r
+    MmiEntry = AllocatePool (sizeof (MMI_ENTRY));\r
+    if (MmiEntry != NULL) {\r
+      //\r
+      // Initialize new MMI entry structure\r
+      //\r
+      MmiEntry->Signature = MMI_ENTRY_SIGNATURE;\r
+      CopyGuid ((VOID *)&MmiEntry->HandlerType, HandlerType);\r
+      InitializeListHead (&MmiEntry->MmiHandlers);\r
+\r
+      //\r
+      // Add it to MMI entry list\r
+      //\r
+      InsertTailList (&mMmiEntryList, &MmiEntry->AllEntries);\r
+    }\r
+  }\r
+  return MmiEntry;\r
+}\r
+\r
+/**\r
+  Manage MMI of a particular type.\r
+\r
+  @param  HandlerType    Points to the handler type or NULL for root MMI handlers.\r
+  @param  Context        Points to an optional context buffer.\r
+  @param  CommBuffer     Points to the optional communication buffer.\r
+  @param  CommBufferSize Points to the size of the optional communication buffer.\r
+\r
+  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING  Interrupt source was processed successfully but not quiesced.\r
+  @retval EFI_INTERRUPT_PENDING              One or more MMI sources could not be quiesced.\r
+  @retval EFI_NOT_FOUND                      Interrupt source was not handled or quiesced.\r
+  @retval EFI_SUCCESS                        Interrupt source was handled and quiesced.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiManage (\r
+  IN     CONST EFI_GUID  *HandlerType,\r
+  IN     CONST VOID      *Context         OPTIONAL,\r
+  IN OUT VOID            *CommBuffer      OPTIONAL,\r
+  IN OUT UINTN           *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  LIST_ENTRY   *Link;\r
+  LIST_ENTRY   *Head;\r
+  MMI_ENTRY    *MmiEntry;\r
+  MMI_HANDLER  *MmiHandler;\r
+  BOOLEAN      SuccessReturn;\r
+  EFI_STATUS   Status;\r
+\r
+  Status = EFI_NOT_FOUND;\r
+  SuccessReturn = FALSE;\r
+  if (HandlerType == NULL) {\r
+    //\r
+    // Root MMI handler\r
+    //\r
+\r
+    Head = &mRootMmiHandlerList;\r
+  } else {\r
+    //\r
+    // Non-root MMI handler\r
+    //\r
+    MmiEntry = MmCoreFindMmiEntry ((EFI_GUID *) HandlerType, FALSE);\r
+    if (MmiEntry == NULL) {\r
+      //\r
+      // There is no handler registered for this interrupt source\r
+      //\r
+      return Status;\r
+    }\r
+\r
+    Head = &MmiEntry->MmiHandlers;\r
+  }\r
+\r
+  for (Link = Head->ForwardLink; Link != Head; Link = Link->ForwardLink) {\r
+    MmiHandler = CR (Link, MMI_HANDLER, Link, MMI_HANDLER_SIGNATURE);\r
+\r
+    Status = MmiHandler->Handler (\r
+               (EFI_HANDLE) MmiHandler,\r
+               Context,\r
+               CommBuffer,\r
+               CommBufferSize\r
+               );\r
+\r
+    switch (Status) {\r
+    case EFI_INTERRUPT_PENDING:\r
+      //\r
+      // If a handler returns EFI_INTERRUPT_PENDING and HandlerType is not NULL then\r
+      // no additional handlers will be processed and EFI_INTERRUPT_PENDING will be returned.\r
+      //\r
+      if (HandlerType != NULL) {\r
+        return EFI_INTERRUPT_PENDING;\r
+      }\r
+      break;\r
+\r
+    case EFI_SUCCESS:\r
+      //\r
+      // If at least one of the handlers returns EFI_SUCCESS then the function will return\r
+      // EFI_SUCCESS. If a handler returns EFI_SUCCESS and HandlerType is not NULL then no\r
+      // additional handlers will be processed.\r
+      //\r
+      if (HandlerType != NULL) {\r
+        return EFI_SUCCESS;\r
+      }\r
+      SuccessReturn = TRUE;\r
+      break;\r
+\r
+    case EFI_WARN_INTERRUPT_SOURCE_QUIESCED:\r
+      //\r
+      // If at least one of the handlers returns EFI_WARN_INTERRUPT_SOURCE_QUIESCED\r
+      // then the function will return EFI_SUCCESS.\r
+      //\r
+      SuccessReturn = TRUE;\r
+      break;\r
+\r
+    case EFI_WARN_INTERRUPT_SOURCE_PENDING:\r
+      //\r
+      // If all the handlers returned EFI_WARN_INTERRUPT_SOURCE_PENDING\r
+      // then EFI_WARN_INTERRUPT_SOURCE_PENDING will be returned.\r
+      //\r
+      break;\r
+\r
+    default:\r
+      //\r
+      // Unexpected status code returned.\r
+      //\r
+      ASSERT (FALSE);\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (SuccessReturn) {\r
+    Status = EFI_SUCCESS;\r
+  }\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Registers a handler to execute within MM.\r
+\r
+  @param  Handler        Handler service funtion pointer.\r
+  @param  HandlerType    Points to the handler type or NULL for root MMI handlers.\r
+  @param  DispatchHandle On return, contains a unique handle which can be used to later unregister the handler function.\r
+\r
+  @retval EFI_SUCCESS           Handler register success.\r
+  @retval EFI_INVALID_PARAMETER Handler or DispatchHandle is NULL.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiHandlerRegister (\r
+  IN  EFI_MM_HANDLER_ENTRY_POINT    Handler,\r
+  IN  CONST EFI_GUID                *HandlerType  OPTIONAL,\r
+  OUT EFI_HANDLE                    *DispatchHandle\r
+  )\r
+{\r
+  MMI_HANDLER  *MmiHandler;\r
+  MMI_ENTRY    *MmiEntry;\r
+  LIST_ENTRY   *List;\r
+\r
+  if (Handler == NULL || DispatchHandle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  MmiHandler = AllocateZeroPool (sizeof (MMI_HANDLER));\r
+  if (MmiHandler == NULL) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  MmiHandler->Signature = MMI_HANDLER_SIGNATURE;\r
+  MmiHandler->Handler = Handler;\r
+\r
+  if (HandlerType == NULL) {\r
+    //\r
+    // This is root MMI handler\r
+    //\r
+    MmiEntry = NULL;\r
+    List = &mRootMmiHandlerList;\r
+  } else {\r
+    //\r
+    // None root MMI handler\r
+    //\r
+    MmiEntry = MmCoreFindMmiEntry ((EFI_GUID *) HandlerType, TRUE);\r
+    if (MmiEntry == NULL) {\r
+      return EFI_OUT_OF_RESOURCES;\r
+    }\r
+\r
+    List = &MmiEntry->MmiHandlers;\r
+  }\r
+\r
+  MmiHandler->MmiEntry = MmiEntry;\r
+  InsertTailList (List, &MmiHandler->Link);\r
+\r
+  *DispatchHandle = (EFI_HANDLE) MmiHandler;\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Unregister a handler in MM.\r
+\r
+  @param  DispatchHandle  The handle that was specified when the handler was registered.\r
+\r
+  @retval EFI_SUCCESS           Handler function was successfully unregistered.\r
+  @retval EFI_INVALID_PARAMETER DispatchHandle does not refer to a valid handle.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiHandlerUnRegister (\r
+  IN EFI_HANDLE  DispatchHandle\r
+  )\r
+{\r
+  MMI_HANDLER  *MmiHandler;\r
+  MMI_ENTRY    *MmiEntry;\r
+\r
+  MmiHandler = (MMI_HANDLER *) DispatchHandle;\r
+\r
+  if (MmiHandler == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (MmiHandler->Signature != MMI_HANDLER_SIGNATURE) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  MmiEntry = MmiHandler->MmiEntry;\r
+\r
+  RemoveEntryList (&MmiHandler->Link);\r
+  FreePool (MmiHandler);\r
+\r
+  if (MmiEntry == NULL) {\r
+    //\r
+    // This is root MMI handler\r
+    //\r
+    return EFI_SUCCESS;\r
+  }\r
+\r
+  if (IsListEmpty (&MmiEntry->MmiHandlers)) {\r
+    //\r
+    // No handler registered for this interrupt now, remove the MMI_ENTRY\r
+    //\r
+    RemoveEntryList (&MmiEntry->AllEntries);\r
+\r
+    FreePool (MmiEntry);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/StandaloneMmPkg/Core/Notify.c b/StandaloneMmPkg/Core/Notify.c
new file mode 100644 (file)
index 0000000..57a03fe
--- /dev/null
@@ -0,0 +1,203 @@
+/** @file\r
+  Support functions for UEFI protocol notification infrastructure.\r
+\r
+  Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+/**\r
+  Signal event for every protocol in protocol entry.\r
+\r
+  @param  Prot                   Protocol interface\r
+\r
+**/\r
+VOID\r
+MmNotifyProtocol (\r
+  IN PROTOCOL_INTERFACE  *Prot\r
+  )\r
+{\r
+  PROTOCOL_ENTRY   *ProtEntry;\r
+  PROTOCOL_NOTIFY  *ProtNotify;\r
+  LIST_ENTRY       *Link;\r
+\r
+  ProtEntry = Prot->Protocol;\r
+  for (Link=ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) {\r
+    ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);\r
+    ProtNotify->Function (&ProtEntry->ProtocolID, Prot->Interface, Prot->Handle);\r
+  }\r
+}\r
+\r
+/**\r
+  Removes Protocol from the protocol list (but not the handle list).\r
+\r
+  @param  Handle                 The handle to remove protocol on.\r
+  @param  Protocol               GUID of the protocol to be moved\r
+  @param  Interface              The interface of the protocol\r
+\r
+  @return Protocol Entry\r
+\r
+**/\r
+PROTOCOL_INTERFACE *\r
+MmRemoveInterfaceFromProtocol (\r
+  IN IHANDLE   *Handle,\r
+  IN EFI_GUID  *Protocol,\r
+  IN VOID      *Interface\r
+  )\r
+{\r
+  PROTOCOL_INTERFACE  *Prot;\r
+  PROTOCOL_NOTIFY     *ProtNotify;\r
+  PROTOCOL_ENTRY      *ProtEntry;\r
+  LIST_ENTRY          *Link;\r
+\r
+  Prot = MmFindProtocolInterface (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
+    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
+    RemoveEntryList (&Prot->ByProtocol);\r
+  }\r
+\r
+  return Prot;\r
+}\r
+\r
+/**\r
+  Add a new protocol notification record for the request protocol.\r
+\r
+  @param  Protocol               The requested protocol to add the notify\r
+                                 registration\r
+  @param  Function               Points to the notification function\r
+  @param  Registration           Returns the registration record\r
+\r
+  @retval EFI_SUCCESS            Successfully returned the registration record\r
+                                 that has been added or unhooked\r
+  @retval EFI_INVALID_PARAMETER  Protocol is NULL or Registration is NULL\r
+  @retval EFI_OUT_OF_RESOURCES   Not enough memory resource to finish the request\r
+  @retval EFI_NOT_FOUND          If the registration is not found when Function == NULL\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmRegisterProtocolNotify (\r
+  IN  CONST EFI_GUID     *Protocol,\r
+  IN  EFI_MM_NOTIFY_FN  Function,\r
+  OUT VOID               **Registration\r
+  )\r
+{\r
+  PROTOCOL_ENTRY   *ProtEntry;\r
+  PROTOCOL_NOTIFY  *ProtNotify;\r
+  LIST_ENTRY       *Link;\r
+  EFI_STATUS       Status;\r
+\r
+  if (Protocol == NULL || Registration == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Function == NULL) {\r
+    //\r
+    // Get the protocol entry per Protocol\r
+    //\r
+    ProtEntry = MmFindProtocolEntry ((EFI_GUID *) Protocol, FALSE);\r
+    if (ProtEntry != NULL) {\r
+      ProtNotify = (PROTOCOL_NOTIFY * )*Registration;\r
+      for (Link = ProtEntry->Notify.ForwardLink;\r
+           Link != &ProtEntry->Notify;\r
+           Link = Link->ForwardLink) {\r
+        //\r
+        // Compare the notification record\r
+        //\r
+        if (ProtNotify == (CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE))) {\r
+          //\r
+          // If Registration is an existing registration, then unhook it\r
+          //\r
+          ProtNotify->Signature = 0;\r
+          RemoveEntryList (&ProtNotify->Link);\r
+          FreePool (ProtNotify);\r
+          return EFI_SUCCESS;\r
+        }\r
+      }\r
+    }\r
+    //\r
+    // If the registration is not found\r
+    //\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  ProtNotify = NULL;\r
+\r
+  //\r
+  // Get the protocol entry to add the notification too\r
+  //\r
+  ProtEntry = MmFindProtocolEntry ((EFI_GUID *) Protocol, TRUE);\r
+  if (ProtEntry != NULL) {\r
+    //\r
+    // Find whether notification already exist\r
+    //\r
+    for (Link = ProtEntry->Notify.ForwardLink;\r
+         Link != &ProtEntry->Notify;\r
+         Link = Link->ForwardLink) {\r
+\r
+      ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);\r
+      if (CompareGuid (&ProtNotify->Protocol->ProtocolID, Protocol) &&\r
+          (ProtNotify->Function == Function)) {\r
+\r
+        //\r
+        // Notification already exist\r
+        //\r
+        *Registration = ProtNotify;\r
+\r
+        return EFI_SUCCESS;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Allocate a new notification record\r
+    //\r
+    ProtNotify = AllocatePool (sizeof (PROTOCOL_NOTIFY));\r
+    if (ProtNotify != NULL) {\r
+      ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE;\r
+      ProtNotify->Protocol = ProtEntry;\r
+      ProtNotify->Function = Function;\r
+      //\r
+      // Start at the ending\r
+      //\r
+      ProtNotify->Position = ProtEntry->Protocols.BackLink;\r
+\r
+      InsertTailList (&ProtEntry->Notify, &ProtNotify->Link);\r
+    }\r
+  }\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
+  Status = EFI_OUT_OF_RESOURCES;\r
+  if (ProtNotify != NULL) {\r
+    *Registration = ProtNotify;\r
+    Status = EFI_SUCCESS;\r
+  }\r
+  return Status;\r
+}\r
diff --git a/StandaloneMmPkg/Core/Page.c b/StandaloneMmPkg/Core/Page.c
new file mode 100644 (file)
index 0000000..8250f8c
--- /dev/null
@@ -0,0 +1,384 @@
+/** @file\r
+  MM Memory page management functions.\r
+\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+#define NEXT_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \\r
+  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size)))\r
+\r
+#define TRUNCATE_TO_PAGES(a)  ((a) >> EFI_PAGE_SHIFT)\r
+\r
+LIST_ENTRY  mMmMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (mMmMemoryMap);\r
+\r
+UINTN mMapKey;\r
+\r
+/**\r
+  Internal Function. Allocate n pages from given free page node.\r
+\r
+  @param  Pages                  The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+\r
+  @return Memory address of allocated pages.\r
+\r
+**/\r
+UINTN\r
+InternalAllocPagesOnOneNode (\r
+  IN OUT FREE_PAGE_LIST  *Pages,\r
+  IN     UINTN           NumberOfPages,\r
+  IN     UINTN           MaxAddress\r
+  )\r
+{\r
+  UINTN           Top;\r
+  UINTN           Bottom;\r
+  FREE_PAGE_LIST  *Node;\r
+\r
+  Top = TRUNCATE_TO_PAGES (MaxAddress + 1 - (UINTN)Pages);\r
+  if (Top > Pages->NumberOfPages) {\r
+    Top = Pages->NumberOfPages;\r
+  }\r
+  Bottom = Top - NumberOfPages;\r
+\r
+  if (Top < Pages->NumberOfPages) {\r
+    Node = (FREE_PAGE_LIST*)((UINTN)Pages + EFI_PAGES_TO_SIZE (Top));\r
+    Node->NumberOfPages = Pages->NumberOfPages - Top;\r
+    InsertHeadList (&Pages->Link, &Node->Link);\r
+  }\r
+\r
+  if (Bottom > 0) {\r
+    Pages->NumberOfPages = Bottom;\r
+  } else {\r
+    RemoveEntryList (&Pages->Link);\r
+  }\r
+\r
+  return (UINTN)Pages + EFI_PAGES_TO_SIZE (Bottom);\r
+}\r
+\r
+/**\r
+  Internal Function. Allocate n pages from free page list below MaxAddress.\r
+\r
+  @param  FreePageList           The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+\r
+  @return Memory address of allocated pages.\r
+\r
+**/\r
+UINTN\r
+InternalAllocMaxAddress (\r
+  IN OUT LIST_ENTRY  *FreePageList,\r
+  IN     UINTN       NumberOfPages,\r
+  IN     UINTN       MaxAddress\r
+  )\r
+{\r
+  LIST_ENTRY      *Node;\r
+  FREE_PAGE_LIST  *Pages;\r
+\r
+  for (Node = FreePageList->BackLink; Node != FreePageList; Node = Node->BackLink) {\r
+    Pages = BASE_CR (Node, FREE_PAGE_LIST, Link);\r
+    if (Pages->NumberOfPages >= NumberOfPages &&\r
+        (UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress) {\r
+      return InternalAllocPagesOnOneNode (Pages, NumberOfPages, MaxAddress);\r
+    }\r
+  }\r
+  return (UINTN)(-1);\r
+}\r
+\r
+/**\r
+  Internal Function. Allocate n pages from free page list at given address.\r
+\r
+  @param  FreePageList           The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+\r
+  @return Memory address of allocated pages.\r
+\r
+**/\r
+UINTN\r
+InternalAllocAddress (\r
+  IN OUT LIST_ENTRY  *FreePageList,\r
+  IN     UINTN       NumberOfPages,\r
+  IN     UINTN       Address\r
+  )\r
+{\r
+  UINTN           EndAddress;\r
+  LIST_ENTRY      *Node;\r
+  FREE_PAGE_LIST  *Pages;\r
+\r
+  if ((Address & EFI_PAGE_MASK) != 0) {\r
+    return ~Address;\r
+  }\r
+\r
+  EndAddress = Address + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  for (Node = FreePageList->BackLink; Node!= FreePageList; Node = Node->BackLink) {\r
+    Pages = BASE_CR (Node, FREE_PAGE_LIST, Link);\r
+    if ((UINTN)Pages <= Address) {\r
+      if ((UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages) < EndAddress) {\r
+        break;\r
+      }\r
+      return InternalAllocPagesOnOneNode (Pages, NumberOfPages, EndAddress);\r
+    }\r
+  }\r
+  return ~Address;\r
+}\r
+\r
+/**\r
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform.\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into.\r
+  @param  NumberOfPages          The number of pages to allocate.\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address.\r
+\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalAllocatePages (\r
+  IN  EFI_ALLOCATE_TYPE     Type,\r
+  IN  EFI_MEMORY_TYPE       MemoryType,\r
+  IN  UINTN                 NumberOfPages,\r
+  OUT EFI_PHYSICAL_ADDRESS  *Memory\r
+  )\r
+{\r
+  UINTN  RequestedAddress;\r
+\r
+  if (MemoryType != EfiRuntimeServicesCode &&\r
+      MemoryType != EfiRuntimeServicesData) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (NumberOfPages > TRUNCATE_TO_PAGES ((UINTN)-1) + 1) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+\r
+  //\r
+  // We don't track memory type in MM\r
+  //\r
+  RequestedAddress = (UINTN)*Memory;\r
+  switch (Type) {\r
+    case AllocateAnyPages:\r
+      RequestedAddress = (UINTN)(-1);\r
+    case AllocateMaxAddress:\r
+      *Memory = InternalAllocMaxAddress (\r
+                  &mMmMemoryMap,\r
+                  NumberOfPages,\r
+                  RequestedAddress\r
+                  );\r
+      if (*Memory == (UINTN)-1) {\r
+        return EFI_OUT_OF_RESOURCES;\r
+      }\r
+      break;\r
+    case AllocateAddress:\r
+      *Memory = InternalAllocAddress (\r
+                  &mMmMemoryMap,\r
+                  NumberOfPages,\r
+                  RequestedAddress\r
+                  );\r
+      if (*Memory != RequestedAddress) {\r
+        return EFI_NOT_FOUND;\r
+      }\r
+      break;\r
+    default:\r
+      return EFI_INVALID_PARAMETER;\r
+  }\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform.\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into.\r
+  @param  NumberOfPages          The number of pages to allocate.\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address.\r
+\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmAllocatePages (\r
+  IN  EFI_ALLOCATE_TYPE     Type,\r
+  IN  EFI_MEMORY_TYPE       MemoryType,\r
+  IN  UINTN                 NumberOfPages,\r
+  OUT EFI_PHYSICAL_ADDRESS  *Memory\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = MmInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Internal Function. Merge two adjacent nodes.\r
+\r
+  @param  First             The first of two nodes to merge.\r
+\r
+  @return Pointer to node after merge (if success) or pointer to next node (if fail).\r
+\r
+**/\r
+FREE_PAGE_LIST *\r
+InternalMergeNodes (\r
+  IN FREE_PAGE_LIST  *First\r
+  )\r
+{\r
+  FREE_PAGE_LIST  *Next;\r
+\r
+  Next = BASE_CR (First->Link.ForwardLink, FREE_PAGE_LIST, Link);\r
+  ASSERT (\r
+    TRUNCATE_TO_PAGES ((UINTN)Next - (UINTN)First) >= First->NumberOfPages);\r
+\r
+  if (TRUNCATE_TO_PAGES ((UINTN)Next - (UINTN)First) == First->NumberOfPages) {\r
+    First->NumberOfPages += Next->NumberOfPages;\r
+    RemoveEntryList (&Next->Link);\r
+    Next = First;\r
+  }\r
+  return Next;\r
+}\r
+\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param  Memory                 Base address of memory being freed.\r
+  @param  NumberOfPages          The number of pages to free.\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalFreePages (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages\r
+  )\r
+{\r
+  LIST_ENTRY      *Node;\r
+  FREE_PAGE_LIST  *Pages;\r
+\r
+  if ((Memory & EFI_PAGE_MASK) != 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Pages = NULL;\r
+  Node = mMmMemoryMap.ForwardLink;\r
+  while (Node != &mMmMemoryMap) {\r
+    Pages = BASE_CR (Node, FREE_PAGE_LIST, Link);\r
+    if (Memory < (UINTN)Pages) {\r
+      break;\r
+    }\r
+    Node = Node->ForwardLink;\r
+  }\r
+\r
+  if (Node != &mMmMemoryMap &&\r
+      Memory + EFI_PAGES_TO_SIZE (NumberOfPages) > (UINTN)Pages) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  if (Node->BackLink != &mMmMemoryMap) {\r
+    Pages = BASE_CR (Node->BackLink, FREE_PAGE_LIST, Link);\r
+    if ((UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages) > Memory) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+  }\r
+\r
+  Pages = (FREE_PAGE_LIST*)(UINTN)Memory;\r
+  Pages->NumberOfPages = NumberOfPages;\r
+  InsertTailList (Node, &Pages->Link);\r
+\r
+  if (Pages->Link.BackLink != &mMmMemoryMap) {\r
+    Pages = InternalMergeNodes (\r
+              BASE_CR (Pages->Link.BackLink, FREE_PAGE_LIST, Link)\r
+              );\r
+  }\r
+\r
+  if (Node != &mMmMemoryMap) {\r
+    InternalMergeNodes (Pages);\r
+  }\r
+\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param  Memory                 Base address of memory being freed.\r
+  @param  NumberOfPages          The number of pages to free.\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFreePages (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = MmInternalFreePages (Memory, NumberOfPages);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Add free MMRAM region for use by memory service.\r
+\r
+  @param  MemBase                Base address of memory region.\r
+  @param  MemLength              Length of the memory region.\r
+  @param  Type                   Memory type.\r
+  @param  Attributes             Memory region state.\r
+\r
+**/\r
+VOID\r
+MmAddMemoryRegion (\r
+  IN  EFI_PHYSICAL_ADDRESS  MemBase,\r
+  IN  UINT64                MemLength,\r
+  IN  EFI_MEMORY_TYPE       Type,\r
+  IN  UINT64                Attributes\r
+  )\r
+{\r
+  UINTN  AlignedMemBase;\r
+\r
+  //\r
+  // Do not add memory regions that is already allocated, needs testing, or needs ECC initialization\r
+  //\r
+  if ((Attributes & (EFI_ALLOCATED | EFI_NEEDS_TESTING | EFI_NEEDS_ECC_INITIALIZATION)) != 0) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // Align range on an EFI_PAGE_SIZE boundary\r
+  //\r
+  AlignedMemBase = (UINTN)(MemBase + EFI_PAGE_MASK) & ~EFI_PAGE_MASK;\r
+  MemLength -= AlignedMemBase - MemBase;\r
+  MmFreePages (AlignedMemBase, TRUNCATE_TO_PAGES ((UINTN)MemLength));\r
+}\r
diff --git a/StandaloneMmPkg/Core/Pool.c b/StandaloneMmPkg/Core/Pool.c
new file mode 100644 (file)
index 0000000..ce6cfcb
--- /dev/null
@@ -0,0 +1,293 @@
+/** @file\r
+  SMM Memory pool management functions.\r
+\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+LIST_ENTRY  mMmPoolLists[MAX_POOL_INDEX];\r
+//\r
+// To cache the MMRAM base since when Loading modules At fixed address feature is enabled,\r
+// all module is assigned an offset relative the MMRAM base in build time.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED  EFI_PHYSICAL_ADDRESS       gLoadModuleAtFixAddressMmramBase = 0;\r
+\r
+/**\r
+  Called to initialize the memory service.\r
+\r
+  @param   MmramRangeCount       Number of MMRAM Regions\r
+  @param   MmramRanges           Pointer to MMRAM Descriptors\r
+\r
+**/\r
+VOID\r
+MmInitializeMemoryServices (\r
+  IN UINTN                 MmramRangeCount,\r
+  IN EFI_MMRAM_DESCRIPTOR  *MmramRanges\r
+  )\r
+{\r
+  UINTN                  Index;\r
+\r
+  //\r
+  // Initialize Pool list\r
+  //\r
+  for (Index = sizeof (mMmPoolLists) / sizeof (*mMmPoolLists); Index > 0;) {\r
+    InitializeListHead (&mMmPoolLists[--Index]);\r
+  }\r
+\r
+\r
+  //\r
+  // Initialize free MMRAM regions\r
+  //\r
+  for (Index = 0; Index < MmramRangeCount; Index++) {\r
+    //\r
+    // BUGBUG: Add legacy MMRAM region is buggy.\r
+    //\r
+    if (MmramRanges[Index].CpuStart < BASE_1MB) {\r
+      continue;\r
+    }\r
+    DEBUG ((DEBUG_INFO, "MmAddMemoryRegion %d : 0x%016lx - 0x%016lx\n",\r
+           Index, MmramRanges[Index].CpuStart, MmramRanges[Index].PhysicalSize));\r
+    MmAddMemoryRegion (\r
+      MmramRanges[Index].CpuStart,\r
+      MmramRanges[Index].PhysicalSize,\r
+      EfiConventionalMemory,\r
+      MmramRanges[Index].RegionState\r
+      );\r
+  }\r
+\r
+}\r
+\r
+/**\r
+  Internal Function. Allocate a pool by specified PoolIndex.\r
+\r
+  @param  PoolIndex             Index which indicate the Pool size.\r
+  @param  FreePoolHdr           The returned Free pool.\r
+\r
+  @retval EFI_OUT_OF_RESOURCES   Allocation failed.\r
+  @retval EFI_SUCCESS            Pool successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+InternalAllocPoolByIndex (\r
+  IN  UINTN             PoolIndex,\r
+  OUT FREE_POOL_HEADER  **FreePoolHdr\r
+  )\r
+{\r
+  EFI_STATUS            Status;\r
+  FREE_POOL_HEADER      *Hdr;\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+\r
+  ASSERT (PoolIndex <= MAX_POOL_INDEX);\r
+  Status = EFI_SUCCESS;\r
+  Hdr = NULL;\r
+  if (PoolIndex == MAX_POOL_INDEX) {\r
+    Status = MmInternalAllocatePages (\r
+                    AllocateAnyPages,\r
+               EfiRuntimeServicesData,\r
+               EFI_SIZE_TO_PAGES (MAX_POOL_SIZE << 1),\r
+               &Address\r
+               );\r
+    if (EFI_ERROR (Status)) {\r
+      return EFI_OUT_OF_RESOURCES;\r
+    }\r
+    Hdr = (FREE_POOL_HEADER *) (UINTN) Address;\r
+  } else if (!IsListEmpty (&mMmPoolLists[PoolIndex])) {\r
+    Hdr = BASE_CR (GetFirstNode (&mMmPoolLists[PoolIndex]), FREE_POOL_HEADER, Link);\r
+    RemoveEntryList (&Hdr->Link);\r
+  } else {\r
+    Status = InternalAllocPoolByIndex (PoolIndex + 1, &Hdr);\r
+    if (!EFI_ERROR (Status)) {\r
+      Hdr->Header.Size >>= 1;\r
+      Hdr->Header.Available = TRUE;\r
+      InsertHeadList (&mMmPoolLists[PoolIndex], &Hdr->Link);\r
+      Hdr = (FREE_POOL_HEADER*)((UINT8*)Hdr + Hdr->Header.Size);\r
+    }\r
+  }\r
+\r
+  if (!EFI_ERROR (Status)) {\r
+    Hdr->Header.Size = MIN_POOL_SIZE << PoolIndex;\r
+    Hdr->Header.Available = FALSE;\r
+  }\r
+\r
+  *FreePoolHdr = Hdr;\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Internal Function. Free a pool by specified PoolIndex.\r
+\r
+  @param  FreePoolHdr           The pool to free.\r
+\r
+  @retval EFI_SUCCESS           Pool successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+InternalFreePoolByIndex (\r
+  IN FREE_POOL_HEADER  *FreePoolHdr\r
+  )\r
+{\r
+  UINTN  PoolIndex;\r
+\r
+  ASSERT ((FreePoolHdr->Header.Size & (FreePoolHdr->Header.Size - 1)) == 0);\r
+  ASSERT (((UINTN)FreePoolHdr & (FreePoolHdr->Header.Size - 1)) == 0);\r
+  ASSERT (FreePoolHdr->Header.Size >= MIN_POOL_SIZE);\r
+\r
+  PoolIndex = (UINTN) (HighBitSet32 ((UINT32)FreePoolHdr->Header.Size) - MIN_POOL_SHIFT);\r
+  FreePoolHdr->Header.Available = TRUE;\r
+  ASSERT (PoolIndex < MAX_POOL_INDEX);\r
+  InsertHeadList (&mMmPoolLists[PoolIndex], &FreePoolHdr->Link);\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Allocate pool of a particular type.\r
+\r
+  @param  PoolType               Type of pool to allocate.\r
+  @param  Size                   The amount of pool to allocate.\r
+  @param  Buffer                 The address to return a pointer to the allocated\r
+                                 pool.\r
+\r
+  @retval EFI_INVALID_PARAMETER  PoolType not valid.\r
+  @retval EFI_OUT_OF_RESOURCES   Size exceeds max pool size or allocation failed.\r
+  @retval EFI_SUCCESS            Pool successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalAllocatePool (\r
+  IN   EFI_MEMORY_TYPE  PoolType,\r
+  IN   UINTN            Size,\r
+  OUT  VOID             **Buffer\r
+  )\r
+{\r
+  POOL_HEADER           *PoolHdr;\r
+  FREE_POOL_HEADER      *FreePoolHdr;\r
+  EFI_STATUS            Status;\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+  UINTN                 PoolIndex;\r
+\r
+  if (PoolType != EfiRuntimeServicesCode &&\r
+      PoolType != EfiRuntimeServicesData) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Size += sizeof (*PoolHdr);\r
+  if (Size > MAX_POOL_SIZE) {\r
+    Size = EFI_SIZE_TO_PAGES (Size);\r
+    Status = MmInternalAllocatePages (AllocateAnyPages, PoolType, Size, &Address);\r
+    if (EFI_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+\r
+    PoolHdr = (POOL_HEADER*)(UINTN)Address;\r
+    PoolHdr->Size = EFI_PAGES_TO_SIZE (Size);\r
+    PoolHdr->Available = FALSE;\r
+    *Buffer = PoolHdr + 1;\r
+    return Status;\r
+  }\r
+\r
+  Size = (Size + MIN_POOL_SIZE - 1) >> MIN_POOL_SHIFT;\r
+  PoolIndex = (UINTN) HighBitSet32 ((UINT32)Size);\r
+  if ((Size & (Size - 1)) != 0) {\r
+    PoolIndex++;\r
+  }\r
+\r
+  Status = InternalAllocPoolByIndex (PoolIndex, &FreePoolHdr);\r
+  if (!EFI_ERROR (Status)) {\r
+    *Buffer = &FreePoolHdr->Header + 1;\r
+  }\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Allocate pool of a particular type.\r
+\r
+  @param  PoolType               Type of pool to allocate.\r
+  @param  Size                   The amount of pool to allocate.\r
+  @param  Buffer                 The address to return a pointer to the allocated\r
+                                 pool.\r
+\r
+  @retval EFI_INVALID_PARAMETER  PoolType not valid.\r
+  @retval EFI_OUT_OF_RESOURCES   Size exceeds max pool size or allocation failed.\r
+  @retval EFI_SUCCESS            Pool successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmAllocatePool (\r
+  IN   EFI_MEMORY_TYPE  PoolType,\r
+  IN   UINTN            Size,\r
+  OUT  VOID             **Buffer\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = MmInternalAllocatePool (PoolType, Size, Buffer);\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Frees pool.\r
+\r
+  @param  Buffer                 The allocated pool entry to free.\r
+\r
+  @retval EFI_INVALID_PARAMETER  Buffer is not a valid value.\r
+  @retval EFI_SUCCESS            Pool successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalFreePool (\r
+  IN VOID  *Buffer\r
+  )\r
+{\r
+  FREE_POOL_HEADER  *FreePoolHdr;\r
+\r
+  if (Buffer == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  FreePoolHdr = (FREE_POOL_HEADER*)((POOL_HEADER*)Buffer - 1);\r
+  ASSERT (!FreePoolHdr->Header.Available);\r
+\r
+  if (FreePoolHdr->Header.Size > MAX_POOL_SIZE) {\r
+    ASSERT (((UINTN)FreePoolHdr & EFI_PAGE_MASK) == 0);\r
+    ASSERT ((FreePoolHdr->Header.Size & EFI_PAGE_MASK) == 0);\r
+    return MmInternalFreePages (\r
+             (EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr,\r
+             EFI_SIZE_TO_PAGES (FreePoolHdr->Header.Size)\r
+             );\r
+  }\r
+  return InternalFreePoolByIndex (FreePoolHdr);\r
+}\r
+\r
+/**\r
+  Frees pool.\r
+\r
+  @param  Buffer                 The allocated pool entry to free.\r
+\r
+  @retval EFI_INVALID_PARAMETER  Buffer is not a valid value.\r
+  @retval EFI_SUCCESS            Pool successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFreePool (\r
+  IN VOID  *Buffer\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = MmInternalFreePool (Buffer);\r
+  return Status;\r
+}\r
diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.c b/StandaloneMmPkg/Core/StandaloneMmCore.c
new file mode 100644 (file)
index 0000000..7443232
--- /dev/null
@@ -0,0 +1,712 @@
+/** @file\r
+  MM Core Main Entry Point\r
+\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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 "StandaloneMmCore.h"\r
+\r
+EFI_STATUS\r
+MmCoreFfsFindMmDriver (\r
+  IN  EFI_FIRMWARE_VOLUME_HEADER  *FwVolHeader\r
+  );\r
+\r
+EFI_STATUS\r
+MmDispatcher (\r
+  VOID\r
+  );\r
+\r
+//\r
+// Globals used to initialize the protocol\r
+//\r
+EFI_HANDLE            mMmCpuHandle = NULL;\r
+\r
+//\r
+// Physical pointer to private structure shared between MM IPL and the MM Core\r
+//\r
+MM_CORE_PRIVATE_DATA  *gMmCorePrivate;\r
+\r
+//\r
+// MM Core global variable for MM System Table.  Only accessed as a physical structure in MMRAM.\r
+//\r
+EFI_MM_SYSTEM_TABLE  gMmCoreMmst = {\r
+\r
+  // The table header for the MMST.\r
+  {\r
+    MM_MMST_SIGNATURE,\r
+    EFI_MM_SYSTEM_TABLE_REVISION,\r
+    sizeof (gMmCoreMmst.Hdr)\r
+  },\r
+  // MmFirmwareVendor\r
+  NULL,\r
+  // MmFirmwareRevision\r
+  0,\r
+  // MmInstallConfigurationTable\r
+  MmInstallConfigurationTable,\r
+  // I/O Service\r
+  {\r
+    {\r
+      (EFI_MM_CPU_IO) MmEfiNotAvailableYetArg5,       // MmMemRead\r
+      (EFI_MM_CPU_IO) MmEfiNotAvailableYetArg5        // MmMemWrite\r
+    },\r
+    {\r
+      (EFI_MM_CPU_IO) MmEfiNotAvailableYetArg5,       // MmIoRead\r
+      (EFI_MM_CPU_IO) MmEfiNotAvailableYetArg5        // MmIoWrite\r
+    }\r
+  },\r
+  // Runtime memory services\r
+  MmAllocatePool,\r
+  MmFreePool,\r
+  MmAllocatePages,\r
+  MmFreePages,\r
+  // MP service\r
+  NULL,                          // MmStartupThisAp\r
+  0,                             // CurrentlyExecutingCpu\r
+  0,                             // NumberOfCpus\r
+  NULL,                          // CpuSaveStateSize\r
+  NULL,                          // CpuSaveState\r
+  0,                             // NumberOfTableEntries\r
+  NULL,                          // MmConfigurationTable\r
+  MmInstallProtocolInterface,\r
+  MmUninstallProtocolInterface,\r
+  MmHandleProtocol,\r
+  MmRegisterProtocolNotify,\r
+  MmLocateHandle,\r
+  MmLocateProtocol,\r
+  MmiManage,\r
+  MmiHandlerRegister,\r
+  MmiHandlerUnRegister\r
+};\r
+\r
+//\r
+// Flag to determine if the platform has performed a legacy boot.\r
+// If this flag is TRUE, then the runtime code and runtime data associated with the\r
+// MM IPL are converted to free memory, so the MM Core must guarantee that is\r
+// does not touch of the code/data associated with the MM IPL if this flag is TRUE.\r
+//\r
+BOOLEAN  mInLegacyBoot = FALSE;\r
+\r
+//\r
+// Table of MMI Handlers that are registered by the MM Core when it is initialized\r
+//\r
+MM_CORE_MMI_HANDLERS  mMmCoreMmiHandlers[] = {\r
+  { MmFvDispatchHandler,     &gMmFvDispatchGuid,                 NULL, TRUE  },\r
+  { MmDriverDispatchHandler, &gEfiEventDxeDispatchGuid,          NULL, TRUE  },\r
+  { MmReadyToLockHandler,    &gEfiDxeMmReadyToLockProtocolGuid,  NULL, TRUE  },\r
+  { MmEndOfDxeHandler,       &gEfiEndOfDxeEventGroupGuid,        NULL, FALSE },\r
+  { MmLegacyBootHandler,     &gEfiEventLegacyBootGuid,           NULL, FALSE },\r
+  { MmExitBootServiceHandler,&gEfiEventExitBootServicesGuid,     NULL, FALSE },\r
+  { MmReadyToBootHandler,    &gEfiEventReadyToBootGuid,          NULL, FALSE },\r
+  { NULL,                    NULL,                               NULL, FALSE },\r
+};\r
+\r
+EFI_SYSTEM_TABLE                *mEfiSystemTable;\r
+UINTN                           mMmramRangeCount;\r
+EFI_MMRAM_DESCRIPTOR            *mMmramRanges;\r
+\r
+/**\r
+  Place holder function until all the MM System Table Service are available.\r
+\r
+  Note: This function is only used by MMRAM invocation.  It is never used by DXE invocation.\r
+\r
+  @param  Arg1                   Undefined\r
+  @param  Arg2                   Undefined\r
+  @param  Arg3                   Undefined\r
+  @param  Arg4                   Undefined\r
+  @param  Arg5                   Undefined\r
+\r
+  @return EFI_NOT_AVAILABLE_YET\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmEfiNotAvailableYetArg5 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4,\r
+  UINTN Arg5\r
+  )\r
+{\r
+  //\r
+  // This function should never be executed.  If it does, then the architectural protocols\r
+  // have not been designed correctly.\r
+  //\r
+  return EFI_NOT_AVAILABLE_YET;\r
+}\r
+\r
+/**\r
+  Software MMI handler that is called when a Legacy Boot event is signaled.  The MM\r
+  Core uses this signal to know that a Legacy Boot has been performed and that\r
+  gMmCorePrivate that is shared between the UEFI and MM execution environments can\r
+  not be accessed from MM anymore since that structure is considered free memory by\r
+  a legacy OS.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLegacyBootHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_HANDLE  MmHandle;\r
+  EFI_STATUS  Status = EFI_SUCCESS;\r
+\r
+  if (!mInLegacyBoot) {\r
+    MmHandle = NULL;\r
+    Status = MmInstallProtocolInterface (\r
+               &MmHandle,\r
+               &gEfiEventLegacyBootGuid,\r
+               EFI_NATIVE_INTERFACE,\r
+               NULL\r
+               );\r
+  }\r
+  mInLegacyBoot = TRUE;\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Software MMI handler that is called when a ExitBoot Service event is signaled.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmExitBootServiceHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_HANDLE  MmHandle;\r
+  EFI_STATUS  Status = EFI_SUCCESS;\r
+  STATIC BOOLEAN mInExitBootServices = FALSE;\r
+\r
+  if (!mInExitBootServices) {\r
+    MmHandle = NULL;\r
+    Status = MmInstallProtocolInterface (\r
+               &MmHandle,\r
+               &gEfiEventExitBootServicesGuid,\r
+               EFI_NATIVE_INTERFACE,\r
+               NULL\r
+               );\r
+  }\r
+  mInExitBootServices = TRUE;\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Software MMI handler that is called when a ExitBoot Service event is signaled.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmReadyToBootHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_HANDLE  MmHandle;\r
+  EFI_STATUS  Status = EFI_SUCCESS;\r
+  STATIC BOOLEAN mInReadyToBoot = FALSE;\r
+\r
+  if (!mInReadyToBoot) {\r
+    MmHandle = NULL;\r
+    Status = MmInstallProtocolInterface (\r
+               &MmHandle,\r
+               &gEfiEventReadyToBootGuid,\r
+               EFI_NATIVE_INTERFACE,\r
+               NULL\r
+               );\r
+  }\r
+  mInReadyToBoot = TRUE;\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Software MMI handler that is called when the DxeMmReadyToLock protocol is added\r
+  or if gEfiEventReadyToBootGuid is signaled.  This function unregisters the\r
+  Software SMIs that are nor required after MMRAM is locked and installs the\r
+  MM Ready To Lock Protocol so MM Drivers are informed that MMRAM is about\r
+  to be locked.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmReadyToLockHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+  UINTN       Index;\r
+  EFI_HANDLE  MmHandle;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmReadyToLockHandler\n"));\r
+\r
+  //\r
+  // Unregister MMI Handlers that are no longer required after the MM driver dispatch is stopped\r
+  //\r
+  for (Index = 0; mMmCoreMmiHandlers[Index].HandlerType != NULL; Index++) {\r
+    if (mMmCoreMmiHandlers[Index].UnRegister) {\r
+      MmiHandlerUnRegister (mMmCoreMmiHandlers[Index].DispatchHandle);\r
+    }\r
+  }\r
+\r
+  //\r
+  // Install MM Ready to lock protocol\r
+  //\r
+  MmHandle = NULL;\r
+  Status = MmInstallProtocolInterface (\r
+             &MmHandle,\r
+             &gEfiMmReadyToLockProtocolGuid,\r
+             EFI_NATIVE_INTERFACE,\r
+             NULL\r
+             );\r
+\r
+  //\r
+  // Make sure MM CPU I/O 2 Protocol has been installed into the handle database\r
+  //\r
+  //Status = MmLocateProtocol (&EFI_MM_CPU_IO_PROTOCOL_GUID, NULL, &Interface);\r
+\r
+  //\r
+  // Print a message on a debug build if the MM CPU I/O 2 Protocol is not installed\r
+  //\r
+  //if (EFI_ERROR (Status)) {\r
+      //DEBUG ((DEBUG_ERROR, "\nSMM: SmmCpuIo Arch Protocol not present!!\n"));\r
+  //}\r
+\r
+\r
+  //\r
+  // Assert if the CPU I/O 2 Protocol is not installed\r
+  //\r
+  //ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Display any drivers that were not dispatched because dependency expression\r
+  // evaluated to false if this is a debug build\r
+  //\r
+  //MmDisplayDiscoveredNotDispatched ();\r
+\r
+  return Status;\r
+}\r
+\r
+/**\r
+  Software MMI handler that is called when the EndOfDxe event is signaled.\r
+  This function installs the MM EndOfDxe Protocol so MM Drivers are informed that\r
+  platform code will invoke 3rd part code.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmEndOfDxeHandler (\r
+  IN     EFI_HANDLE  DispatchHandle,\r
+  IN     CONST VOID  *Context,        OPTIONAL\r
+  IN OUT VOID        *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN       *CommBufferSize  OPTIONAL\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+  EFI_HANDLE  MmHandle;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmEndOfDxeHandler\n"));\r
+  //\r
+  // Install MM EndOfDxe protocol\r
+  //\r
+  MmHandle = NULL;\r
+  Status = MmInstallProtocolInterface (\r
+             &MmHandle,\r
+             &gEfiMmEndOfDxeProtocolGuid,\r
+             EFI_NATIVE_INTERFACE,\r
+             NULL\r
+             );\r
+  return Status;\r
+}\r
+\r
+\r
+\r
+/**\r
+  The main entry point to MM Foundation.\r
+\r
+  Note: This function is only used by MMRAM invocation.  It is never used by DXE invocation.\r
+\r
+  @param  MmEntryContext           Processor information and functionality\r
+                                    needed by MM Foundation.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+MmEntryPoint (\r
+  IN CONST EFI_MM_ENTRY_CONTEXT  *MmEntryContext\r
+)\r
+{\r
+  EFI_STATUS                  Status;\r
+  EFI_MM_COMMUNICATE_HEADER  *CommunicateHeader;\r
+  BOOLEAN                     InLegacyBoot;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmEntryPoint ...\n"));\r
+\r
+  //\r
+  // Update MMST using the context\r
+  //\r
+  CopyMem (&gMmCoreMmst.MmStartupThisAp, MmEntryContext, sizeof (EFI_MM_ENTRY_CONTEXT));\r
+\r
+  //\r
+  // Call platform hook before Mm Dispatch\r
+  //\r
+  //PlatformHookBeforeMmDispatch ();\r
+\r
+  //\r
+  // If a legacy boot has occured, then make sure gMmCorePrivate is not accessed\r
+  //\r
+  InLegacyBoot = mInLegacyBoot;\r
+  if (!InLegacyBoot) {\r
+    //\r
+    // TBD: Mark the InMm flag as TRUE\r
+    //\r
+    gMmCorePrivate->InMm = TRUE;\r
+\r
+    //\r
+    // Check to see if this is a Synchronous MMI sent through the MM Communication\r
+    // Protocol or an Asynchronous MMI\r
+    //\r
+    if (gMmCorePrivate->CommunicationBuffer != 0) {\r
+      //\r
+      // Synchronous MMI for MM Core or request from Communicate protocol\r
+      //\r
+      if (!MmIsBufferOutsideMmValid ((UINTN)gMmCorePrivate->CommunicationBuffer, gMmCorePrivate->BufferSize)) {\r
+        //\r
+        // If CommunicationBuffer is not in valid address scope, return EFI_INVALID_PARAMETER\r
+        //\r
+        gMmCorePrivate->CommunicationBuffer = 0;\r
+        gMmCorePrivate->ReturnStatus = EFI_INVALID_PARAMETER;\r
+      } else {\r
+        CommunicateHeader = (EFI_MM_COMMUNICATE_HEADER *)(UINTN)gMmCorePrivate->CommunicationBuffer;\r
+        gMmCorePrivate->BufferSize -= OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data);\r
+        Status = MmiManage (\r
+                   &CommunicateHeader->HeaderGuid,\r
+                   NULL,\r
+                   CommunicateHeader->Data,\r
+                   (UINTN *)&gMmCorePrivate->BufferSize\r
+                   );\r
+        //\r
+        // Update CommunicationBuffer, BufferSize and ReturnStatus\r
+        // Communicate service finished, reset the pointer to CommBuffer to NULL\r
+        //\r
+        gMmCorePrivate->BufferSize += OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data);\r
+        gMmCorePrivate->CommunicationBuffer = 0;\r
+        gMmCorePrivate->ReturnStatus = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Process Asynchronous MMI sources\r
+  //\r
+  MmiManage (NULL, NULL, NULL, NULL);\r
+\r
+  //\r
+  // TBD: Do not use private data structure ?\r
+  //\r
+\r
+  //\r
+  // If a legacy boot has occured, then make sure gMmCorePrivate is not accessed\r
+  //\r
+  if (!InLegacyBoot) {\r
+    //\r
+    // Clear the InMm flag as we are going to leave MM\r
+    //\r
+    gMmCorePrivate->InMm = FALSE;\r
+  }\r
+\r
+  DEBUG ((DEBUG_INFO, "MmEntryPoint Done\n"));\r
+}\r
+\r
+EFI_STATUS\r
+EFIAPI\r
+MmConfigurationMmNotify (\r
+  IN CONST EFI_GUID *Protocol,\r
+  IN VOID           *Interface,\r
+  IN EFI_HANDLE      Handle\r
+  )\r
+{\r
+  EFI_STATUS                      Status;\r
+  EFI_MM_CONFIGURATION_PROTOCOL  *MmConfiguration;\r
+\r
+  DEBUG ((DEBUG_INFO, "MmConfigurationMmNotify(%g) - %x\n", Protocol, Interface));\r
+\r
+  MmConfiguration = Interface;\r
+\r
+  //\r
+  // Register the MM Entry Point provided by the MM Core with the MM COnfiguration protocol\r
+  //\r
+  Status = MmConfiguration->RegisterMmEntry (MmConfiguration, (EFI_MM_ENTRY_POINT)(UINTN)gMmCorePrivate->MmEntryPoint);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Set flag to indicate that the MM Entry Point has been registered which\r
+  // means that MMIs are now fully operational.\r
+  //\r
+  gMmCorePrivate->MmEntryPointRegistered = TRUE;\r
+\r
+  //\r
+  // Print debug message showing MM Core entry point address.\r
+  //\r
+  DEBUG ((DEBUG_INFO, "MM Core registered MM Entry Point address %p\n", (VOID *)(UINTN)gMmCorePrivate->MmEntryPoint));\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+UINTN\r
+GetHobListSize (\r
+  IN VOID *HobStart\r
+  )\r
+{\r
+  EFI_PEI_HOB_POINTERS  Hob;\r
+\r
+  ASSERT (HobStart != NULL);\r
+\r
+  Hob.Raw = (UINT8 *) HobStart;\r
+  while (!END_OF_HOB_LIST (Hob)) {\r
+    Hob.Raw = GET_NEXT_HOB (Hob);\r
+  }\r
+  //\r
+  // Need plus END_OF_HOB_LIST\r
+  //\r
+  return (UINTN)Hob.Raw - (UINTN)HobStart + sizeof (EFI_HOB_GENERIC_HEADER);\r
+}\r
+\r
+/**\r
+  The Entry Point for MM Core\r
+\r
+  Install DXE Protocols and reload MM Core into MMRAM and register MM Core\r
+  EntryPoint on the MMI vector.\r
+\r
+  Note: This function is called for both DXE invocation and MMRAM invocation.\r
+\r
+  @param  ImageHandle    The firmware allocated handle for the EFI image.\r
+  @param  SystemTable    A pointer to the EFI System Table.\r
+\r
+  @retval EFI_SUCCESS    The entry point is executed successfully.\r
+  @retval Other          Some error occurred when executing this entry point.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+StandaloneMmMain (\r
+  IN VOID  *HobStart\r
+  )\r
+{\r
+  EFI_STATUS                      Status;\r
+  UINTN                           Index;\r
+  VOID                            *MmHobStart;\r
+  UINTN                           HobSize;\r
+  VOID                            *Registration;\r
+  EFI_HOB_GUID_TYPE               *GuidHob;\r
+  MM_CORE_DATA_HOB_DATA           *DataInHob;\r
+  EFI_HOB_GUID_TYPE               *MmramRangesHob;\r
+  EFI_MMRAM_HOB_DESCRIPTOR_BLOCK  *MmramRangesHobData;\r
+  EFI_MMRAM_DESCRIPTOR            *MmramRanges;\r
+  UINT32                          MmramRangeCount;\r
+  EFI_HOB_FIRMWARE_VOLUME         *BfvHob;\r
+\r
+  ProcessLibraryConstructorList (HobStart, &gMmCoreMmst);\r
+\r
+  DEBUG ((DEBUG_INFO, "MmMain - 0x%x\n", HobStart));\r
+\r
+  //\r
+  // Determine if the caller has passed a reference to a MM_CORE_PRIVATE_DATA\r
+  // structure in the Hoblist. This choice will govern how boot information is\r
+  // extracted later.\r
+  //\r
+  GuidHob = GetNextGuidHob (&gMmCoreDataHobGuid, HobStart);\r
+  if (GuidHob == NULL) {\r
+    //\r
+    // Allocate and zero memory for a MM_CORE_PRIVATE_DATA table and then\r
+    // initialise it\r
+    //\r
+    gMmCorePrivate = (MM_CORE_PRIVATE_DATA *) AllocateRuntimePages(EFI_SIZE_TO_PAGES(sizeof (MM_CORE_PRIVATE_DATA)));\r
+    SetMem ((VOID *)(UINTN)gMmCorePrivate, sizeof (MM_CORE_PRIVATE_DATA), 0);\r
+    gMmCorePrivate->Signature = MM_CORE_PRIVATE_DATA_SIGNATURE;\r
+    gMmCorePrivate->MmEntryPointRegistered = FALSE;\r
+    gMmCorePrivate->InMm = FALSE;\r
+    gMmCorePrivate->ReturnStatus = EFI_SUCCESS;\r
+\r
+    //\r
+    // Extract the MMRAM ranges from the MMRAM descriptor HOB\r
+    //\r
+    MmramRangesHob = GetNextGuidHob (&gEfiMmPeiMmramMemoryReserveGuid, HobStart);\r
+    if (MmramRangesHob == NULL)\r
+      return EFI_UNSUPPORTED;\r
+\r
+    MmramRangesHobData = GET_GUID_HOB_DATA (MmramRangesHob);\r
+    ASSERT (MmramRangesHobData != NULL);\r
+    MmramRanges = MmramRangesHobData->Descriptor;\r
+    MmramRangeCount = MmramRangesHobData->NumberOfMmReservedRegions;\r
+    ASSERT (MmramRanges);\r
+    ASSERT (MmramRangeCount);\r
+\r
+    //\r
+    // Copy the MMRAM ranges into MM_CORE_PRIVATE_DATA table just in case any\r
+    // code relies on them being present there\r
+    //\r
+    gMmCorePrivate->MmramRangeCount = MmramRangeCount;\r
+    gMmCorePrivate->MmramRanges =\r
+      (EFI_PHYSICAL_ADDRESS)(UINTN)AllocatePool (MmramRangeCount * sizeof (EFI_MMRAM_DESCRIPTOR));\r
+    ASSERT (gMmCorePrivate->MmramRanges != 0);\r
+    CopyMem (\r
+      (VOID *)(UINTN)gMmCorePrivate->MmramRanges,\r
+      MmramRanges,\r
+      MmramRangeCount * sizeof (EFI_MMRAM_DESCRIPTOR)\r
+      );\r
+  } else {\r
+    DataInHob       = GET_GUID_HOB_DATA (GuidHob);\r
+    gMmCorePrivate = (MM_CORE_PRIVATE_DATA *)(UINTN)DataInHob->Address;\r
+    MmramRanges     = (EFI_MMRAM_DESCRIPTOR *)(UINTN)gMmCorePrivate->MmramRanges;\r
+    MmramRangeCount = gMmCorePrivate->MmramRangeCount;\r
+  }\r
+\r
+  //\r
+  // Print the MMRAM ranges passed by the caller\r
+  //\r
+  DEBUG ((DEBUG_INFO, "MmramRangeCount - 0x%x\n", MmramRangeCount));\r
+  for (Index = 0; Index < MmramRangeCount; Index++) {\r
+          DEBUG ((DEBUG_INFO, "MmramRanges[%d]: 0x%016lx - 0x%lx\n", Index,\r
+                  MmramRanges[Index].CpuStart,\r
+                  MmramRanges[Index].PhysicalSize));\r
+  }\r
+\r
+  //\r
+  // Copy the MMRAM ranges into private MMRAM\r
+  //\r
+  mMmramRangeCount = MmramRangeCount;\r
+  DEBUG ((DEBUG_INFO, "mMmramRangeCount - 0x%x\n", mMmramRangeCount));\r
+  mMmramRanges = AllocatePool (mMmramRangeCount * sizeof (EFI_MMRAM_DESCRIPTOR));\r
+  DEBUG ((DEBUG_INFO, "mMmramRanges - 0x%x\n", mMmramRanges));\r
+  ASSERT (mMmramRanges != NULL);\r
+  CopyMem (mMmramRanges, (VOID *)(UINTN)MmramRanges, mMmramRangeCount * sizeof (EFI_MMRAM_DESCRIPTOR));\r
+\r
+  //\r
+  // Get Boot Firmware Volume address from the BFV Hob\r
+  //\r
+  BfvHob = GetFirstHob (EFI_HOB_TYPE_FV);\r
+  if (BfvHob != NULL) {\r
+    DEBUG ((DEBUG_INFO, "BFV address - 0x%x\n", BfvHob->BaseAddress));\r
+    DEBUG ((DEBUG_INFO, "BFV size    - 0x%x\n", BfvHob->Length));\r
+    gMmCorePrivate->StandaloneBfvAddress = BfvHob->BaseAddress;\r
+  }\r
+\r
+  gMmCorePrivate->Mmst          = (EFI_PHYSICAL_ADDRESS)(UINTN)&gMmCoreMmst;\r
+  gMmCorePrivate->MmEntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)MmEntryPoint;\r
+\r
+  //\r
+  // No need to initialize memory service.\r
+  // It is done in constructor of StandaloneMmCoreMemoryAllocationLib(),\r
+  // so that the library linked with StandaloneMmCore can use AllocatePool() in constuctor.\r
+  //\r
+\r
+  DEBUG ((DEBUG_INFO, "MmInstallConfigurationTable For HobList\n"));\r
+  //\r
+  // Install HobList\r
+  //\r
+  HobSize = GetHobListSize (HobStart);\r
+  DEBUG ((DEBUG_INFO, "HobSize - 0x%x\n", HobSize));\r
+  MmHobStart = AllocatePool (HobSize);\r
+  DEBUG ((DEBUG_INFO, "MmHobStart - 0x%x\n", MmHobStart));\r
+  ASSERT (MmHobStart != NULL);\r
+  CopyMem (MmHobStart, HobStart, HobSize);\r
+  Status = MmInstallConfigurationTable (&gMmCoreMmst, &gEfiHobListGuid, MmHobStart, HobSize);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Register notification for EFI_MM_CONFIGURATION_PROTOCOL registration and\r
+  // use it to register the MM Foundation entrypoint\r
+  //\r
+  DEBUG ((DEBUG_INFO, "MmRegisterProtocolNotify - MmConfigurationMmProtocol\n"));\r
+  Status = MmRegisterProtocolNotify (\r
+             &gEfiMmConfigurationProtocolGuid,\r
+             MmConfigurationMmNotify,\r
+             &Registration\r
+             );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Dispatch standalone BFV\r
+  //\r
+  DEBUG ((DEBUG_INFO, "Mm Dispatch StandaloneBfvAddress - 0x%08x\n", gMmCorePrivate->StandaloneBfvAddress));\r
+  if (gMmCorePrivate->StandaloneBfvAddress != 0) {\r
+    MmCoreFfsFindMmDriver ((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)gMmCorePrivate->StandaloneBfvAddress);\r
+    MmDispatcher ();\r
+  }\r
+\r
+  //\r
+  // Register all handlers in the core table\r
+  //\r
+  for (Index = 0; mMmCoreMmiHandlers[Index].HandlerType != NULL; Index++) {\r
+    Status = MmiHandlerRegister (\r
+               mMmCoreMmiHandlers[Index].Handler,\r
+               mMmCoreMmiHandlers[Index].HandlerType,\r
+               &mMmCoreMmiHandlers[Index].DispatchHandle\r
+               );\r
+    DEBUG ((DEBUG_INFO, "MmiHandlerRegister - GUID %g - Status %d\n", mMmCoreMmiHandlers[Index].HandlerType, Status));\r
+  }\r
+\r
+  DEBUG ((DEBUG_INFO, "MmMain Done!\n"));\r
+\r
+  return EFI_SUCCESS;\r
+}\r
diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.h b/StandaloneMmPkg/Core/StandaloneMmCore.h
new file mode 100644 (file)
index 0000000..0d20bca
--- /dev/null
@@ -0,0 +1,903 @@
+/** @file\r
+  The internal header file includes the common header files, defines\r
+  internal structure and functions used by MmCore module.\r
+\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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
+#ifndef _MM_CORE_H_\r
+#define _MM_CORE_H_\r
+\r
+#include <PiMm.h>\r
+#include <StandaloneMm.h>\r
+\r
+#include <Protocol/DxeMmReadyToLock.h>\r
+#include <Protocol/MmReadyToLock.h>\r
+#include <Protocol/MmEndOfDxe.h>\r
+#include <Protocol/MmCommunication.h>\r
+#include <Protocol/LoadedImage.h>\r
+#include <Protocol/MmConfiguration.h>\r
+\r
+#include <Guid/Apriori.h>\r
+#include <Guid/EventGroup.h>\r
+#include <Guid/EventLegacyBios.h>\r
+#include <Guid/ZeroGuid.h>\r
+#include <Guid/MemoryProfile.h>\r
+#include <Guid/HobList.h>\r
+#include <Guid/MmFvDispatch.h>\r
+#include <Guid/MmramMemoryReserve.h>\r
+\r
+#include <Library/StandaloneMmCoreEntryPoint.h>\r
+#include <Library/BaseLib.h>\r
+#include <Library/BaseMemoryLib.h>\r
+#include <Library/PeCoffLib.h>\r
+#include <Library/CacheMaintenanceLib.h>\r
+#include <Library/DebugLib.h>\r
+#include <Library/ReportStatusCodeLib.h>\r
+#include <Library/MemoryAllocationLib.h>\r
+#include <Library/PcdLib.h>\r
+\r
+#include <Library/StandaloneMmMemLib.h>\r
+#include <Library/HobLib.h>\r
+\r
+#include "StandaloneMmCorePrivateData.h"\r
+\r
+//\r
+// Used to build a table of MMI Handlers that the MM Core registers\r
+//\r
+typedef struct {\r
+  EFI_MM_HANDLER_ENTRY_POINT    Handler;\r
+  EFI_GUID                      *HandlerType;\r
+  EFI_HANDLE                    DispatchHandle;\r
+  BOOLEAN                       UnRegister;\r
+} MM_CORE_MMI_HANDLERS;\r
+\r
+//\r
+// Structure for recording the state of an MM Driver\r
+//\r
+#define EFI_MM_DRIVER_ENTRY_SIGNATURE SIGNATURE_32('s', '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
+  VOID                            *Pe32Data;\r
+  UINTN                           Pe32DataSize;\r
+\r
+  VOID                            *Depex;\r
+  UINTN                           DepexSize;\r
+\r
+  BOOLEAN                         Before;\r
+  BOOLEAN                         After;\r
+  EFI_GUID                        BeforeAfterGuid;\r
+\r
+  BOOLEAN                         Dependent;\r
+  BOOLEAN                         Scheduled;\r
+  BOOLEAN                         Initialized;\r
+  BOOLEAN                         DepexProtocolError;\r
+\r
+  EFI_HANDLE                      ImageHandle;\r
+  EFI_LOADED_IMAGE_PROTOCOL       *LoadedImage;\r
+  //\r
+  // Image EntryPoint in MMRAM\r
+  //\r
+  PHYSICAL_ADDRESS                ImageEntryPoint;\r
+  //\r
+  // Image Buffer in MMRAM\r
+  //\r
+  PHYSICAL_ADDRESS                ImageBuffer;\r
+  //\r
+  // Image Page Number\r
+  //\r
+  UINTN                           NumberOfPage;\r
+} EFI_MM_DRIVER_ENTRY;\r
+\r
+#define EFI_HANDLE_SIGNATURE            SIGNATURE_32('h','n','d','l')\r
+\r
+///\r
+/// IHANDLE - contains a list of protocol handles\r
+///\r
+typedef struct {\r
+  UINTN               Signature;\r
+  /// All handles list of IHANDLE\r
+  LIST_ENTRY          AllHandles;\r
+  /// List of PROTOCOL_INTERFACE's for this handle\r
+  LIST_ENTRY          Protocols;\r
+  UINTN               LocateRequest;\r
+} IHANDLE;\r
+\r
+#define ASSERT_IS_HANDLE(a)  ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE)\r
+\r
+#define PROTOCOL_ENTRY_SIGNATURE        SIGNATURE_32('p','r','t','e')\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
+typedef struct {\r
+  UINTN               Signature;\r
+  /// Link Entry inserted to mProtocolDatabase\r
+  LIST_ENTRY          AllEntries;\r
+  /// ID of the protocol\r
+  EFI_GUID            ProtocolID;\r
+  /// All protocol interfaces\r
+  LIST_ENTRY          Protocols;\r
+  /// Registerd notification handlers\r
+  LIST_ENTRY          Notify;\r
+} PROTOCOL_ENTRY;\r
+\r
+#define PROTOCOL_INTERFACE_SIGNATURE  SIGNATURE_32('p','i','f','c')\r
+\r
+///\r
+/// PROTOCOL_INTERFACE - each protocol installed on a handle is tracked\r
+/// with a protocol interface structure\r
+///\r
+typedef struct {\r
+  UINTN                       Signature;\r
+  /// Link on IHANDLE.Protocols\r
+  LIST_ENTRY                  Link;\r
+  /// Back pointer\r
+  IHANDLE                     *Handle;\r
+  /// Link on PROTOCOL_ENTRY.Protocols\r
+  LIST_ENTRY                  ByProtocol;\r
+  /// The protocol ID\r
+  PROTOCOL_ENTRY              *Protocol;\r
+  /// The interface value\r
+  VOID                        *Interface;\r
+} PROTOCOL_INTERFACE;\r
+\r
+#define PROTOCOL_NOTIFY_SIGNATURE       SIGNATURE_32('p','r','t','n')\r
+\r
+///\r
+/// PROTOCOL_NOTIFY - used for each register notification for a protocol\r
+///\r
+typedef struct {\r
+  UINTN               Signature;\r
+  PROTOCOL_ENTRY      *Protocol;\r
+  /// All notifications for this protocol\r
+  LIST_ENTRY          Link;\r
+  /// Notification function\r
+  EFI_MM_NOTIFY_FN   Function;\r
+  /// Last position notified\r
+  LIST_ENTRY          *Position;\r
+} PROTOCOL_NOTIFY;\r
+\r
+//\r
+// MM Core Global Variables\r
+//\r
+extern MM_CORE_PRIVATE_DATA  *gMmCorePrivate;\r
+extern EFI_MM_SYSTEM_TABLE   gMmCoreMmst;\r
+extern LIST_ENTRY            gHandleList;\r
+extern EFI_PHYSICAL_ADDRESS  gLoadModuleAtFixAddressMmramBase;\r
+\r
+/**\r
+  Called to initialize the memory service.\r
+\r
+  @param   MmramRangeCount       Number of MMRAM Regions\r
+  @param   MmramRanges           Pointer to MMRAM Descriptors\r
+\r
+**/\r
+VOID\r
+MmInitializeMemoryServices (\r
+  IN UINTN                 MmramRangeCount,\r
+  IN EFI_MMRAM_DESCRIPTOR  *MmramRanges\r
+  );\r
+\r
+/**\r
+  The MmInstallConfigurationTable() function is used to maintain the list\r
+  of configuration tables that are stored in the System Management System\r
+  Table.  The list is stored as an array of (GUID, Pointer) pairs.  The list\r
+  must be allocated from pool memory with PoolType set to EfiRuntimeServicesData.\r
+\r
+  @param  SystemTable      A pointer to the MM System Table (SMST).\r
+  @param  Guid             A pointer to the GUID for the entry to add, update, or remove.\r
+  @param  Table            A pointer to the buffer of the table to add.\r
+  @param  TableSize        The size of the table to install.\r
+\r
+  @retval EFI_SUCCESS           The (Guid, Table) pair was added, updated, or removed.\r
+  @retval EFI_INVALID_PARAMETER Guid is not valid.\r
+  @retval EFI_NOT_FOUND         An attempt was made to delete a non-existent entry.\r
+  @retval EFI_OUT_OF_RESOURCES  There is not enough memory available to complete the operation.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInstallConfigurationTable (\r
+  IN  CONST EFI_MM_SYSTEM_TABLE  *SystemTable,\r
+  IN  CONST EFI_GUID              *Guid,\r
+  IN  VOID                        *Table,\r
+  IN  UINTN                       TableSize\r
+  );\r
+\r
+/**\r
+  Wrapper function to MmInstallProtocolInterfaceNotify.  This is the public API which\r
+  Calls the private one which contains a BOOLEAN parameter for notifications\r
+\r
+  @param  UserHandle             The handle to install the protocol handler on,\r
+                                 or NULL if a new handle is to be allocated\r
+  @param  Protocol               The protocol to add to the handle\r
+  @param  InterfaceType          Indicates whether Interface is supplied in\r
+                                 native form.\r
+  @param  Interface              The interface for the protocol being added\r
+\r
+  @return Status code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInstallProtocolInterface (\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
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into\r
+  @param  NumberOfPages          The number of pages to allocate\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address\r
+\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmAllocatePages (\r
+  IN      EFI_ALLOCATE_TYPE         Type,\r
+  IN      EFI_MEMORY_TYPE           MemoryType,\r
+  IN      UINTN                     NumberOfPages,\r
+  OUT     EFI_PHYSICAL_ADDRESS      *Memory\r
+  );\r
+\r
+/**\r
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into\r
+  @param  NumberOfPages          The number of pages to allocate\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address\r
+\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalAllocatePages (\r
+  IN      EFI_ALLOCATE_TYPE         Type,\r
+  IN      EFI_MEMORY_TYPE           MemoryType,\r
+  IN      UINTN                     NumberOfPages,\r
+  OUT     EFI_PHYSICAL_ADDRESS      *Memory\r
+  );\r
+\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param  Memory                 Base address of memory being freed\r
+  @param  NumberOfPages          The number of pages to free\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFreePages (\r
+  IN      EFI_PHYSICAL_ADDRESS      Memory,\r
+  IN      UINTN                     NumberOfPages\r
+  );\r
+\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param  Memory                 Base address of memory being freed\r
+  @param  NumberOfPages          The number of pages to free\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalFreePages (\r
+  IN      EFI_PHYSICAL_ADDRESS      Memory,\r
+  IN      UINTN                     NumberOfPages\r
+  );\r
+\r
+/**\r
+  Allocate pool of a particular type.\r
+\r
+  @param  PoolType               Type of pool to allocate\r
+  @param  Size                   The amount of pool to allocate\r
+  @param  Buffer                 The address to return a pointer to the allocated\r
+                                 pool\r
+\r
+  @retval EFI_INVALID_PARAMETER  PoolType not valid\r
+  @retval EFI_OUT_OF_RESOURCES   Size exceeds max pool size or allocation failed.\r
+  @retval EFI_SUCCESS            Pool successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmAllocatePool (\r
+  IN      EFI_MEMORY_TYPE           PoolType,\r
+  IN      UINTN                     Size,\r
+  OUT     VOID                      **Buffer\r
+  );\r
+\r
+/**\r
+  Allocate pool of a particular type.\r
+\r
+  @param  PoolType               Type of pool to allocate\r
+  @param  Size                   The amount of pool to allocate\r
+  @param  Buffer                 The address to return a pointer to the allocated\r
+                                 pool\r
+\r
+  @retval EFI_INVALID_PARAMETER  PoolType not valid\r
+  @retval EFI_OUT_OF_RESOURCES   Size exceeds max pool size or allocation failed.\r
+  @retval EFI_SUCCESS            Pool successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalAllocatePool (\r
+  IN      EFI_MEMORY_TYPE           PoolType,\r
+  IN      UINTN                     Size,\r
+  OUT     VOID                      **Buffer\r
+  );\r
+\r
+/**\r
+  Frees pool.\r
+\r
+  @param  Buffer                 The allocated pool entry to free\r
+\r
+  @retval EFI_INVALID_PARAMETER  Buffer is not a valid value.\r
+  @retval EFI_SUCCESS            Pool successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFreePool (\r
+  IN      VOID                      *Buffer\r
+  );\r
+\r
+/**\r
+  Frees pool.\r
+\r
+  @param  Buffer                 The allocated pool entry to free\r
+\r
+  @retval EFI_INVALID_PARAMETER  Buffer is not a valid value.\r
+  @retval EFI_SUCCESS            Pool successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmInternalFreePool (\r
+  IN      VOID                      *Buffer\r
+  );\r
+\r
+/**\r
+  Installs a protocol interface into the boot services environment.\r
+\r
+  @param  UserHandle             The handle to install the protocol handler on,\r
+                                 or NULL if a new handle is to be allocated\r
+  @param  Protocol               The protocol to add to the handle\r
+  @param  InterfaceType          Indicates whether Interface is supplied in\r
+                                 native form.\r
+  @param  Interface              The interface for the protocol being added\r
+  @param  Notify                 indicates whether notify the notification list\r
+                                 for this protocol\r
+\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_OUT_OF_RESOURCES   No enough buffer to allocate\r
+  @retval EFI_SUCCESS            Protocol interface successfully installed\r
+\r
+**/\r
+EFI_STATUS\r
+MmInstallProtocolInterfaceNotify (\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
+  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
+  @param  UserHandle             The handle to remove the protocol handler from\r
+  @param  Protocol               The protocol, of protocol:interface, to remove\r
+  @param  Interface              The interface, of protocol:interface, to remove\r
+\r
+  @retval EFI_INVALID_PARAMETER  Protocol is NULL.\r
+  @retval EFI_SUCCESS            Protocol interface successfully uninstalled.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmUninstallProtocolInterface (\r
+  IN EFI_HANDLE       UserHandle,\r
+  IN EFI_GUID         *Protocol,\r
+  IN VOID             *Interface\r
+  );\r
+\r
+/**\r
+  Queries a handle to determine if it supports a specified protocol.\r
+\r
+  @param  UserHandle             The handle being queried.\r
+  @param  Protocol               The published unique identifier of the protocol.\r
+  @param  Interface              Supplies the address where a pointer to the\r
+                                 corresponding Protocol Interface is returned.\r
+\r
+  @return The requested protocol interface for the handle\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmHandleProtocol (\r
+  IN EFI_HANDLE       UserHandle,\r
+  IN EFI_GUID         *Protocol,\r
+  OUT VOID            **Interface\r
+  );\r
+\r
+/**\r
+  Add a new protocol notification record for the request protocol.\r
+\r
+  @param  Protocol               The requested protocol to add the notify\r
+                                 registration\r
+  @param  Function               Points to the notification function\r
+  @param  Registration           Returns the registration record\r
+\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_SUCCESS            Successfully returned the registration record\r
+                                 that has been added\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmRegisterProtocolNotify (\r
+  IN  CONST EFI_GUID              *Protocol,\r
+  IN  EFI_MM_NOTIFY_FN           Function,\r
+  OUT VOID                        **Registration\r
+  );\r
+\r
+/**\r
+  Locates the requested handle(s) and returns them in Buffer.\r
+\r
+  @param  SearchType             The type of search to perform to locate the\r
+                                 handles\r
+  @param  Protocol               The protocol to search for\r
+  @param  SearchKey              Dependant on SearchType\r
+  @param  BufferSize             On input the size of Buffer.  On output the\r
+                                 size of data returned.\r
+  @param  Buffer                 The buffer to return the results in\r
+\r
+  @retval EFI_BUFFER_TOO_SMALL   Buffer too small, required buffer size is\r
+                                 returned in BufferSize.\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_SUCCESS            Successfully found the requested handle(s) and\r
+                                 returns them in Buffer.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLocateHandle (\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
+  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
+  @param  Protocol               The protocol to search for\r
+  @param  Registration           Optional Registration Key returned from\r
+                                 RegisterProtocolNotify()\r
+  @param  Interface              Return the Protocol interface (instance).\r
+\r
+  @retval EFI_SUCCESS            If a valid Interface is returned\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_NOT_FOUND          Protocol interface not found\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLocateProtocol (\r
+  IN  EFI_GUID  *Protocol,\r
+  IN  VOID      *Registration OPTIONAL,\r
+  OUT VOID      **Interface\r
+  );\r
+\r
+/**\r
+  Manage MMI of a particular type.\r
+\r
+  @param  HandlerType    Points to the handler type or NULL for root MMI handlers.\r
+  @param  Context        Points to an optional context buffer.\r
+  @param  CommBuffer     Points to the optional communication buffer.\r
+  @param  CommBufferSize Points to the size of the optional communication buffer.\r
+\r
+  @retval EFI_SUCCESS                        Interrupt source was processed successfully but not quiesced.\r
+  @retval EFI_INTERRUPT_PENDING              One or more MMI sources could not be quiesced.\r
+  @retval EFI_WARN_INTERRUPT_SOURCE_PENDING  Interrupt source was not handled or quiesced.\r
+  @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED Interrupt source was handled and quiesced.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiManage (\r
+  IN     CONST EFI_GUID           *HandlerType,\r
+  IN     CONST VOID               *Context         OPTIONAL,\r
+  IN OUT VOID                     *CommBuffer      OPTIONAL,\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  Registers a handler to execute within MM.\r
+\r
+  @param  Handler        Handler service funtion pointer.\r
+  @param  HandlerType    Points to the handler type or NULL for root MMI handlers.\r
+  @param  DispatchHandle On return, contains a unique handle which can be used to later unregister the handler function.\r
+\r
+  @retval EFI_SUCCESS           Handler register success.\r
+  @retval EFI_INVALID_PARAMETER Handler or DispatchHandle is NULL.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiHandlerRegister (\r
+  IN   EFI_MM_HANDLER_ENTRY_POINT     Handler,\r
+  IN   CONST EFI_GUID                 *HandlerType  OPTIONAL,\r
+  OUT  EFI_HANDLE                     *DispatchHandle\r
+  );\r
+\r
+/**\r
+  Unregister a handler in MM.\r
+\r
+  @param  DispatchHandle  The handle that was specified when the handler was registered.\r
+\r
+  @retval EFI_SUCCESS           Handler function was successfully unregistered.\r
+  @retval EFI_INVALID_PARAMETER DispatchHandle does not refer to a valid handle.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmiHandlerUnRegister (\r
+  IN  EFI_HANDLE                      DispatchHandle\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmDriverDispatchHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmFvDispatchHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmLegacyBootHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmExitBootServiceHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmReadyToBootHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmReadyToLockHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  This function is the main entry point for an MM handler dispatch\r
+  or communicate-based callback.\r
+\r
+  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().\r
+  @param  Context         Points to an optional handler context which was specified when the handler was registered.\r
+  @param  CommBuffer      A pointer to a collection of data in memory that will\r
+                          be conveyed from a non-MM environment into an MM environment.\r
+  @param  CommBufferSize  The size of the CommBuffer.\r
+\r
+  @return Status Code\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmEndOfDxeHandler (\r
+  IN     EFI_HANDLE               DispatchHandle,\r
+  IN     CONST VOID               *Context,        OPTIONAL\r
+  IN OUT VOID                     *CommBuffer,     OPTIONAL\r
+  IN OUT UINTN                    *CommBufferSize  OPTIONAL\r
+  );\r
+\r
+/**\r
+  Place holder function until all the MM System Table Service are available.\r
+\r
+  @param  Arg1                   Undefined\r
+  @param  Arg2                   Undefined\r
+  @param  Arg3                   Undefined\r
+  @param  Arg4                   Undefined\r
+  @param  Arg5                   Undefined\r
+\r
+  @return EFI_NOT_AVAILABLE_YET\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+MmEfiNotAvailableYetArg5 (\r
+  UINTN Arg1,\r
+  UINTN Arg2,\r
+  UINTN Arg3,\r
+  UINTN Arg4,\r
+  UINTN Arg5\r
+  );\r
+\r
+//\r
+//Functions used during debug buils\r
+//\r
+\r
+/**\r
+  Traverse the discovered list for any drivers that were discovered but not loaded\r
+  because the dependency expressions evaluated to false.\r
+\r
+**/\r
+VOID\r
+MmDisplayDiscoveredNotDispatched (\r
+  VOID\r
+  );\r
+\r
+/**\r
+  Add free MMRAM region for use by memory service.\r
+\r
+  @param  MemBase                Base address of memory region.\r
+  @param  MemLength              Length of the memory region.\r
+  @param  Type                   Memory type.\r
+  @param  Attributes             Memory region state.\r
+\r
+**/\r
+VOID\r
+MmAddMemoryRegion (\r
+  IN      EFI_PHYSICAL_ADDRESS      MemBase,\r
+  IN      UINT64                    MemLength,\r
+  IN      EFI_MEMORY_TYPE           Type,\r
+  IN      UINT64                    Attributes\r
+  );\r
+\r
+/**\r
+  Finds the protocol entry for the requested protocol.\r
+\r
+  @param  Protocol               The ID of the protocol\r
+  @param  Create                 Create a new entry if not found\r
+\r
+  @return Protocol entry\r
+\r
+**/\r
+PROTOCOL_ENTRY  *\r
+MmFindProtocolEntry (\r
+  IN EFI_GUID   *Protocol,\r
+  IN BOOLEAN    Create\r
+  );\r
+\r
+/**\r
+  Signal event for every protocol in protocol entry.\r
+\r
+  @param  Prot                   Protocol interface\r
+\r
+**/\r
+VOID\r
+MmNotifyProtocol (\r
+  IN PROTOCOL_INTERFACE   *Prot\r
+  );\r
+\r
+/**\r
+  Finds the protocol instance for the requested handle and protocol.\r
+  Note: This function doesn't do parameters checking, it's caller's responsibility\r
+  to pass in valid parameters.\r
+\r
+  @param  Handle                 The handle to search the protocol on\r
+  @param  Protocol               GUID of the protocol\r
+  @param  Interface              The interface for the protocol being searched\r
+\r
+  @return Protocol instance (NULL: Not found)\r
+\r
+**/\r
+PROTOCOL_INTERFACE *\r
+MmFindProtocolInterface (\r
+  IN IHANDLE        *Handle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *Interface\r
+  );\r
+\r
+/**\r
+  Removes Protocol from the protocol list (but not the handle list).\r
+\r
+  @param  Handle                 The handle to remove protocol on.\r
+  @param  Protocol               GUID of the protocol to be moved\r
+  @param  Interface              The interface of the protocol\r
+\r
+  @return Protocol Entry\r
+\r
+**/\r
+PROTOCOL_INTERFACE *\r
+MmRemoveInterfaceFromProtocol (\r
+  IN IHANDLE        *Handle,\r
+  IN EFI_GUID       *Protocol,\r
+  IN VOID           *Interface\r
+  );\r
+\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. POSTFIX means all the math is done on top of the stack.\r
+\r
+  @param  DriverEntry           DriverEntry element to update.\r
+\r
+  @retval TRUE                  If driver is ready to run.\r
+  @retval FALSE                 If driver is not ready to run or some fatal error\r
+                                was found.\r
+\r
+**/\r
+BOOLEAN\r
+MmIsSchedulable (\r
+  IN  EFI_MM_DRIVER_ENTRY   *DriverEntry\r
+  );\r
+\r
+/**\r
+  Dump MMRAM information.\r
+\r
+**/\r
+VOID\r
+DumpMmramInfo (\r
+  VOID\r
+  );\r
+\r
+extern UINTN                    mMmramRangeCount;\r
+extern EFI_MMRAM_DESCRIPTOR     *mMmramRanges;\r
+extern EFI_SYSTEM_TABLE         *mEfiSystemTable;\r
+\r
+#endif\r
diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.inf b/StandaloneMmPkg/Core/StandaloneMmCore.inf
new file mode 100644 (file)
index 0000000..ff2b8b9
--- /dev/null
@@ -0,0 +1,80 @@
+## @file\r
+# This module provide an SMM CIS compliant implementation of SMM Core.\r
+#\r
+# Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+#\r
+# 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
+# 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
+[Defines]\r
+  INF_VERSION                    = 0x0001001A\r
+  BASE_NAME                      = StandaloneMmCore\r
+  FILE_GUID                      = 6E14B6FD-3600-4DD6-A17A-206B3B6DCE16\r
+  MODULE_TYPE                    = MM_CORE_STANDALONE\r
+  VERSION_STRING                 = 1.0\r
+  PI_SPECIFICATION_VERSION       = 0x00010032\r
+  ENTRY_POINT                    = StandaloneMmMain\r
+\r
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64\r
+\r
+[Sources]\r
+  StandaloneMmCore.c\r
+  StandaloneMmCore.h\r
+  StandaloneMmCorePrivateData.h\r
+  Page.c\r
+  Pool.c\r
+  Handle.c\r
+  Locate.c\r
+  Notify.c\r
+  Dependency.c\r
+  Dispatcher.c\r
+  Mmi.c\r
+  InstallConfigurationTable.c\r
+  FwVol.c\r
+\r
+[Packages]\r
+  MdePkg/MdePkg.dec\r
+  MdeModulePkg/MdeModulePkg.dec\r
+  StandaloneMmPkg/StandaloneMmPkg.dec\r
+\r
+[LibraryClasses]\r
+  BaseLib\r
+  BaseMemoryLib\r
+  CacheMaintenanceLib\r
+  DebugLib\r
+  FvLib\r
+  HobLib\r
+  MemoryAllocationLib\r
+  MemLib\r
+  PeCoffLib\r
+  ReportStatusCodeLib\r
+  StandaloneMmCoreEntryPoint\r
+\r
+[Protocols]\r
+  gEfiDxeMmReadyToLockProtocolGuid             ## UNDEFINED # SmiHandlerRegister\r
+  gEfiMmReadyToLockProtocolGuid                ## PRODUCES\r
+  gEfiMmEndOfDxeProtocolGuid                   ## PRODUCES\r
+  gEfiLoadedImageProtocolGuid                   ## PRODUCES\r
+  gEfiMmConfigurationProtocolGuid               ## CONSUMES\r
+\r
+[Guids]\r
+  gAprioriGuid                                  ## SOMETIMES_CONSUMES   ## File\r
+  gEfiEventDxeDispatchGuid                      ## PRODUCES             ## GUID # SmiHandlerRegister\r
+  gEfiEndOfDxeEventGroupGuid                    ## PRODUCES             ## GUID # SmiHandlerRegister\r
+  ## SOMETIMES_CONSUMES   ## GUID # Locate protocol\r
+  ## SOMETIMES_PRODUCES   ## GUID # SmiHandlerRegister\r
+  gEdkiiMemoryProfileGuid\r
+  gZeroGuid                                     ## SOMETIMES_CONSUMES   ## GUID\r
+  gEfiHobListGuid\r
+  gMmCoreDataHobGuid\r
+  gMmFvDispatchGuid\r
+  gEfiEventLegacyBootGuid\r
+  gEfiEventExitBootServicesGuid\r
+  gEfiEventReadyToBootGuid\r
diff --git a/StandaloneMmPkg/Core/StandaloneMmCorePrivateData.h b/StandaloneMmPkg/Core/StandaloneMmCorePrivateData.h
new file mode 100644 (file)
index 0000000..d959893
--- /dev/null
@@ -0,0 +1,66 @@
+/** @file\r
+  The internal header file that declared a data structure that is shared\r
+  between the MM IPL and the MM Core.\r
+\r
+  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+  This program and the accompanying materials are licensed and made available\r
+  under the terms and conditions of the BSD License which accompanies this\r
+  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
+#ifndef _STANDALONE_MM_CORE_PRIVATE_DATA_H_\r
+#define _STANDALONE_MM_CORE_PRIVATE_DATA_H_\r
+\r
+#include <Guid/MmCoreData.h>\r
+\r
+//\r
+// Page management\r
+//\r
+\r
+typedef struct {\r
+  LIST_ENTRY  Link;\r
+  UINTN       NumberOfPages;\r
+} FREE_PAGE_LIST;\r
+\r
+extern LIST_ENTRY  mMmMemoryMap;\r
+\r
+//\r
+// Pool management\r
+//\r
+\r
+//\r
+// MIN_POOL_SHIFT must not be less than 5\r
+//\r
+#define MIN_POOL_SHIFT  6\r
+#define MIN_POOL_SIZE   (1 << MIN_POOL_SHIFT)\r
+\r
+//\r
+// MAX_POOL_SHIFT must not be less than EFI_PAGE_SHIFT - 1\r
+//\r
+#define MAX_POOL_SHIFT  (EFI_PAGE_SHIFT - 1)\r
+#define MAX_POOL_SIZE   (1 << MAX_POOL_SHIFT)\r
+\r
+//\r
+// MAX_POOL_INDEX are calculated by maximum and minimum pool sizes\r
+//\r
+#define MAX_POOL_INDEX  (MAX_POOL_SHIFT - MIN_POOL_SHIFT + 1)\r
+\r
+typedef struct {\r
+  UINTN        Size;\r
+  BOOLEAN      Available;\r
+} POOL_HEADER;\r
+\r
+typedef struct {\r
+  POOL_HEADER  Header;\r
+  LIST_ENTRY   Link;\r
+} FREE_POOL_HEADER;\r
+\r
+extern LIST_ENTRY  mMmPoolLists[MAX_POOL_INDEX];\r
+\r
+#endif\r
diff --git a/StandaloneMmPkg/Include/Guid/MmFvDispatch.h b/StandaloneMmPkg/Include/Guid/MmFvDispatch.h
new file mode 100644 (file)
index 0000000..d141d40
--- /dev/null
@@ -0,0 +1,39 @@
+/** @file\r
+  GUIDs for MM Event.\r
+\r
+Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+\r
+This program and the accompanying materials are licensed and made available under\r
+the terms and conditions of the BSD License that accompanies this distribution.\r
+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
+#ifndef __MM_FV_DISPATCH_H__\r
+#define __MM_FV_DISPATCH_H__\r
+\r
+#define MM_FV_DISPATCH_GUID \\r
+  { 0xb65694cc, 0x9e3, 0x4c3b, { 0xb5, 0xcd, 0x5, 0xf4, 0x4d, 0x3c, 0xdb, 0xff }}\r
+\r
+extern EFI_GUID gMmFvDispatchGuid;\r
+\r
+#pragma pack(1)\r
+\r
+typedef struct {\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+  UINT64                Size;\r
+} EFI_MM_COMMUNICATE_FV_DISPATCH_DATA;\r
+\r
+typedef struct {\r
+  EFI_GUID                              HeaderGuid;\r
+  UINTN                                 MessageLength;\r
+  EFI_MM_COMMUNICATE_FV_DISPATCH_DATA   Data;\r
+} EFI_MM_COMMUNICATE_FV_DISPATCH;\r
+#pragma pack()\r
+\r
+#endif\r
diff --git a/StandaloneMmPkg/Include/Library/StandaloneMmCoreEntryPoint.h b/StandaloneMmPkg/Include/Library/StandaloneMmCoreEntryPoint.h
new file mode 100644 (file)
index 0000000..f53094b
--- /dev/null
@@ -0,0 +1,101 @@
+/** @file\r
+  Module entry point library for STANDALONE MM core.\r
+\r
+Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+\r
+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
+#ifndef __MODULE_ENTRY_POINT_H__\r
+#define __MODULE_ENTRY_POINT_H__\r
+\r
+///\r
+/// Global variable that contains a pointer to the Hob List passed into the STANDALONE MM Core entry point.\r
+///\r
+extern VOID  *gHobList;\r
+\r
+\r
+/**\r
+  The entry point of PE/COFF Image for the STANDALONE MM Core.\r
+\r
+  This function is the entry point for the STANDALONE MM Core. This function is required to call\r
+  ProcessModuleEntryPointList() and ProcessModuleEntryPointList() is never expected to return.\r
+  The STANDALONE MM Core is responsible for calling ProcessLibraryConstructorList() as soon as the EFI\r
+  System Table and the image handle for the STANDALONE MM Core itself have been established.\r
+  If ProcessModuleEntryPointList() returns, then ASSERT() and halt the system.\r
+\r
+  @param  HobStart  Pointer to the beginning of the HOB List passed in from the PEI Phase.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+_ModuleEntryPoint (\r
+  IN VOID  *HobStart\r
+  );\r
+\r
+\r
+/**\r
+  Required by the EBC compiler and identical in functionality to _ModuleEntryPoint().\r
+\r
+  This function is required to call _ModuleEntryPoint() passing in HobStart.\r
+\r
+  @param  HobStart  Pointer to the beginning of the HOB List passed in from the PEI Phase.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+EfiMain (\r
+  IN VOID  *HobStart\r
+  );\r
+\r
+\r
+/**\r
+  Auto generated function that calls the library constructors for all of the module's dependent libraries.\r
+\r
+  This function must be called by _ModuleEntryPoint().\r
+  This function calls the set of library constructors for the set of library instances\r
+  that a module depends on.  This includes library instances that a module depends on\r
+  directly and library instances that a module depends on indirectly through other\r
+  libraries. This function is auto generated by build tools and those build tools are\r
+  responsible for collecting the set of library instances, determine which ones have\r
+  constructors, and calling the library constructors in the proper order based upon\r
+  each of the library instances own dependencies.\r
+\r
+  @param  ImageHandle  The image handle of the STANDALONE MM Core.\r
+  @param  SystemTable  A pointer to the EFI System Table.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+ProcessLibraryConstructorList (\r
+  IN EFI_HANDLE             ImageHandle,\r
+  IN EFI_MM_SYSTEM_TABLE    *MmSystemTable\r
+  );\r
+\r
+\r
+/**\r
+  Autogenerated function that calls a set of module entry points.\r
+\r
+  This function must be called by _ModuleEntryPoint().\r
+  This function calls the set of module entry points.\r
+  This function is auto generated by build tools and those build tools are responsible\r
+  for collecting the module entry points and calling them in a specified order.\r
+\r
+  @param  HobStart  Pointer to the beginning of the HOB List passed in from the PEI Phase.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+ProcessModuleEntryPointList (\r
+  IN VOID  *HobStart\r
+  );\r
+\r
+#endif\r
diff --git a/StandaloneMmPkg/Include/StandaloneMm.h b/StandaloneMmPkg/Include/StandaloneMm.h
new file mode 100644 (file)
index 0000000..2517d41
--- /dev/null
@@ -0,0 +1,36 @@
+/** @file\r
+  Standalone MM.\r
+\r
+Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>\r
+\r
+This program and the accompanying materials\r
+are licensed and made available under the terms and conditions\r
+of the BSD License which accompanies this distribution.  The\r
+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
+#ifndef _STANDALONE_MM_H_\r
+#define _STANDALONE_MM_H_\r
+\r
+#include <PiMm.h>\r
+\r
+typedef\r
+EFI_STATUS\r
+(EFIAPI *MM_IMAGE_ENTRY_POINT) (\r
+  IN EFI_HANDLE            ImageHandle,\r
+  IN EFI_MM_SYSTEM_TABLE   *MmSystemTable\r
+  );\r
+\r
+typedef\r
+EFI_STATUS\r
+(EFIAPI *STANDALONE_MM_FOUNDATION_ENTRY_POINT) (\r
+  IN VOID  *HobStart\r
+  );\r
+\r
+#endif\r