2 SMM IPL that produces SMM related runtime protocols and load the SMM Core into SMRAM
4 Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials are licensed and made available
6 under the terms and conditions of the BSD License which accompanies this
7 distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17 #include <Protocol/SmmBase2.h>
18 #include <Protocol/SmmCommunication.h>
19 #include <Protocol/SmmAccess2.h>
20 #include <Protocol/SmmConfiguration.h>
21 #include <Protocol/SmmControl2.h>
22 #include <Protocol/DxeSmmReadyToLock.h>
23 #include <Protocol/Cpu.h>
25 #include <Guid/EventGroup.h>
26 #include <Guid/EventLegacyBios.h>
27 #include <Guid/LoadModuleAtFixedAddress.h>
29 #include <Library/BaseLib.h>
30 #include <Library/BaseMemoryLib.h>
31 #include <Library/PeCoffLib.h>
32 #include <Library/CacheMaintenanceLib.h>
33 #include <Library/MemoryAllocationLib.h>
34 #include <Library/DebugLib.h>
35 #include <Library/UefiBootServicesTableLib.h>
36 #include <Library/DxeServicesTableLib.h>
37 #include <Library/DxeServicesLib.h>
38 #include <Library/UefiLib.h>
39 #include <Library/UefiRuntimeLib.h>
40 #include <Library/PcdLib.h>
42 #include "PiSmmCorePrivateData.h"
45 // Function prototypes from produced protocols
49 Indicate whether the driver is currently executing in the SMM Initialization phase.
51 @param This The EFI_SMM_BASE2_PROTOCOL instance.
52 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
53 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
55 @retval EFI_INVALID_PARAMETER InSmram was NULL.
56 @retval EFI_SUCCESS The call returned successfully.
62 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
67 Retrieves the location of the System Management System Table (SMST).
69 @param This The EFI_SMM_BASE2_PROTOCOL instance.
70 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
72 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
73 @retval EFI_SUCCESS The memory was returned to the system.
74 @retval EFI_UNSUPPORTED Not in SMM.
79 SmmBase2GetSmstLocation (
80 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
81 OUT EFI_SMM_SYSTEM_TABLE2
**Smst
85 Communicates with a registered handler.
87 This function provides a service to send and receive messages from a registered
88 UEFI service. This function is part of the SMM Communication Protocol that may
89 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
90 after SetVirtualAddressMap().
92 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
93 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
94 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
95 being returned. Zero if the handler does not wish to reply with any data.
97 @retval EFI_SUCCESS The message was successfully posted.
98 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
102 SmmCommunicationCommunicate (
103 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL
*This
,
104 IN OUT VOID
*CommBuffer
,
105 IN OUT UINTN
*CommSize
109 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
111 @param Event The Event that is being processed, not used.
112 @param Context Event Context, not used.
117 SmmIplSmmConfigurationEventNotify (
123 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
124 or if gEfiEventReadyToBootGuid is signalled.
126 @param Event The Event that is being processed, not used.
127 @param Context Event Context, not used.
132 SmmIplReadyToLockEventNotify (
138 Event notification that is fired when DxeDispatch Event Group is signaled.
140 @param Event The Event that is being processed, not used.
141 @param Context Event Context, not used.
146 SmmIplDxeDispatchEventNotify (
152 Event notification that is fired when a GUIDed Event Group is signaled.
154 @param Event The Event that is being processed, not used.
155 @param Context Event Context, not used.
160 SmmIplGuidedEventNotify (
166 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
168 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
169 It convers pointer to new virtual address.
171 @param Event Event whose notification function is being invoked.
172 @param Context Pointer to the notification function's context.
177 SmmIplSetVirtualAddressNotify (
183 // Data structure used to declare a table of protocol notifications and event
184 // notifications required by the SMM IPL
190 EFI_EVENT_NOTIFY NotifyFunction
;
194 } SMM_IPL_EVENT_NOTIFICATION
;
197 // Handle to install the SMM Base2 Protocol and the SMM Communication Protocol
199 EFI_HANDLE mSmmIplHandle
= NULL
;
202 // SMM Base 2 Protocol instance
204 EFI_SMM_BASE2_PROTOCOL mSmmBase2
= {
206 SmmBase2GetSmstLocation
210 // SMM Communication Protocol instance
212 EFI_SMM_COMMUNICATION_PROTOCOL mSmmCommunication
= {
213 SmmCommunicationCommunicate
217 // SMM Core Private Data structure that contains the data shared between
218 // the SMM IPL and the SMM Core.
220 SMM_CORE_PRIVATE_DATA mSmmCorePrivateData
= {
221 SMM_CORE_PRIVATE_DATA_SIGNATURE
, // Signature
222 NULL
, // SmmIplImageHandle
223 0, // SmramRangeCount
225 NULL
, // SmmEntryPoint
226 FALSE
, // SmmEntryPointRegistered
229 NULL
, // CommunicationBuffer
231 EFI_SUCCESS
// ReturnStatus
235 // Global pointer used to access mSmmCorePrivateData from outside and inside SMM
237 SMM_CORE_PRIVATE_DATA
*gSmmCorePrivate
= &mSmmCorePrivateData
;
240 // SMM IPL global variables
242 EFI_SMM_CONTROL2_PROTOCOL
*mSmmControl2
;
243 EFI_SMM_ACCESS2_PROTOCOL
*mSmmAccess
;
244 EFI_SMRAM_DESCRIPTOR
*mCurrentSmramRange
;
245 BOOLEAN mSmmLocked
= FALSE
;
246 EFI_PHYSICAL_ADDRESS mSmramCacheBase
;
247 UINT64 mSmramCacheSize
;
250 // Table of Protocol notification and GUIDed Event notifications that the SMM IPL requires
252 SMM_IPL_EVENT_NOTIFICATION mSmmIplEvents
[] = {
254 // Declare protocol notification on the SMM Configuration protocol. When this notification is etablished,
255 // the associated event is immediately signalled, so the notification function will be executed and the
256 // SMM Configuration Protocol will be found if it is already in the handle database.
258 { TRUE
, FALSE
, &gEfiSmmConfigurationProtocolGuid
, SmmIplSmmConfigurationEventNotify
, &gEfiSmmConfigurationProtocolGuid
, TPL_NOTIFY
, NULL
},
260 // Declare protocl notification on DxeSmmReadyToLock protocols. When this notification is etablished,
261 // the associated event is immediately signalled, so the notification function will be executed and the
262 // DXE SMM Ready To Lock Protocol will be found if it is already in the handle database.
264 { TRUE
, TRUE
, &gEfiDxeSmmReadyToLockProtocolGuid
, SmmIplReadyToLockEventNotify
, &gEfiDxeSmmReadyToLockProtocolGuid
, TPL_CALLBACK
, NULL
},
266 // Declare event notification on the DXE Dispatch Event Group. This event is signaled by the DXE Core
267 // each time the DXE Core dispatcher has completed its work. When this event is signalled, the SMM Core
268 // if notified, so the SMM Core can dispatch SMM drivers.
270 { FALSE
, TRUE
, &gEfiEventDxeDispatchGuid
, SmmIplDxeDispatchEventNotify
, &gEfiEventDxeDispatchGuid
, TPL_CALLBACK
, NULL
},
272 // Declare event notification on Ready To Boot Event Group. This is an extra event notification that is
273 // used to make sure SMRAM is locked before any boot options are processed.
275 { FALSE
, TRUE
, &gEfiEventReadyToBootGuid
, SmmIplReadyToLockEventNotify
, &gEfiEventReadyToBootGuid
, TPL_CALLBACK
, NULL
},
277 // Declare event notification on Legacy Boot Event Group. This is used to inform the SMM Core that the platform
278 // is performing a legacy boot operation, and that the UEFI environment is no longer available and the SMM Core
279 // must guarantee that it does not access any UEFI related structures outside of SMRAM.
281 { FALSE
, FALSE
, &gEfiEventLegacyBootGuid
, SmmIplGuidedEventNotify
, &gEfiEventLegacyBootGuid
, TPL_CALLBACK
, NULL
},
283 // Declare event notification on SetVirtualAddressMap() Event Group. This is used to convert gSmmCorePrivate
284 // and mSmmControl2 from physical addresses to virtual addresses.
286 { FALSE
, FALSE
, &gEfiEventVirtualAddressChangeGuid
, SmmIplSetVirtualAddressNotify
, NULL
, TPL_CALLBACK
, NULL
},
288 // Terminate the table of event notifications
290 { FALSE
, FALSE
, NULL
, NULL
, NULL
, TPL_CALLBACK
, NULL
}
294 Find the maximum SMRAM cache range that covers the range specified by SmramRange.
296 This function searches and joins all adjacent ranges of SmramRange into a range to be cached.
298 @param SmramRange The SMRAM range to search from.
299 @param SmramCacheBase The returned cache range base.
300 @param SmramCacheSize The returned cache range size.
305 IN EFI_SMRAM_DESCRIPTOR
*SmramRange
,
306 OUT EFI_PHYSICAL_ADDRESS
*SmramCacheBase
,
307 OUT UINT64
*SmramCacheSize
311 EFI_PHYSICAL_ADDRESS RangeCpuStart
;
312 UINT64 RangePhysicalSize
;
313 BOOLEAN FoundAjacentRange
;
315 *SmramCacheBase
= SmramRange
->CpuStart
;
316 *SmramCacheSize
= SmramRange
->PhysicalSize
;
319 FoundAjacentRange
= FALSE
;
320 for (Index
= 0; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
321 RangeCpuStart
= gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
;
322 RangePhysicalSize
= gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
;
323 if (RangeCpuStart
< *SmramCacheBase
&& *SmramCacheBase
== (RangeCpuStart
+ RangePhysicalSize
)) {
324 *SmramCacheBase
= RangeCpuStart
;
325 *SmramCacheSize
+= RangePhysicalSize
;
326 FoundAjacentRange
= TRUE
;
327 } else if ((*SmramCacheBase
+ *SmramCacheSize
) == RangeCpuStart
&& RangePhysicalSize
> 0) {
328 *SmramCacheSize
+= RangePhysicalSize
;
329 FoundAjacentRange
= TRUE
;
332 } while (FoundAjacentRange
);
337 Indicate whether the driver is currently executing in the SMM Initialization phase.
339 @param This The EFI_SMM_BASE2_PROTOCOL instance.
340 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
341 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
343 @retval EFI_INVALID_PARAMETER InSmram was NULL.
344 @retval EFI_SUCCESS The call returned successfully.
350 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
354 if (InSmram
== NULL
) {
355 return EFI_INVALID_PARAMETER
;
358 *InSmram
= gSmmCorePrivate
->InSmm
;
364 Retrieves the location of the System Management System Table (SMST).
366 @param This The EFI_SMM_BASE2_PROTOCOL instance.
367 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
369 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
370 @retval EFI_SUCCESS The memory was returned to the system.
371 @retval EFI_UNSUPPORTED Not in SMM.
376 SmmBase2GetSmstLocation (
377 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
378 OUT EFI_SMM_SYSTEM_TABLE2
**Smst
381 if ((This
== NULL
) ||(Smst
== NULL
)) {
382 return EFI_INVALID_PARAMETER
;
385 if (!gSmmCorePrivate
->InSmm
) {
386 return EFI_UNSUPPORTED
;
389 *Smst
= gSmmCorePrivate
->Smst
;
395 Communicates with a registered handler.
397 This function provides a service to send and receive messages from a registered
398 UEFI service. This function is part of the SMM Communication Protocol that may
399 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
400 after SetVirtualAddressMap().
402 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
403 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
404 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
405 being returned. Zero if the handler does not wish to reply with any data.
407 @retval EFI_SUCCESS The message was successfully posted.
408 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
412 SmmCommunicationCommunicate (
413 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL
*This
,
414 IN OUT VOID
*CommBuffer
,
415 IN OUT UINTN
*CommSize
419 EFI_SMM_COMMUNICATE_HEADER
*CommunicateHeader
;
425 if ((CommBuffer
== NULL
) || (CommSize
== NULL
)) {
426 return EFI_INVALID_PARAMETER
;
430 // CommSize must hold HeaderGuid and MessageLength
432 if (*CommSize
< OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER
, Data
)) {
433 return EFI_INVALID_PARAMETER
;
437 // If not already in SMM, then generate a Software SMI
439 if (!gSmmCorePrivate
->InSmm
&& gSmmCorePrivate
->SmmEntryPointRegistered
) {
441 // Put arguments for Software SMI in gSmmCorePrivate
443 gSmmCorePrivate
->CommunicationBuffer
= CommBuffer
;
444 gSmmCorePrivate
->BufferSize
= *CommSize
;
447 // Generate Software SMI
449 Status
= mSmmControl2
->Trigger (mSmmControl2
, NULL
, NULL
, FALSE
, 0);
450 if (EFI_ERROR (Status
)) {
451 return EFI_UNSUPPORTED
;
455 // Return status from software SMI
457 *CommSize
= gSmmCorePrivate
->BufferSize
;
458 return gSmmCorePrivate
->ReturnStatus
;
462 // If we are in SMM, then the execution mode must be physical, which means that
463 // OS established virtual addresses can not be used. If SetVirtualAddressMap()
464 // has been called, then a direct invocation of the Software SMI is not
465 // not allowed so return EFI_INVALID_PARAMETER.
467 if (EfiGoneVirtual()) {
468 return EFI_INVALID_PARAMETER
;
472 // If we are not in SMM, don't allow call SmiManage() directly when SMRAM is closed or locked.
474 if ((!gSmmCorePrivate
->InSmm
) && (!mSmmAccess
->OpenState
|| mSmmAccess
->LockState
)) {
475 return EFI_INVALID_PARAMETER
;
479 // Save current InSmm state and set InSmm state to TRUE
481 OldInSmm
= gSmmCorePrivate
->InSmm
;
482 gSmmCorePrivate
->InSmm
= TRUE
;
485 // Already in SMM and before SetVirtualAddressMap(), so call SmiManage() directly.
487 CommunicateHeader
= (EFI_SMM_COMMUNICATE_HEADER
*)CommBuffer
;
488 *CommSize
-= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER
, Data
);
489 Status
= gSmmCorePrivate
->Smst
->SmiManage (
490 &CommunicateHeader
->HeaderGuid
,
492 CommunicateHeader
->Data
,
497 // Update CommunicationBuffer, BufferSize and ReturnStatus
498 // Communicate service finished, reset the pointer to CommBuffer to NULL
500 *CommSize
+= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER
, Data
);
503 // Restore original InSmm state
505 gSmmCorePrivate
->InSmm
= OldInSmm
;
507 return (Status
== EFI_WARN_INTERRUPT_SOURCE_QUIESCED
) ? EFI_SUCCESS
: EFI_NOT_FOUND
;
511 Event notification that is fired when GUIDed Event Group is signaled.
513 @param Event The Event that is being processed, not used.
514 @param Context Event Context, not used.
519 SmmIplGuidedEventNotify (
524 EFI_SMM_COMMUNICATE_HEADER CommunicateHeader
;
528 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
530 CopyGuid (&CommunicateHeader
.HeaderGuid
, (EFI_GUID
*)Context
);
531 CommunicateHeader
.MessageLength
= 1;
532 CommunicateHeader
.Data
[0] = 0;
535 // Generate the Software SMI and return the result
537 Size
= sizeof (CommunicateHeader
);
538 SmmCommunicationCommunicate (&mSmmCommunication
, &CommunicateHeader
, &Size
);
542 Event notification that is fired when DxeDispatch Event Group is signaled.
544 @param Event The Event that is being processed, not used.
545 @param Context Event Context, not used.
550 SmmIplDxeDispatchEventNotify (
555 EFI_SMM_COMMUNICATE_HEADER CommunicateHeader
;
560 // Keep calling the SMM Core Dispatcher until there is no request to restart it.
564 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
565 // Clear the buffer passed into the Software SMI. This buffer will return
566 // the status of the SMM Core Dispatcher.
568 CopyGuid (&CommunicateHeader
.HeaderGuid
, (EFI_GUID
*)Context
);
569 CommunicateHeader
.MessageLength
= 1;
570 CommunicateHeader
.Data
[0] = 0;
573 // Generate the Software SMI and return the result
575 Size
= sizeof (CommunicateHeader
);
576 SmmCommunicationCommunicate (&mSmmCommunication
, &CommunicateHeader
, &Size
);
579 // Return if there is no request to restart the SMM Core Dispatcher
581 if (CommunicateHeader
.Data
[0] != COMM_BUFFER_SMM_DISPATCH_RESTART
) {
586 // Attempt to reset SMRAM cacheability to UC
587 // Assume CPU AP is available at this time
589 Status
= gDS
->SetMemorySpaceAttributes(
594 if (EFI_ERROR (Status
)) {
595 DEBUG ((DEBUG_WARN
, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
599 // Close all SMRAM ranges to protect SMRAM
601 Status
= mSmmAccess
->Close (mSmmAccess
);
602 ASSERT_EFI_ERROR (Status
);
605 // Print debug message that the SMRAM window is now closed.
607 DEBUG ((DEBUG_INFO
, "SMM IPL closed SMRAM window\n"));
612 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
614 @param Event The Event that is being processed, not used.
615 @param Context Event Context, not used.
620 SmmIplSmmConfigurationEventNotify (
626 EFI_SMM_CONFIGURATION_PROTOCOL
*SmmConfiguration
;
629 // Make sure this notification is for this handler
631 Status
= gBS
->LocateProtocol (Context
, NULL
, (VOID
**)&SmmConfiguration
);
632 if (EFI_ERROR (Status
)) {
637 // Register the SMM Entry Point provided by the SMM Core with the SMM COnfiguration protocol
639 Status
= SmmConfiguration
->RegisterSmmEntry (SmmConfiguration
, gSmmCorePrivate
->SmmEntryPoint
);
640 ASSERT_EFI_ERROR (Status
);
643 // Set flag to indicate that the SMM Entry Point has been registered which
644 // means that SMIs are now fully operational.
646 gSmmCorePrivate
->SmmEntryPointRegistered
= TRUE
;
649 // Print debug message showing SMM Core entry point address.
651 DEBUG ((DEBUG_INFO
, "SMM IPL registered SMM Entry Point address %p\n", (VOID
*)(UINTN
)gSmmCorePrivate
->SmmEntryPoint
));
655 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
656 or if gEfiEventReadyToBootGuid is signalled.
658 @param Event The Event that is being processed, not used.
659 @param Context Event Context, not used.
664 SmmIplReadyToLockEventNotify (
674 // See if we are already locked
681 // Make sure this notification is for this handler
683 if (CompareGuid ((EFI_GUID
*)Context
, &gEfiDxeSmmReadyToLockProtocolGuid
)) {
684 Status
= gBS
->LocateProtocol (&gEfiDxeSmmReadyToLockProtocolGuid
, NULL
, &Interface
);
685 if (EFI_ERROR (Status
)) {
690 // If SMM is not locked yet and we got here from gEfiEventReadyToBootGuid being
691 // signalled, then gEfiDxeSmmReadyToLockProtocolGuid was not installed as expected.
692 // Print a warning on debug builds.
694 DEBUG ((DEBUG_WARN
, "SMM IPL! DXE SMM Ready To Lock Protocol not installed before Ready To Boot signal\n"));
698 // Lock the SMRAM (Note: Locking SMRAM may not be supported on all platforms)
700 mSmmAccess
->Lock (mSmmAccess
);
703 // Close protocol and event notification events that do not apply after the
704 // DXE SMM Ready To Lock Protocol has been installed or the Ready To Boot
705 // event has been signalled.
707 for (Index
= 0; mSmmIplEvents
[Index
].NotifyFunction
!= NULL
; Index
++) {
708 if (mSmmIplEvents
[Index
].CloseOnLock
) {
709 gBS
->CloseEvent (mSmmIplEvents
[Index
].Event
);
714 // Inform SMM Core that the DxeSmmReadyToLock protocol was installed
716 SmmIplGuidedEventNotify (Event
, (VOID
*)&gEfiDxeSmmReadyToLockProtocolGuid
);
719 // Print debug message that the SMRAM window is now locked.
721 DEBUG ((DEBUG_INFO
, "SMM IPL locked SMRAM window\n"));
724 // Set flag so this operation will not be performed again
730 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
732 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
733 It convers pointer to new virtual address.
735 @param Event Event whose notification function is being invoked.
736 @param Context Pointer to the notification function's context.
741 SmmIplSetVirtualAddressNotify (
746 EfiConvertPointer (0x0, (VOID
**)&mSmmControl2
);
750 Get the fixed loadding address from image header assigned by build tool. This function only be called
751 when Loading module at Fixed address feature enabled.
753 @param ImageContext Pointer to the image context structure that describes the PE/COFF
754 image that needs to be examined by this function.
755 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
756 @retval EFI_NOT_FOUND The image has no assigned fixed loadding address.
759 GetPeCoffImageFixLoadingAssignedAddress(
760 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
763 UINTN SectionHeaderOffset
;
765 EFI_IMAGE_SECTION_HEADER SectionHeader
;
766 EFI_IMAGE_OPTIONAL_HEADER_UNION
*ImgHdr
;
767 EFI_PHYSICAL_ADDRESS FixLoaddingAddress
;
770 UINT16 NumberOfSections
;
771 EFI_PHYSICAL_ADDRESS SmramBase
;
773 UINT64 ValueInSectionHeader
;
775 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
777 SmmCodeSize
= EFI_PAGES_TO_SIZE (PcdGet32(PcdLoadFixAddressSmmCodePageNumber
));
779 FixLoaddingAddress
= 0;
780 Status
= EFI_NOT_FOUND
;
781 SmramBase
= mCurrentSmramRange
->CpuStart
;
783 // Get PeHeader pointer
785 ImgHdr
= (EFI_IMAGE_OPTIONAL_HEADER_UNION
*)((CHAR8
* )ImageContext
->Handle
+ ImageContext
->PeCoffHeaderOffset
);
786 SectionHeaderOffset
= (UINTN
)(
787 ImageContext
->PeCoffHeaderOffset
+
789 sizeof (EFI_IMAGE_FILE_HEADER
) +
790 ImgHdr
->Pe32
.FileHeader
.SizeOfOptionalHeader
792 NumberOfSections
= ImgHdr
->Pe32
.FileHeader
.NumberOfSections
;
795 // Get base address from the first section header that doesn't point to code section.
797 for (Index
= 0; Index
< NumberOfSections
; Index
++) {
799 // Read section header from file
801 Size
= sizeof (EFI_IMAGE_SECTION_HEADER
);
802 Status
= ImageContext
->ImageRead (
803 ImageContext
->Handle
,
808 if (EFI_ERROR (Status
)) {
812 Status
= EFI_NOT_FOUND
;
814 if ((SectionHeader
.Characteristics
& EFI_IMAGE_SCN_CNT_CODE
) == 0) {
816 // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the
817 // first section header that doesn't point to code section in image header. And there is an assumption that when the
818 // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers
819 // fields should NOT be Zero, or else, these 2 fileds should be set to Zero
821 ValueInSectionHeader
= ReadUnaligned64((UINT64
*)&SectionHeader
.PointerToRelocations
);
822 if (ValueInSectionHeader
!= 0) {
824 // Found first section header that doesn't point to code section in which uild tool saves the
825 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
827 FixLoaddingAddress
= (EFI_PHYSICAL_ADDRESS
)(SmramBase
+ (INT64
)ValueInSectionHeader
);
829 if (SmramBase
+ SmmCodeSize
> FixLoaddingAddress
&& SmramBase
<= FixLoaddingAddress
) {
831 // The assigned address is valid. Return the specified loadding address
833 ImageContext
->ImageAddress
= FixLoaddingAddress
;
834 Status
= EFI_SUCCESS
;
839 SectionHeaderOffset
+= sizeof (EFI_IMAGE_SECTION_HEADER
);
841 DEBUG ((EFI_D_INFO
|EFI_D_LOAD
, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoaddingAddress
, Status
));
845 Load the SMM Core image into SMRAM and executes the SMM Core from SMRAM.
847 @param[in] SmramRange Descriptor for the range of SMRAM to reload the
848 currently executing image.
849 @param[in] Context Context to pass into SMM Core
855 ExecuteSmmCoreFromSmram (
856 IN EFI_SMRAM_DESCRIPTOR
*SmramRange
,
863 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
865 EFI_PHYSICAL_ADDRESS DestinationBuffer
;
866 EFI_IMAGE_ENTRY_POINT EntryPoint
;
869 // Search all Firmware Volumes for a PE/COFF image in a file of type SMM_CORE
871 Status
= GetSectionFromAnyFvByFileType (
872 EFI_FV_FILETYPE_SMM_CORE
,
879 if (EFI_ERROR (Status
)) {
884 // Initilize ImageContext
886 ImageContext
.Handle
= SourceBuffer
;
887 ImageContext
.ImageRead
= PeCoffLoaderImageReadFromMemory
;
890 // Get information about the image being loaded
892 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
893 if (EFI_ERROR (Status
)) {
897 // if Loading module at Fixed Address feature is enabled, the SMM core driver will be loaded to
898 // the address assigned by build tool.
900 if (PcdGet64(PcdLoadModuleAtFixAddressEnable
) != 0) {
902 // Get the fixed loading address assigned by Build tool
904 Status
= GetPeCoffImageFixLoadingAssignedAddress (&ImageContext
);
905 if (!EFI_ERROR (Status
)) {
907 // Since the memory range to load SMM CORE will be cut out in SMM core, so no need to allocate and free this range
911 DEBUG ((EFI_D_INFO
, "LOADING MODULE FIXED ERROR: Loading module at fixed address at address failed\n"));
913 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
914 // specified by SmramRange
916 PageCount
= (UINTN
)EFI_SIZE_TO_PAGES((UINTN
)ImageContext
.ImageSize
+ ImageContext
.SectionAlignment
);
918 ASSERT ((SmramRange
->PhysicalSize
& EFI_PAGE_MASK
) == 0);
919 ASSERT (SmramRange
->PhysicalSize
> EFI_PAGES_TO_SIZE (PageCount
));
921 SmramRange
->PhysicalSize
-= EFI_PAGES_TO_SIZE (PageCount
);
922 DestinationBuffer
= SmramRange
->CpuStart
+ SmramRange
->PhysicalSize
;
925 // Align buffer on section boundry
927 ImageContext
.ImageAddress
= DestinationBuffer
;
931 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
932 // specified by SmramRange
934 PageCount
= (UINTN
)EFI_SIZE_TO_PAGES((UINTN
)ImageContext
.ImageSize
+ ImageContext
.SectionAlignment
);
936 ASSERT ((SmramRange
->PhysicalSize
& EFI_PAGE_MASK
) == 0);
937 ASSERT (SmramRange
->PhysicalSize
> EFI_PAGES_TO_SIZE (PageCount
));
939 SmramRange
->PhysicalSize
-= EFI_PAGES_TO_SIZE (PageCount
);
940 DestinationBuffer
= SmramRange
->CpuStart
+ SmramRange
->PhysicalSize
;
943 // Align buffer on section boundry
945 ImageContext
.ImageAddress
= DestinationBuffer
;
948 ImageContext
.ImageAddress
+= ImageContext
.SectionAlignment
- 1;
949 ImageContext
.ImageAddress
&= ~(ImageContext
.SectionAlignment
- 1);
952 // Print debug message showing SMM Core load address.
954 DEBUG ((DEBUG_INFO
, "SMM IPL loading SMM Core at SMRAM address %p\n", (VOID
*)(UINTN
)ImageContext
.ImageAddress
));
957 // Load the image to our new buffer
959 Status
= PeCoffLoaderLoadImage (&ImageContext
);
960 if (!EFI_ERROR (Status
)) {
962 // Relocate the image in our new buffer
964 Status
= PeCoffLoaderRelocateImage (&ImageContext
);
965 if (!EFI_ERROR (Status
)) {
967 // Flush the instruction cache so the image data are written before we execute it
969 InvalidateInstructionCacheRange ((VOID
*)(UINTN
)ImageContext
.ImageAddress
, (UINTN
)ImageContext
.ImageSize
);
972 // Print debug message showing SMM Core entry point address.
974 DEBUG ((DEBUG_INFO
, "SMM IPL calling SMM Core at SMRAM address %p\n", (VOID
*)(UINTN
)ImageContext
.EntryPoint
));
979 EntryPoint
= (EFI_IMAGE_ENTRY_POINT
)(UINTN
)ImageContext
.EntryPoint
;
980 Status
= EntryPoint ((EFI_HANDLE
)Context
, gST
);
985 // If the load operation, relocate operation, or the image execution return an
986 // error, then free memory allocated from the EFI_SRAM_DESCRIPTOR specified by
989 if (EFI_ERROR (Status
)) {
990 SmramRange
->PhysicalSize
+= EFI_PAGES_TO_SIZE (PageCount
);
994 // Always free memory allocted by GetFileBufferByFilePath ()
996 FreePool (SourceBuffer
);
1002 The Entry Point for SMM IPL
1004 Load SMM Core into SMRAM, register SMM Core entry point for SMIs, install
1005 SMM Base 2 Protocol and SMM Communication Protocol, and register for the
1006 critical events required to coordinate between DXE and SMM environments.
1008 @param ImageHandle The firmware allocated handle for the EFI image.
1009 @param SystemTable A pointer to the EFI System Table.
1011 @retval EFI_SUCCESS The entry point is executed successfully.
1012 @retval Other Some error occurred when executing this entry point.
1018 IN EFI_HANDLE ImageHandle
,
1019 IN EFI_SYSTEM_TABLE
*SystemTable
1023 EFI_SMM_CONFIGURATION_PROTOCOL
*SmmConfiguration
;
1026 EFI_SMM_RESERVED_SMRAM_REGION
*SmramResRegion
;
1030 EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE
*LMFAConfigurationTable
;
1031 EFI_CPU_ARCH_PROTOCOL
*CpuArch
;
1034 // Fill in the image handle of the SMM IPL so the SMM Core can use this as the
1035 // ParentImageHandle field of the Load Image Protocol for all SMM Drivers loaded
1038 mSmmCorePrivateData
.SmmIplImageHandle
= ImageHandle
;
1041 // Get SMM Access Protocol
1043 Status
= gBS
->LocateProtocol (&gEfiSmmAccess2ProtocolGuid
, NULL
, (VOID
**)&mSmmAccess
);
1044 ASSERT_EFI_ERROR (Status
);
1047 // Get SMM Control2 Protocol
1049 Status
= gBS
->LocateProtocol (&gEfiSmmControl2ProtocolGuid
, NULL
, (VOID
**)&mSmmControl2
);
1050 ASSERT_EFI_ERROR (Status
);
1053 // Get SMM Configuration Protocol if it is present
1055 SmmConfiguration
= NULL
;
1056 Status
= gBS
->LocateProtocol (&gEfiSmmConfigurationProtocolGuid
, NULL
, (VOID
**) &SmmConfiguration
);
1059 // Get SMRAM information
1062 Status
= mSmmAccess
->GetCapabilities (mSmmAccess
, &Size
, NULL
);
1063 ASSERT (Status
== EFI_BUFFER_TOO_SMALL
);
1065 gSmmCorePrivate
->SmramRanges
= (EFI_SMRAM_DESCRIPTOR
*)AllocatePool (Size
);
1066 ASSERT (gSmmCorePrivate
->SmramRanges
!= NULL
);
1068 Status
= mSmmAccess
->GetCapabilities (mSmmAccess
, &Size
, gSmmCorePrivate
->SmramRanges
);
1069 ASSERT_EFI_ERROR (Status
);
1071 gSmmCorePrivate
->SmramRangeCount
= Size
/ sizeof (EFI_SMRAM_DESCRIPTOR
);
1074 // Open all SMRAM ranges
1076 Status
= mSmmAccess
->Open (mSmmAccess
);
1077 ASSERT_EFI_ERROR (Status
);
1080 // Print debug message that the SMRAM window is now open.
1082 DEBUG ((DEBUG_INFO
, "SMM IPL opened SMRAM window\n"));
1085 // Subtract SMRAM any reserved SMRAM regions.
1087 if (SmmConfiguration
!= NULL
) {
1088 SmramResRegion
= SmmConfiguration
->SmramReservedRegions
;
1089 while (SmramResRegion
->SmramReservedSize
!= 0) {
1090 for (Index
= 0; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
1091 if ((SmramResRegion
->SmramReservedStart
>= gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
) && \
1092 ((SmramResRegion
->SmramReservedStart
+ SmramResRegion
->SmramReservedSize
) <= \
1093 (gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
+ gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
))) {
1095 // This range has reserved area, calculate the left free size
1097 gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
= SmramResRegion
->SmramReservedStart
- gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
;
1105 // Find the largest SMRAM range between 1MB and 4GB that is at least 256KB - 4K in size
1107 mCurrentSmramRange
= NULL
;
1108 for (Index
= 0, MaxSize
= SIZE_256KB
- EFI_PAGE_SIZE
; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
1110 // Skip any SMRAM region that is already allocated, needs testing, or needs ECC initialization
1112 if ((gSmmCorePrivate
->SmramRanges
[Index
].RegionState
& (EFI_ALLOCATED
| EFI_NEEDS_TESTING
| EFI_NEEDS_ECC_INITIALIZATION
)) != 0) {
1116 if (gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
>= BASE_1MB
) {
1117 if ((gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
+ gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
) <= BASE_4GB
) {
1118 if (gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
>= MaxSize
) {
1119 MaxSize
= gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
;
1120 mCurrentSmramRange
= &gSmmCorePrivate
->SmramRanges
[Index
];
1126 if (mCurrentSmramRange
!= NULL
) {
1128 // Print debug message showing SMRAM window that will be used by SMM IPL and SMM Core
1130 DEBUG ((DEBUG_INFO
, "SMM IPL found SMRAM window %p - %p\n",
1131 (VOID
*)(UINTN
)mCurrentSmramRange
->CpuStart
,
1132 (VOID
*)(UINTN
)(mCurrentSmramRange
->CpuStart
+ mCurrentSmramRange
->PhysicalSize
- 1)
1135 GetSmramCacheRange (mCurrentSmramRange
, &mSmramCacheBase
, &mSmramCacheSize
);
1137 // If CPU AP is present, attempt to set SMRAM cacheability to WB
1138 // Note that it is expected that cacheability of SMRAM has been set to WB if CPU AP
1139 // is not available here.
1142 Status
= gBS
->LocateProtocol (&gEfiCpuArchProtocolGuid
, NULL
, (VOID
**)&CpuArch
);
1143 if (!EFI_ERROR (Status
)) {
1144 Status
= gDS
->SetMemorySpaceAttributes(
1149 if (EFI_ERROR (Status
)) {
1150 DEBUG ((DEBUG_WARN
, "SMM IPL failed to set SMRAM window to EFI_MEMORY_WB\n"));
1154 // if Loading module at Fixed Address feature is enabled, save the SMRAM base to Load
1155 // Modules At Fixed Address Configuration Table.
1157 if (PcdGet64(PcdLoadModuleAtFixAddressEnable
) != 0) {
1159 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
1161 SmmCodeSize
= LShiftU64 (PcdGet32(PcdLoadFixAddressSmmCodePageNumber
), EFI_PAGE_SHIFT
);
1163 // The SMRAM available memory is assumed to be larger than SmmCodeSize
1165 ASSERT (mCurrentSmramRange
->PhysicalSize
> SmmCodeSize
);
1167 // Retrieve Load modules At fixed address configuration table and save the SMRAM base.
1169 Status
= EfiGetSystemConfigurationTable (
1170 &gLoadFixedAddressConfigurationTableGuid
,
1171 (VOID
**) &LMFAConfigurationTable
1173 if (!EFI_ERROR (Status
) && LMFAConfigurationTable
!= NULL
) {
1174 LMFAConfigurationTable
->SmramBase
= mCurrentSmramRange
->CpuStart
;
1176 // Print the SMRAM base
1178 DEBUG ((EFI_D_INFO
, "LOADING MODULE FIXED INFO: TSEG BASE is %x. \n", LMFAConfigurationTable
->SmramBase
));
1182 // Load SMM Core into SMRAM and execute it from SMRAM
1184 Status
= ExecuteSmmCoreFromSmram (mCurrentSmramRange
, gSmmCorePrivate
);
1185 if (EFI_ERROR (Status
)) {
1187 // Print error message that the SMM Core failed to be loaded and executed.
1189 DEBUG ((DEBUG_ERROR
, "SMM IPL could not load and execute SMM Core from SMRAM\n"));
1192 // Attempt to reset SMRAM cacheability to UC
1194 if (CpuArch
!= NULL
) {
1195 Status
= gDS
->SetMemorySpaceAttributes(
1200 if (EFI_ERROR (Status
)) {
1201 DEBUG ((DEBUG_WARN
, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
1207 // Print error message that there are not enough SMRAM resources to load the SMM Core.
1209 DEBUG ((DEBUG_ERROR
, "SMM IPL could not find a large enough SMRAM region to load SMM Core\n"));
1213 // If the SMM Core could not be loaded then close SMRAM window, free allocated
1214 // resources, and return an error so SMM IPL will be unloaded.
1216 if (mCurrentSmramRange
== NULL
|| EFI_ERROR (Status
)) {
1218 // Close all SMRAM ranges
1220 Status
= mSmmAccess
->Close (mSmmAccess
);
1221 ASSERT_EFI_ERROR (Status
);
1224 // Print debug message that the SMRAM window is now closed.
1226 DEBUG ((DEBUG_INFO
, "SMM IPL closed SMRAM window\n"));
1229 // Free all allocated resources
1231 FreePool (gSmmCorePrivate
->SmramRanges
);
1233 return EFI_UNSUPPORTED
;
1237 // Install SMM Base2 Protocol and SMM Communication Protocol
1239 Status
= gBS
->InstallMultipleProtocolInterfaces (
1241 &gEfiSmmBase2ProtocolGuid
, &mSmmBase2
,
1242 &gEfiSmmCommunicationProtocolGuid
, &mSmmCommunication
,
1245 ASSERT_EFI_ERROR (Status
);
1248 // Create the set of protocol and event notififcations that the SMM IPL requires
1250 for (Index
= 0; mSmmIplEvents
[Index
].NotifyFunction
!= NULL
; Index
++) {
1251 if (mSmmIplEvents
[Index
].Protocol
) {
1252 mSmmIplEvents
[Index
].Event
= EfiCreateProtocolNotifyEvent (
1253 mSmmIplEvents
[Index
].Guid
,
1254 mSmmIplEvents
[Index
].NotifyTpl
,
1255 mSmmIplEvents
[Index
].NotifyFunction
,
1256 mSmmIplEvents
[Index
].NotifyContext
,
1260 Status
= gBS
->CreateEventEx (
1262 mSmmIplEvents
[Index
].NotifyTpl
,
1263 mSmmIplEvents
[Index
].NotifyFunction
,
1264 mSmmIplEvents
[Index
].NotifyContext
,
1265 mSmmIplEvents
[Index
].Guid
,
1266 &mSmmIplEvents
[Index
].Event
1268 ASSERT_EFI_ERROR (Status
);