summaryrefslogtreecommitdiffstats
path: root/StandaloneMmPkg/Core/StandaloneMmCore.c
blob: 5a3694b58c933276d70e3ecb6707f2089102cf83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/** @file
  MM Core Main Entry Point

  Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
  Copyright (c) 2016 - 2021, Arm Limited. All rights reserved.<BR>
  SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "StandaloneMmCore.h"

EFI_STATUS
MmDispatcher (
  VOID
  );

//
// Globals used to initialize the protocol
//
EFI_HANDLE  mMmCpuHandle = NULL;

//
// MM Core global variable for MM System Table.  Only accessed as a physical structure in MMRAM.
//
EFI_MM_SYSTEM_TABLE  gMmCoreMmst = {
  // The table header for the MMST.
  {
    MM_MMST_SIGNATURE,
    EFI_MM_SYSTEM_TABLE_REVISION,
    sizeof (gMmCoreMmst.Hdr)
  },
  // MmFirmwareVendor
  NULL,
  // MmFirmwareRevision
  0,
  // MmInstallConfigurationTable
  MmInstallConfigurationTable,
  // I/O Service
  {
    {
      (EFI_MM_CPU_IO)MmEfiNotAvailableYetArg5,        // MmMemRead
      (EFI_MM_CPU_IO)MmEfiNotAvailableYetArg5         // MmMemWrite
    },
    {
      (EFI_MM_CPU_IO)MmEfiNotAvailableYetArg5,        // MmIoRead
      (EFI_MM_CPU_IO)MmEfiNotAvailableYetArg5         // MmIoWrite
    }
  },
  // Runtime memory services
  MmAllocatePool,
  MmFreePool,
  MmAllocatePages,
  MmFreePages,
  // MP service
  NULL,                          // MmStartupThisAp
  0,                             // CurrentlyExecutingCpu
  0,                             // NumberOfCpus
  NULL,                          // CpuSaveStateSize
  NULL,                          // CpuSaveState
  0,                             // NumberOfTableEntries
  NULL,                          // MmConfigurationTable
  MmInstallProtocolInterface,
  MmUninstallProtocolInterface,
  MmHandleProtocol,
  MmRegisterProtocolNotify,
  MmLocateHandle,
  MmLocateProtocol,
  MmiManage,
  MmiHandlerRegister,
  MmiHandlerUnRegister
};

//
// Table of MMI Handlers that are registered by the MM Core when it is initialized
//
MM_CORE_MMI_HANDLERS  mMmCoreMmiHandlers[] = {
  { MmDriverDispatchHandler,  &gEventMmDispatchGuid,             NULL, FALSE },
  { MmReadyToLockHandler,     &gEfiDxeMmReadyToLockProtocolGuid, NULL, TRUE  },
  { MmEndOfPeiHandler,        &gEfiMmEndOfPeiProtocol,           NULL, FALSE },
  { MmEndOfDxeHandler,        &gEfiEndOfDxeEventGroupGuid,       NULL, FALSE },
  { MmExitBootServiceHandler, &gEfiEventExitBootServicesGuid,    NULL, FALSE },
  { MmReadyToBootHandler,     &gEfiEventReadyToBootGuid,         NULL, FALSE },
  { NULL,                     NULL,                              NULL, FALSE },
};

BOOLEAN                     mMmEntryPointRegistered = FALSE;
MM_COMM_BUFFER              *mMmCommunicationBuffer;
VOID                        *mInternalCommBufferCopy;
EFI_FIRMWARE_VOLUME_HEADER  *mBfv = NULL;

/**
  Place holder function until all the MM System Table Service are available.

  Note: This function is only used by MMRAM invocation.  It is never used by DXE invocation.

  @param  Arg1                   Undefined
  @param  Arg2                   Undefined
  @param  Arg3                   Undefined
  @param  Arg4                   Undefined
  @param  Arg5                   Undefined

  @return EFI_NOT_AVAILABLE_YET

**/
EFI_STATUS
EFIAPI
MmEfiNotAvailableYetArg5 (
  UINTN  Arg1,
  UINTN  Arg2,
  UINTN  Arg3,
  UINTN  Arg4,
  UINTN  Arg5
  )
{
  //
  // This function should never be executed.  If it does, then the architectural protocols
  // have not been designed correctly.
  //
  return EFI_NOT_AVAILABLE_YET;
}

/**
  Software MMI handler that is called when a ExitBoot Service event is signaled.

  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().
  @param  Context         Points to an optional handler context which was specified when the handler was registered.
  @param  CommBuffer      A pointer to a collection of data in memory that will
                          be conveyed from a non-MM environment into an MM environment.
  @param  CommBufferSize  The size of the CommBuffer.

  @return Status Code

**/
EFI_STATUS
EFIAPI
MmExitBootServiceHandler (
  IN     EFI_HANDLE  DispatchHandle,
  IN     CONST VOID  *Context         OPTIONAL,
  IN OUT VOID        *CommBuffer      OPTIONAL,
  IN OUT UINTN       *CommBufferSize  OPTIONAL
  )
{
  EFI_HANDLE      MmHandle;
  EFI_STATUS      Status;
  STATIC BOOLEAN  mInExitBootServices = FALSE;

  Status = EFI_SUCCESS;
  if (!mInExitBootServices) {
    MmHandle = NULL;
    Status   = MmInstallProtocolInterface (
                 &MmHandle,
                 &gEfiEventExitBootServicesGuid,
                 EFI_NATIVE_INTERFACE,
                 NULL
                 );
  }

  mInExitBootServices = TRUE;
  return Status;
}

/**
  Software MMI handler that is called when a ExitBoot Service event is signaled.

  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().
  @param  Context         Points to an optional handler context which was specified when the handler was registered.
  @param  CommBuffer      A pointer to a collection of data in memory that will
                          be conveyed from a non-MM environment into an MM environment.
  @param  CommBufferSize  The size of the CommBuffer.

  @return Status Code

**/
EFI_STATUS
EFIAPI
MmReadyToBootHandler (
  IN     EFI_HANDLE  DispatchHandle,
  IN     CONST VOID  *Context         OPTIONAL,
  IN OUT VOID        *CommBuffer      OPTIONAL,
  IN OUT UINTN       *CommBufferSize  OPTIONAL
  )
{
  EFI_HANDLE      MmHandle;
  EFI_STATUS      Status;
  STATIC BOOLEAN  mInReadyToBoot = FALSE;

  Status = EFI_SUCCESS;
  if (!mInReadyToBoot) {
    MmHandle = NULL;
    Status   = MmInstallProtocolInterface (
                 &MmHandle,
                 &gEfiEventReadyToBootGuid,
                 EFI_NATIVE_INTERFACE,
                 NULL
                 );
  }

  mInReadyToBoot = TRUE;
  return Status;
}

/**
  Software MMI handler that is called when the DxeMmReadyToLock protocol is added
  or if gEfiEventReadyToBootGuid is signaled.  This function unregisters the
  Software SMIs that are nor required after MMRAM is locked and installs the
  MM Ready To Lock Protocol so MM Drivers are informed that MMRAM is about
  to be locked.

  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().
  @param  Context         Points to an optional handler context which was specified when the handler was registered.
  @param  CommBuffer      A pointer to a collection of data in memory that will
                          be conveyed from a non-MM environment into an MM environment.
  @param  CommBufferSize  The size of the CommBuffer.

  @return Status Code

**/
EFI_STATUS
EFIAPI
MmReadyToLockHandler (
  IN     EFI_HANDLE  DispatchHandle,
  IN     CONST VOID  *Context         OPTIONAL,
  IN OUT VOID        *CommBuffer      OPTIONAL,
  IN OUT UINTN       *CommBufferSize  OPTIONAL
  )
{
  EFI_STATUS  Status;
  UINTN       Index;
  EFI_HANDLE  MmHandle;

  DEBUG ((DEBUG_INFO, "MmReadyToLockHandler\n"));

  //
  // Unregister MMI Handlers that are no longer required after the MM driver dispatch is stopped
  //
  for (Index = 0; mMmCoreMmiHandlers[Index].HandlerType != NULL; Index++) {
    if (mMmCoreMmiHandlers[Index].UnRegister) {
      MmiHandlerUnRegister (mMmCoreMmiHandlers[Index].DispatchHandle);
    }
  }

  //
  // Install MM Ready to lock protocol
  //
  MmHandle = NULL;
  Status   = MmInstallProtocolInterface (
               &MmHandle,
               &gEfiMmReadyToLockProtocolGuid,
               EFI_NATIVE_INTERFACE,
               NULL
               );

  //
  // Make sure MM CPU I/O 2 Protocol has been installed into the handle database
  //
  // Status = MmLocateProtocol (&EFI_MM_CPU_IO_PROTOCOL_GUID, NULL, &Interface);

  //
  // Print a message on a debug build if the MM CPU I/O 2 Protocol is not installed
  //
  // if (EFI_ERROR (Status)) {
  // DEBUG ((DEBUG_ERROR, "\nSMM: SmmCpuIo Arch Protocol not present!!\n"));
  // }

  //
  // Assert if the CPU I/O 2 Protocol is not installed
  //
  // ASSERT_EFI_ERROR (Status);

  //
  // Display any drivers that were not dispatched because dependency expression
  // evaluated to false if this is a debug build
  //
  // MmDisplayDiscoveredNotDispatched ();

  return Status;
}

/**
  Software MMI handler that is called when the EndOfPei event is signaled.
  This function installs the MM EndOfPei Protocol so MM Drivers are informed that
  EndOfPei event is signaled.

  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().
  @param  Context         Points to an optional handler context which was specified when the handler was registered.
  @param  CommBuffer      A pointer to a collection of data in memory that will
                          be conveyed from a non-MM environment into an MM environment.
  @param  CommBufferSize  The size of the CommBuffer.

  @return Status Code

**/
EFI_STATUS
EFIAPI
MmEndOfPeiHandler (
  IN     EFI_HANDLE  DispatchHandle,
  IN     CONST VOID  *Context         OPTIONAL,
  IN OUT VOID        *CommBuffer      OPTIONAL,
  IN OUT UINTN       *CommBufferSize  OPTIONAL
  )
{
  EFI_STATUS  Status;
  EFI_HANDLE  MmHandle;

  DEBUG ((DEBUG_INFO, "MmEndOfPeiHandler\n"));
  //
  // Install MM EndOfDxe protocol
  //
  MmHandle = NULL;
  Status   = MmInstallProtocolInterface (
               &MmHandle,
               &gEfiMmEndOfPeiProtocol,
               EFI_NATIVE_INTERFACE,
               NULL
               );
  return Status;
}

/**
  Software MMI handler that is called when the EndOfDxe event is signaled.
  This function installs the MM EndOfDxe Protocol so MM Drivers are informed that
  platform code will invoke 3rd part code.

  @param  DispatchHandle  The unique handle assigned to this handler by MmiHandlerRegister().
  @param  Context         Points to an optional handler context which was specified when the handler was registered.
  @param  CommBuffer      A pointer to a collection of data in memory that will
                          be conveyed from a non-MM environment into an MM environment.
  @param  CommBufferSize  The size of the CommBuffer.

  @return Status Code

**/
EFI_STATUS
EFIAPI
MmEndOfDxeHandler (
  IN     EFI_HANDLE  DispatchHandle,
  IN     CONST VOID  *Context         OPTIONAL,
  IN OUT VOID        *CommBuffer      OPTIONAL,
  IN OUT UINTN       *CommBufferSize  OPTIONAL
  )
{
  EFI_STATUS  Status;
  EFI_HANDLE  MmHandle;

  DEBUG ((DEBUG_INFO, "MmEndOfDxeHandler\n"));
  //
  // Install MM EndOfDxe protocol
  //
  MmHandle = NULL;
  Status   = MmInstallProtocolInterface (
               &MmHandle,
               &gEfiMmEndOfDxeProtocolGuid,
               EFI_NATIVE_INTERFACE,
               NULL
               );
  return Status;
}

/**
  Install LoadedImage protocol for MM Core.

**/
VOID
MmCoreInstallLoadedImage (
  VOID
  )
{
  EFI_STATUS                 Status;
  EFI_PHYSICAL_ADDRESS       MmCoreImageBaseAddress;
  UINT64                     MmCoreImageLength;
  EFI_PEI_HOB_POINTERS       Hob;
  EFI_LOADED_IMAGE_PROTOCOL  *LoadedImage;
  EFI_HANDLE                 ImageHandle;

  //
  // Searching for Memory Allocation HOB
  //
  Hob.Raw = GetHobList ();
  while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) {
    //
    // Find MM Core HOB
    //
    if (CompareGuid (
          &Hob.MemoryAllocationModule->MemoryAllocationHeader.Name,
          &gEfiHobMemoryAllocModuleGuid
          ))
    {
      if (CompareGuid (&Hob.MemoryAllocationModule->ModuleName, &gEfiCallerIdGuid)) {
        break;
      }
    }

    Hob.Raw = GET_NEXT_HOB (Hob);
  }

  if (Hob.Raw == NULL) {
    return;
  }

  MmCoreImageBaseAddress = Hob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress;
  MmCoreImageLength      = Hob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength;

  //
  // Allocate a Loaded Image Protocol in MM
  //
  LoadedImage = AllocatePool (sizeof (EFI_LOADED_IMAGE_PROTOCOL));
  ASSERT (LoadedImage != NULL);
  if (LoadedImage == NULL) {
    return;
  }

  ZeroMem (LoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL));

  //
  // Fill in the remaining fields of the Loaded Image Protocol instance.
  //
  LoadedImage->Revision     = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
  LoadedImage->ParentHandle = NULL;
  LoadedImage->SystemTable  = NULL;

  LoadedImage->ImageBase     = (VOID *)(UINTN)MmCoreImageBaseAddress;
  LoadedImage->ImageSize     = MmCoreImageLength;
  LoadedImage->ImageCodeType = EfiRuntimeServicesCode;
  LoadedImage->ImageDataType = EfiRuntimeServicesData;

  //
  // Create a new image handle in the MM handle database for the MM Core
  //
  ImageHandle = NULL;
  Status      = MmInstallProtocolInterface (
                  &ImageHandle,
                  &gEfiLoadedImageProtocolGuid,
                  EFI_NATIVE_INTERFACE,
                  LoadedImage
                  );
  ASSERT_EFI_ERROR (Status);
}

/**
  Prepare communication buffer for MMI.
**/
VOID
MmCorePrepareCommunicationBuffer (
  VOID
  )
{
  EFI_STATUS            Status;
  EFI_HOB_GUID_TYPE     *GuidHob;
  EFI_PHYSICAL_ADDRESS  Buffer;

  mMmCommunicationBuffer  = NULL;
  mInternalCommBufferCopy = NULL;

  GuidHob = GetFirstGuidHob (&gMmCommBufferHobGuid);
  ASSERT (GuidHob != NULL);
  if (GuidHob == NULL) {
    return;
  }

  mMmCommunicationBuffer = (MM_COMM_BUFFER *)GET_GUID_HOB_DATA (GuidHob);
  DEBUG ((
    DEBUG_INFO,
    "MM Communication Buffer is at %x, number of pages is %x\n",
    mMmCommunicationBuffer->PhysicalStart,
    mMmCommunicationBuffer->NumberOfPages
    ));
  ASSERT (mMmCommunicationBuffer->PhysicalStart != 0 && mMmCommunicationBuffer->NumberOfPages != 0);

  if (!MmIsBufferOutsideMmValid (
         mMmCommunicationBuffer->PhysicalStart,
         EFI_PAGES_TO_SIZE (mMmCommunicationBuffer->NumberOfPages)
         ))
  {
    mMmCommunicationBuffer = NULL;
    DEBUG ((DEBUG_ERROR, "MM Communication Buffer is invalid!\n"));
    ASSERT (FALSE);
    return;
  }

  Status = MmAllocatePages (
             AllocateAnyPages,
             EfiRuntimeServicesData,
             mMmCommunicationBuffer->NumberOfPages,
             &Buffer
             );
  ASSERT_EFI_ERROR (Status);
  if (EFI_ERROR (Status)) {
    return;
  }

  mInternalCommBufferCopy = (VOID *)(UINTN)Buffer;
  DEBUG ((DEBUG_INFO, "Internal Communication Buffer Copy is at %p\n", mInternalCommBufferCopy));
}

/**
  The main entry point to MM Foundation.

  Note: This function is only used by MMRAM invocation.  It is never used by DXE invocation.

  @param  MmEntryContext           Processor information and functionality
                                    needed by MM Foundation.

**/
VOID
EFIAPI
MmEntryPoint (
  IN CONST EFI_MM_ENTRY_CONTEXT  *MmEntryContext
  )
{
  EFI_STATUS                 Status;
  EFI_MM_COMMUNICATE_HEADER  *CommunicateHeader;
  MM_COMM_BUFFER_STATUS      *CommunicationStatus;
  UINTN                      BufferSize;

  DEBUG ((DEBUG_INFO, "MmEntryPoint ...\n"));

  //
  // Update MMST using the context
  //
  CopyMem (&gMmCoreMmst.MmStartupThisAp, MmEntryContext, sizeof (EFI_MM_ENTRY_CONTEXT));

  //
  // Call platform hook before Mm Dispatch
  //
  // PlatformHookBeforeMmDispatch ();

  //
  // Check to see if this is a Synchronous MMI sent through the MM Communication
  // Protocol or an Asynchronous MMI
  //
  if ((mMmCommunicationBuffer != NULL) && (mInternalCommBufferCopy != NULL)) {
    CommunicationStatus = (MM_COMM_BUFFER_STATUS *)(UINTN)mMmCommunicationBuffer->Status;
    if (CommunicationStatus->IsCommBufferValid) {
      //
      // Synchronous MMI for MM Core or request from Communicate protocol
      //
      CommunicateHeader = (EFI_MM_COMMUNICATE_HEADER *)(UINTN)mMmCommunicationBuffer->PhysicalStart;
      BufferSize        = OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data) + CommunicateHeader->MessageLength;
      if (BufferSize <= EFI_PAGES_TO_SIZE (mMmCommunicationBuffer->NumberOfPages)) {
        //
        // Shadow the data from MM Communication Buffer to internal buffer
        //
        CopyMem (
          mInternalCommBufferCopy,
          (VOID *)(UINTN)mMmCommunicationBuffer->PhysicalStart,
          BufferSize
          );
        ZeroMem (
          (UINT8 *)mInternalCommBufferCopy + BufferSize,
          EFI_PAGES_TO_SIZE (mMmCommunicationBuffer->NumberOfPages) - BufferSize
          );

        CommunicateHeader = (EFI_MM_COMMUNICATE_HEADER *)mInternalCommBufferCopy;
        BufferSize        = CommunicateHeader->MessageLength;
        Status            = MmiManage (
                              &CommunicateHeader->HeaderGuid,
                              NULL,
                              CommunicateHeader->Data,
                              &BufferSize
                              );

        BufferSize = BufferSize + OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data);
        if (BufferSize <= EFI_PAGES_TO_SIZE (mMmCommunicationBuffer->NumberOfPages)) {
          //
          // Copy the data back to MM Communication Buffer
          //
          CopyMem (
            (VOID *)(UINTN)mMmCommunicationBuffer->PhysicalStart,
            mInternalCommBufferCopy,
            BufferSize
            );
        } else {
          DEBUG ((DEBUG_ERROR, "Returned buffer size is larger than the size of MM Communication Buffer\n"));
          ASSERT (FALSE);
        }

        //
        // Update ReturnBufferSize and ReturnStatus
        // Communicate service finished, reset IsCommBufferValid to FALSE
        //
        CommunicationStatus->IsCommBufferValid = FALSE;
        CommunicationStatus->ReturnBufferSize  = BufferSize;
        CommunicationStatus->ReturnStatus      = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND;
      } else {
        DEBUG ((DEBUG_ERROR, "Input buffer size is larger than the size of MM Communication Buffer\n"));
        ASSERT (FALSE);
      }
    }
  } else {
    DEBUG ((DEBUG_ERROR, "No valid communication buffer, no Synchronous MMI will be processed\n"));
  }

  //
  // Process Asynchronous MMI sources
  //
  MmiManage (NULL, NULL, NULL, NULL);

  //
  // TBD: Do not use private data structure ?
  //

  DEBUG ((DEBUG_INFO, "MmEntryPoint Done\n"));
}

/** Register the MM Entry Point provided by the MM Core with the
    MM Configuration protocol.

  @param [in]  Protocol   Pointer to the protocol.
  @param [in]  Interface  Pointer to the MM Configuration protocol.
  @param [in]  Handle     Handle.

  @retval EFI_SUCCESS             Success.
**/
EFI_STATUS
EFIAPI
MmConfigurationMmNotify (
  IN CONST EFI_GUID  *Protocol,
  IN VOID            *Interface,
  IN EFI_HANDLE      Handle
  )
{
  EFI_STATUS                     Status;
  EFI_MM_CONFIGURATION_PROTOCOL  *MmConfiguration;

  DEBUG ((DEBUG_INFO, "MmConfigurationMmNotify(%g) - %x\n", Protocol, Interface));

  MmConfiguration = Interface;

  //
  // Register the MM Entry Point provided by the MM Core with the MM COnfiguration protocol
  //
  Status = MmConfiguration->RegisterMmEntry (MmConfiguration, (EFI_MM_ENTRY_POINT)MmEntryPoint);
  ASSERT_EFI_ERROR (Status);

  //
  // Set flag to indicate that the MM Entry Point has been registered which
  // means that MMIs are now fully operational.
  //
  mMmEntryPointRegistered = TRUE;

  //
  // Print debug message showing MM Core entry point address.
  //
  DEBUG ((DEBUG_INFO, "MM Core registered MM Entry Point address %p\n", MmEntryPoint));
  return EFI_SUCCESS;
}

/**
  Migrate MemoryBaseAddress in memory allocation HOBs with BootServiceData
  type and non-zero GUID name from Boot Service memory to MMRAM.

  @param[in]  HobStart       Pointer to the start of the HOB list.

**/
VOID
MigrateMemoryAllocationHobs (
  IN VOID  *HobStart
  )
{
  EFI_PEI_HOB_POINTERS       Hob;
  EFI_HOB_MEMORY_ALLOCATION  *MemoryAllocationHob;
  VOID                       *MemoryInMmram;

  MemoryAllocationHob = NULL;
  Hob.Raw             = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, HobStart);
  while (Hob.Raw != NULL) {
    MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw;
    if (MemoryAllocationHob->AllocDescriptor.MemoryType == EfiBootServicesData) {
      if (!IsZeroGuid (&MemoryAllocationHob->AllocDescriptor.Name)) {
        MemoryInMmram = AllocatePages (EFI_SIZE_TO_PAGES (MemoryAllocationHob->AllocDescriptor.MemoryLength));
        if (MemoryInMmram != NULL) {
          DEBUG ((
            DEBUG_INFO,
            "Migrate Memory Allocation Hob (%g) from %08x to %08p\n",
            &MemoryAllocationHob->AllocDescriptor.Name,
            MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress,
            MemoryInMmram
            ));
          CopyMem (
            MemoryInMmram,
            (VOID *)(UINTN)MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress,
            MemoryAllocationHob->AllocDescriptor.MemoryLength
            );
          MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)MemoryInMmram;
          MemoryAllocationHob->AllocDescriptor.MemoryType        = EfiRuntimeServicesData;
        }
      } else {
        DEBUG ((
          DEBUG_ERROR,
          "Error - Memory Allocation Hob [%08x, %08x] doesn't have a GUID name specified\n",
          MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress,
          MemoryAllocationHob->AllocDescriptor.MemoryLength
          ));
      }
    }

    Hob.Raw = GET_NEXT_HOB (Hob);
    Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw);
  }
}

/** Returns the HOB list size.

  @param [in]  HobStart   Pointer to the start of the HOB list.

  @retval Size of the HOB list.
**/
UINTN
GetHobListSize (
  IN VOID  *HobStart
  )
{
  EFI_PEI_HOB_POINTERS  Hob;

  ASSERT (HobStart != NULL);

  Hob.Raw = (UINT8 *)HobStart;
  while (!END_OF_HOB_LIST (Hob)) {
    Hob.Raw = GET_NEXT_HOB (Hob);
  }

  //
  // Need plus END_OF_HOB_LIST
  //
  return (UINTN)Hob.Raw - (UINTN)HobStart + sizeof (EFI_HOB_GENERIC_HEADER);
}

/**
  The Entry Point for MM Core

  Install DXE Protocols and reload MM Core into MMRAM and register MM Core
  EntryPoint on the MMI vector.

  Note: This function is called for both DXE invocation and MMRAM invocation.

  @param  HobStart       Pointer to the start of the HOB list.

  @retval EFI_SUCCESS             Success.
  @retval EFI_UNSUPPORTED         Unsupported operation.
**/
EFI_STATUS
EFIAPI
StandaloneMmMain (
  IN VOID  *HobStart
  )
{
  EFI_STATUS                      Status;
  UINTN                           Index;
  VOID                            *MmHobStart;
  UINTN                           HobSize;
  VOID                            *Registration;
  EFI_HOB_GUID_TYPE               *MmramRangesHob;
  EFI_MMRAM_HOB_DESCRIPTOR_BLOCK  *MmramRangesHobData;
  EFI_MMRAM_DESCRIPTOR            *MmramRanges;
  UINTN                           MmramRangeCount;
  EFI_HOB_FIRMWARE_VOLUME         *BfvHob;

  ProcessLibraryConstructorList (HobStart, &gMmCoreMmst);

  DEBUG ((DEBUG_INFO, "MmMain - 0x%x\n", HobStart));

  DEBUG_CODE (
    PrintHobList (HobStart, NULL);
    );

  //
  // Extract the MMRAM ranges from the MMRAM descriptor HOB
  //
  MmramRangesHob = GetNextGuidHob (&gEfiSmmSmramMemoryGuid, HobStart);
  if (MmramRangesHob == NULL) {
    MmramRangesHob = GetNextGuidHob (&gEfiMmPeiMmramMemoryReserveGuid, HobStart);
    if (MmramRangesHob == NULL) {
      return EFI_UNSUPPORTED;
    }
  }

  MmramRangesHobData = GET_GUID_HOB_DATA (MmramRangesHob);
  ASSERT (MmramRangesHobData != NULL);
  MmramRanges     = MmramRangesHobData->Descriptor;
  MmramRangeCount = (UINTN)MmramRangesHobData->NumberOfMmReservedRegions;
  ASSERT (MmramRanges);
  ASSERT (MmramRangeCount);

  //
  // Print the MMRAM ranges passed by the caller
  //
  DEBUG ((DEBUG_INFO, "MmramRangeCount - 0x%x\n", MmramRangeCount));
  for (Index = 0; Index < MmramRangeCount; Index++) {
    DEBUG ((
      DEBUG_INFO,
      "MmramRanges[%d]: 0x%016lx - 0x%lx\n",
      Index,
      MmramRanges[Index].CpuStart,
      MmramRanges[Index].PhysicalSize
      ));
  }

  //
  // No need to initialize memory service.
  // It is done in the constructor of StandaloneMmCoreMemoryAllocationLib(),
  // so that the library linked with StandaloneMmCore can use AllocatePool() in
  // the constructor.

  DEBUG ((DEBUG_INFO, "MmInstallConfigurationTable For HobList\n"));
  //
  // Install HobList
  //
  HobSize = GetHobListSize (HobStart);
  DEBUG ((DEBUG_INFO, "HobSize - 0x%x\n", HobSize));
  MmHobStart = AllocatePool (HobSize);
  DEBUG ((DEBUG_INFO, "MmHobStart - 0x%x\n", MmHobStart));
  ASSERT (MmHobStart != NULL);
  CopyMem (MmHobStart, HobStart, HobSize);
  Status = MmInstallConfigurationTable (&gMmCoreMmst, &gEfiHobListGuid, MmHobStart, HobSize);
  ASSERT_EFI_ERROR (Status);
  MigrateMemoryAllocationHobs (MmHobStart);
  gHobList = MmHobStart;

  //
  // Register notification for EFI_MM_CONFIGURATION_PROTOCOL registration and
  // use it to register the MM Foundation entrypoint
  //
  DEBUG ((DEBUG_INFO, "MmRegisterProtocolNotify - MmConfigurationMmProtocol\n"));
  Status = MmRegisterProtocolNotify (
             &gEfiMmConfigurationProtocolGuid,
             MmConfigurationMmNotify,
             &Registration
             );
  ASSERT_EFI_ERROR (Status);

  //
  // Get Boot Firmware Volume address from the BFV Hob
  //
  BfvHob = GetFirstHob (EFI_HOB_TYPE_FV);
  if (BfvHob != NULL) {
    DEBUG ((DEBUG_INFO, "BFV address - 0x%x\n", BfvHob->BaseAddress));
    DEBUG ((DEBUG_INFO, "BFV size    - 0x%x\n", BfvHob->Length));
    //
    // Dispatch standalone BFV
    //
    if (BfvHob->BaseAddress != 0) {
      //
      // Shadow standalone BFV into MMRAM
      //
      mBfv = AllocatePool (BfvHob->Length);
      if (mBfv != NULL) {
        CopyMem ((VOID *)mBfv, (VOID *)(UINTN)BfvHob->BaseAddress, BfvHob->Length);
        DEBUG ((DEBUG_INFO, "Mm Dispatch StandaloneBfvAddress - 0x%08x\n", mBfv));
        MmCoreFfsFindMmDriver (mBfv, 0);
        MmDispatcher ();
        if (!FeaturePcdGet (PcdRestartMmDispatcherOnceMmEntryRegistered)) {
          FreePool (mBfv);
        }
      }
    }
  }

  //
  // Register all handlers in the core table
  //
  for (Index = 0; mMmCoreMmiHandlers[Index].HandlerType != NULL; Index++) {
    Status = MmiHandlerRegister (
               mMmCoreMmiHandlers[Index].Handler,
               mMmCoreMmiHandlers[Index].HandlerType,
               &mMmCoreMmiHandlers[Index].DispatchHandle
               );
    DEBUG ((DEBUG_INFO, "MmiHandlerRegister - GUID %g - Status %d\n", mMmCoreMmiHandlers[Index].HandlerType, Status));
  }

  MmCorePrepareCommunicationBuffer ();

  //
  // Install Loaded Image Protocol form MM Core
  //
  MmCoreInstallLoadedImage ();

  DEBUG ((DEBUG_INFO, "MmMain Done!\n"));

  return EFI_SUCCESS;
}