2 SMM IPL that produces SMM related runtime protocols and load the SMM Core into SMRAM
4 Copyright (c) 2009 - 2010, 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/FirmwareVolume2.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/UefiLib.h>
38 #include <Library/UefiRuntimeLib.h>
39 #include <Library/PcdLib.h>
41 #include "PiSmmCorePrivateData.h"
44 // Function prototypes from produced protocols
48 Indicate whether the driver is currently executing in the SMM Initialization phase.
50 @param This The EFI_SMM_BASE2_PROTOCOL instance.
51 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
52 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
54 @retval EFI_INVALID_PARAMETER InSmram was NULL.
55 @retval EFI_SUCCESS The call returned successfully.
61 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
66 Retrieves the location of the System Management System Table (SMST).
68 @param This The EFI_SMM_BASE2_PROTOCOL instance.
69 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
71 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
72 @retval EFI_SUCCESS The memory was returned to the system.
73 @retval EFI_UNSUPPORTED Not in SMM.
78 SmmBase2GetSmstLocation (
79 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
80 OUT EFI_SMM_SYSTEM_TABLE2
**Smst
84 Communicates with a registered handler.
86 This function provides a service to send and receive messages from a registered
87 UEFI service. This function is part of the SMM Communication Protocol that may
88 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
89 after SetVirtualAddressMap().
91 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
92 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
93 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
94 being returned. Zero if the handler does not wish to reply with any data.
96 @retval EFI_SUCCESS The message was successfully posted.
97 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
101 SmmCommunicationCommunicate (
102 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL
*This
,
103 IN OUT VOID
*CommBuffer
,
104 IN OUT UINTN
*CommSize
108 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
110 @param Event The Event that is being processed, not used.
111 @param Context Event Context, not used.
116 SmmIplSmmConfigurationEventNotify (
122 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
123 or if gEfiEventReadyToBootGuid is signalled.
125 @param Event The Event that is being processed, not used.
126 @param Context Event Context, not used.
131 SmmIplReadyToLockEventNotify (
137 Event notification that is fired when DxeDispatch Event Group is signaled.
139 @param Event The Event that is being processed, not used.
140 @param Context Event Context, not used.
145 SmmIplGuidedEventNotify (
151 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
153 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
154 It convers pointer to new virtual address.
156 @param Event Event whose notification function is being invoked.
157 @param Context Pointer to the notification function's context.
162 SmmIplSetVirtualAddressNotify (
168 // Data structure used to declare a table of protocol notifications and event
169 // notifications required by the SMM IPL
175 EFI_EVENT_NOTIFY NotifyFunction
;
178 } SMM_IPL_EVENT_NOTIFICATION
;
181 // Handle to install the SMM Base2 Protocol and the SMM Communication Protocol
183 EFI_HANDLE mSmmIplHandle
= NULL
;
186 // SMM Base 2 Protocol instance
188 EFI_SMM_BASE2_PROTOCOL mSmmBase2
= {
190 SmmBase2GetSmstLocation
194 // SMM Communication Protocol instance
196 EFI_SMM_COMMUNICATION_PROTOCOL mSmmCommunication
= {
197 SmmCommunicationCommunicate
201 // SMM Core Private Data structure that contains the data shared between
202 // the SMM IPL and the SMM Core.
204 SMM_CORE_PRIVATE_DATA mSmmCorePrivateData
= {
205 SMM_CORE_PRIVATE_DATA_SIGNATURE
, // Signature
206 NULL
, // SmmIplImageHandle
207 0, // SmramRangeCount
209 NULL
, // SmmEntryPoint
210 FALSE
, // SmmEntryPointRegistered
214 NULL
, // CommunicationBuffer
215 EFI_SUCCESS
// ReturnStatus
219 // Global pointer used to access mSmmCorePrivateData from outside and inside SMM
221 SMM_CORE_PRIVATE_DATA
*gSmmCorePrivate
= &mSmmCorePrivateData
;
224 // SMM IPL global variables
226 EFI_SMM_CONTROL2_PROTOCOL
*mSmmControl2
;
227 EFI_SMM_ACCESS2_PROTOCOL
*mSmmAccess
;
228 EFI_SMRAM_DESCRIPTOR
*mCurrentSmramRange
;
229 BOOLEAN mSmmLocked
= FALSE
;
230 EFI_PHYSICAL_ADDRESS mSmramCacheBase
;
231 UINT64 mSmramCacheSize
;
234 // Table of Protocol notification and GUIDed Event notifications that the SMM IPL requires
236 SMM_IPL_EVENT_NOTIFICATION mSmmIplEvents
[] = {
238 // Declare protocol notification on the SMM Configuration protocol. When this notification is etablished,
239 // the associated event is immediately signalled, so the notification function will be executed and the
240 // SMM Configuration Protocol will be found if it is already in the handle database.
242 { TRUE
, FALSE
, &gEfiSmmConfigurationProtocolGuid
, SmmIplSmmConfigurationEventNotify
, &gEfiSmmConfigurationProtocolGuid
, NULL
},
244 // Declare protocl notification on DxeSmmReadyToLock protocols. When this notification is etablished,
245 // the associated event is immediately signalled, so the notification function will be executed and the
246 // DXE SMM Ready To Lock Protocol will be found if it is already in the handle database.
248 { TRUE
, TRUE
, &gEfiDxeSmmReadyToLockProtocolGuid
, SmmIplReadyToLockEventNotify
, &gEfiDxeSmmReadyToLockProtocolGuid
, NULL
},
250 // Declare event notification on the DXE Dispatch Event Group. This event is signaled by the DXE Core
251 // each time the DXE Core dispatcher has completed its work. When this event is signalled, the SMM Core
252 // if notified, so the SMM Core can dispatch SMM drivers.
254 { FALSE
, TRUE
, &gEfiEventDxeDispatchGuid
, SmmIplGuidedEventNotify
, &gEfiEventDxeDispatchGuid
, NULL
},
256 // Declare event notification on Ready To Boot Event Group. This is an extra event notification that is
257 // used to make sure SMRAM is locked before any boot options are processed.
259 { FALSE
, TRUE
, &gEfiEventReadyToBootGuid
, SmmIplReadyToLockEventNotify
, &gEfiEventReadyToBootGuid
, NULL
},
261 // Declare event notification on Legacy Boot Event Group. This is used to inform the SMM Core that the platform
262 // is performing a legacy boot operation, and that the UEFI environment is no longer available and the SMM Core
263 // must guarantee that it does not access any UEFI related structures outside of SMRAM.
265 { FALSE
, FALSE
, &gEfiEventLegacyBootGuid
, SmmIplGuidedEventNotify
, &gEfiEventLegacyBootGuid
, NULL
},
267 // Declare event notification on SetVirtualAddressMap() Event Group. This is used to convert gSmmCorePrivate
268 // and mSmmControl2 from physical addresses to virtual addresses.
270 { FALSE
, FALSE
, &gEfiEventVirtualAddressChangeGuid
, SmmIplSetVirtualAddressNotify
, NULL
, NULL
},
272 // Terminate the table of event notifications
274 { FALSE
, FALSE
, NULL
, NULL
, NULL
, NULL
}
278 Find the maximum SMRAM cache range that covers the range specified by SmramRange.
280 This function searches and joins all adjacent ranges of SmramRange into a range to be cached.
282 @param SmramRange The SMRAM range to search from.
283 @param SmramCacheBase The returned cache range base.
284 @param SmramCacheSize The returned cache range size.
289 IN EFI_SMRAM_DESCRIPTOR
*SmramRange
,
290 OUT EFI_PHYSICAL_ADDRESS
*SmramCacheBase
,
291 OUT UINT64
*SmramCacheSize
295 EFI_PHYSICAL_ADDRESS RangeCpuStart
;
296 UINT64 RangePhysicalSize
;
297 BOOLEAN FoundAjacentRange
;
299 *SmramCacheBase
= SmramRange
->CpuStart
;
300 *SmramCacheSize
= SmramRange
->PhysicalSize
;
303 FoundAjacentRange
= FALSE
;
304 for (Index
= 0; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
305 RangeCpuStart
= gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
;
306 RangePhysicalSize
= gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
;
307 if (RangeCpuStart
< *SmramCacheBase
&& *SmramCacheBase
== (RangeCpuStart
+ RangePhysicalSize
)) {
308 *SmramCacheBase
= RangeCpuStart
;
309 *SmramCacheSize
+= RangePhysicalSize
;
310 FoundAjacentRange
= TRUE
;
311 } else if ((*SmramCacheBase
+ *SmramCacheSize
) == RangeCpuStart
&& RangePhysicalSize
> 0) {
312 *SmramCacheSize
+= RangePhysicalSize
;
313 FoundAjacentRange
= TRUE
;
316 } while (FoundAjacentRange
);
321 Indicate whether the driver is currently executing in the SMM Initialization phase.
323 @param This The EFI_SMM_BASE2_PROTOCOL instance.
324 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
325 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
327 @retval EFI_INVALID_PARAMETER InSmram was NULL.
328 @retval EFI_SUCCESS The call returned successfully.
334 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
338 if (InSmram
== NULL
) {
339 return EFI_INVALID_PARAMETER
;
342 *InSmram
= gSmmCorePrivate
->InSmm
;
348 Retrieves the location of the System Management System Table (SMST).
350 @param This The EFI_SMM_BASE2_PROTOCOL instance.
351 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
353 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
354 @retval EFI_SUCCESS The memory was returned to the system.
355 @retval EFI_UNSUPPORTED Not in SMM.
360 SmmBase2GetSmstLocation (
361 IN CONST EFI_SMM_BASE2_PROTOCOL
*This
,
362 OUT EFI_SMM_SYSTEM_TABLE2
**Smst
365 if ((This
== NULL
) ||(Smst
== NULL
)) {
366 return EFI_INVALID_PARAMETER
;
369 if (!gSmmCorePrivate
->InSmm
) {
370 return EFI_UNSUPPORTED
;
373 *Smst
= gSmmCorePrivate
->Smst
;
379 Communicates with a registered handler.
381 This function provides a service to send and receive messages from a registered
382 UEFI service. This function is part of the SMM Communication Protocol that may
383 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
384 after SetVirtualAddressMap().
386 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
387 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
388 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
389 being returned. Zero if the handler does not wish to reply with any data.
391 @retval EFI_SUCCESS The message was successfully posted.
392 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
396 SmmCommunicationCommunicate (
397 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL
*This
,
398 IN OUT VOID
*CommBuffer
,
399 IN OUT UINTN
*CommSize
403 EFI_SMM_COMMUNICATE_HEADER
*CommunicateHeader
;
409 if ((CommBuffer
== NULL
) || (CommSize
== NULL
)) {
410 return EFI_INVALID_PARAMETER
;
414 // If not already in SMM, then generate a Software SMI
416 if (!gSmmCorePrivate
->InSmm
&& gSmmCorePrivate
->SmmEntryPointRegistered
) {
418 // Put arguments for Software SMI in gSmmCorePrivate
420 gSmmCorePrivate
->CommunicationBuffer
= CommBuffer
;
421 gSmmCorePrivate
->BufferSize
= CommSize
;
424 // Generate Software SMI
426 Status
= mSmmControl2
->Trigger (mSmmControl2
, NULL
, NULL
, FALSE
, 0);
427 if (EFI_ERROR (Status
)) {
428 return EFI_UNSUPPORTED
;
432 // Return status from software SMI
434 return gSmmCorePrivate
->ReturnStatus
;
438 // If we are in SMM, then the execution mode must be physical, which means that
439 // OS established virtual addresses can not be used. If SetVirtualAddressMap()
440 // has been called, then a direct invocation of the Software SMI is not
441 // not allowed so return EFI_INVALID_PARAMETER.
443 if (EfiGoneVirtual()) {
444 return EFI_INVALID_PARAMETER
;
448 // Don't allow call SmiManage() directly when SMRAM is closed or locked.
450 if (!mSmmAccess
->OpenState
|| mSmmAccess
->LockState
) {
451 return EFI_INVALID_PARAMETER
;
455 // Save current InSmm state and set InSmm state to TRUE
457 OldInSmm
= gSmmCorePrivate
->InSmm
;
458 gSmmCorePrivate
->InSmm
= TRUE
;
461 // Already in SMM and before SetVirtualAddressMap(), so call SmiManage() directly.
463 CommunicateHeader
= (EFI_SMM_COMMUNICATE_HEADER
*)CommBuffer
;
464 *CommSize
-= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER
, Data
);
465 Status
= gSmmCorePrivate
->Smst
->SmiManage (
466 &CommunicateHeader
->HeaderGuid
,
468 CommunicateHeader
->Data
,
473 // Update CommunicationBuffer, BufferSize and ReturnStatus
474 // Communicate service finished, reset the pointer to CommBuffer to NULL
476 *CommSize
+= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER
, Data
);
479 // Restore original InSmm state
481 gSmmCorePrivate
->InSmm
= OldInSmm
;
483 return (Status
== EFI_WARN_INTERRUPT_SOURCE_QUIESCED
) ? EFI_SUCCESS
: EFI_NOT_FOUND
;
487 Event notification that is fired when DxeDispatch Event Group is signaled.
489 @param Event The Event that is being processed, not used.
490 @param Context Event Context, not used.
495 SmmIplGuidedEventNotify (
500 EFI_SMM_COMMUNICATE_HEADER CommunicateHeader
;
504 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
506 CopyGuid (&CommunicateHeader
.HeaderGuid
, (EFI_GUID
*)Context
);
507 CommunicateHeader
.MessageLength
= 1;
508 CommunicateHeader
.Data
[0] = 0;
511 // Generate the Software SMI and return the result
513 Size
= sizeof (CommunicateHeader
);
514 SmmCommunicationCommunicate (&mSmmCommunication
, &CommunicateHeader
, &Size
);
518 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
520 @param Event The Event that is being processed, not used.
521 @param Context Event Context, not used.
526 SmmIplSmmConfigurationEventNotify (
532 EFI_SMM_CONFIGURATION_PROTOCOL
*SmmConfiguration
;
535 // Make sure this notification is for this handler
537 Status
= gBS
->LocateProtocol (Context
, NULL
, (VOID
**)&SmmConfiguration
);
538 if (EFI_ERROR (Status
)) {
543 // Register the SMM Entry Point provided by the SMM Core with the SMM COnfiguration protocol
545 Status
= SmmConfiguration
->RegisterSmmEntry (SmmConfiguration
, gSmmCorePrivate
->SmmEntryPoint
);
546 ASSERT_EFI_ERROR (Status
);
549 // Set flag to indicate that the SM< Entry Point has been registered which
550 // means that SMIs are now fully operational.
552 gSmmCorePrivate
->SmmEntryPointRegistered
= TRUE
;
555 // Print debug message showing SMM Core entry point address.
557 DEBUG ((DEBUG_INFO
, "SMM IPL registered SMM Entry Point address %p\n", (VOID
*)(UINTN
)gSmmCorePrivate
->SmmEntryPoint
));
560 // Attempt to reset SMRAM cacheability to UC
562 Status
= gDS
->SetMemorySpaceAttributes(
567 if (EFI_ERROR (Status
)) {
568 DEBUG ((DEBUG_WARN
, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
572 // Close all SMRAM ranges to protect SMRAM
574 Status
= mSmmAccess
->Close (mSmmAccess
);
575 ASSERT_EFI_ERROR (Status
);
578 // Print debug message that the SMRAM window is now closed.
580 DEBUG ((DEBUG_INFO
, "SMM IPL closed SMRAM window\n"));
584 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
585 or if gEfiEventReadyToBootGuid is signalled.
587 @param Event The Event that is being processed, not used.
588 @param Context Event Context, not used.
593 SmmIplReadyToLockEventNotify (
603 // See if we are already locked
610 // Make sure this notification is for this handler
612 if (CompareGuid ((EFI_GUID
*)Context
, &gEfiDxeSmmReadyToLockProtocolGuid
)) {
613 Status
= gBS
->LocateProtocol (&gEfiDxeSmmReadyToLockProtocolGuid
, NULL
, &Interface
);
614 if (EFI_ERROR (Status
)) {
619 // If SMM is not locked yet and we got here from gEfiEventReadyToBootGuid being
620 // signalled, then gEfiDxeSmmReadyToLockProtocolGuid was not installed as expected.
621 // Print a warning on debug builds.
623 DEBUG ((DEBUG_WARN
, "SMM IPL! DXE SMM Ready To Lock Protocol not installed before Ready To Boot signal\n"));
627 // Lock the SMRAM (Note: Locking SMRAM may not be supported on all platforms)
629 mSmmAccess
->Lock (mSmmAccess
);
632 // Close protocol and event notification events that do not apply after the
633 // DXE SMM Ready To Lock Protocol has been installed or the Ready To Boot
634 // event has been signalled.
636 for (Index
= 0; mSmmIplEvents
[Index
].NotifyFunction
!= NULL
; Index
++) {
637 if (mSmmIplEvents
[Index
].CloseOnLock
) {
638 gBS
->CloseEvent (mSmmIplEvents
[Index
].Event
);
643 // Inform SMM Core that the DxeSmmReadyToLock protocol was installed
645 SmmIplGuidedEventNotify (Event
, (VOID
*)&gEfiDxeSmmReadyToLockProtocolGuid
);
648 // Print debug message that the SMRAM window is now locked.
650 DEBUG ((DEBUG_INFO
, "SMM IPL locked SMRAM window\n"));
653 // Set flag so this operation will not be performed again
659 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
661 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
662 It convers pointer to new virtual address.
664 @param Event Event whose notification function is being invoked.
665 @param Context Pointer to the notification function's context.
670 SmmIplSetVirtualAddressNotify (
675 EfiConvertPointer (0x0, (VOID
**)&mSmmControl2
);
679 Searches all Firmware Volumes for the first file matching FileType and SectionType and returns the section data.
681 @param FileType FileType to search for within any of the firmware volumes in the platform.
682 @param SectionType SectionType to search for within any of the matching FileTypes in the firmware volumes in the platform.
683 @param SourceSize Return the size of the returned section data..
685 @retval != NULL Pointer to the allocated buffer containing the section data.
686 @retval NULL Section data was not found.
691 IN EFI_FV_FILETYPE FileType
,
692 IN EFI_SECTION_TYPE SectionType
,
693 OUT UINTN
*SourceSize
698 EFI_HANDLE
*HandleBuffer
;
700 EFI_FIRMWARE_VOLUME2_PROTOCOL
*Fv
;
703 EFI_FV_FILE_ATTRIBUTES Attributes
;
705 UINT32 AuthenticationStatus
;
708 Status
= gBS
->LocateHandleBuffer (
710 &gEfiFirmwareVolume2ProtocolGuid
,
715 if (EFI_ERROR (Status
)) {
719 for (Index
= 0; Index
< HandleCount
; Index
++) {
720 Status
= gBS
->HandleProtocol (
722 &gEfiFirmwareVolume2ProtocolGuid
,
725 if (EFI_ERROR (Status
)) {
730 // Use Firmware Volume 2 Protocol to search for a file of type FileType
733 Status
= Fv
->GetNextFile (Fv
, &Key
, &FileType
, &NameGuid
, &Attributes
, SourceSize
);
734 if (EFI_ERROR (Status
)) {
739 // Use Firmware Volume 2 Protocol to read a section of type SectionType
742 Status
= Fv
->ReadSection (Fv
, &NameGuid
, SectionType
, 0, &SourceBuffer
, SourceSize
, &AuthenticationStatus
);
743 if (!EFI_ERROR (Status
)) {
744 FreePool (HandleBuffer
);
749 FreePool(HandleBuffer
);
754 Get the fixed loadding address from image header assigned by build tool. This function only be called
755 when Loading module at Fixed address feature enabled.
757 @param ImageContext Pointer to the image context structure that describes the PE/COFF
758 image that needs to be examined by this function.
759 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
760 @retval EFI_NOT_FOUND The image has no assigned fixed loadding address.
763 GetPeCoffImageFixLoadingAssignedAddress(
764 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
767 UINTN SectionHeaderOffset
;
769 EFI_IMAGE_SECTION_HEADER SectionHeader
;
770 EFI_IMAGE_OPTIONAL_HEADER_UNION
*ImgHdr
;
771 EFI_PHYSICAL_ADDRESS FixLoaddingAddress
;
774 UINT16 NumberOfSections
;
775 EFI_PHYSICAL_ADDRESS SmramBase
;
777 UINT64 ValueInSectionHeader
;
779 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
781 SmmCodeSize
= EFI_PAGES_TO_SIZE (PcdGet32(PcdLoadFixAddressSmmCodePageNumber
));
783 FixLoaddingAddress
= 0;
784 Status
= EFI_NOT_FOUND
;
785 SmramBase
= mCurrentSmramRange
->CpuStart
;
787 // Get PeHeader pointer
789 ImgHdr
= (EFI_IMAGE_OPTIONAL_HEADER_UNION
*)((CHAR8
* )ImageContext
->Handle
+ ImageContext
->PeCoffHeaderOffset
);
790 SectionHeaderOffset
= (UINTN
)(
791 ImageContext
->PeCoffHeaderOffset
+
793 sizeof (EFI_IMAGE_FILE_HEADER
) +
794 ImgHdr
->Pe32
.FileHeader
.SizeOfOptionalHeader
796 NumberOfSections
= ImgHdr
->Pe32
.FileHeader
.NumberOfSections
;
799 // Get base address from the first section header that doesn't point to code section.
801 for (Index
= 0; Index
< NumberOfSections
; Index
++) {
803 // Read section header from file
805 Size
= sizeof (EFI_IMAGE_SECTION_HEADER
);
806 Status
= ImageContext
->ImageRead (
807 ImageContext
->Handle
,
812 if (EFI_ERROR (Status
)) {
816 Status
= EFI_NOT_FOUND
;
818 if ((SectionHeader
.Characteristics
& EFI_IMAGE_SCN_CNT_CODE
) == 0) {
820 // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the
821 // first section header that doesn't point to code section in image header. And there is an assumption that when the
822 // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers
823 // fields should NOT be Zero, or else, these 2 fileds should be set to Zero
825 ValueInSectionHeader
= ReadUnaligned64((UINT64
*)&SectionHeader
.PointerToRelocations
);
826 if (ValueInSectionHeader
!= 0) {
828 // Found first section header that doesn't point to code section in which uild tool saves the
829 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
831 FixLoaddingAddress
= (EFI_PHYSICAL_ADDRESS
)(SmramBase
+ (INT64
)ValueInSectionHeader
);
833 if (SmramBase
+ SmmCodeSize
> FixLoaddingAddress
&& SmramBase
<= FixLoaddingAddress
) {
835 // The assigned address is valid. Return the specified loadding address
837 ImageContext
->ImageAddress
= FixLoaddingAddress
;
838 Status
= EFI_SUCCESS
;
843 SectionHeaderOffset
+= sizeof (EFI_IMAGE_SECTION_HEADER
);
845 DEBUG ((EFI_D_INFO
|EFI_D_LOAD
, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoaddingAddress
, Status
));
849 Load the SMM Core image into SMRAM and executes the SMM Core from SMRAM.
851 @param[in] SmramRange Descriptor for the range of SMRAM to reload the
852 currently executing image.
853 @param[in] Context Context to pass into SMM Core
859 ExecuteSmmCoreFromSmram (
860 IN EFI_SMRAM_DESCRIPTOR
*SmramRange
,
867 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
869 EFI_PHYSICAL_ADDRESS DestinationBuffer
;
870 EFI_IMAGE_ENTRY_POINT EntryPoint
;
873 // Search all Firmware Volumes for a PE/COFF image in a file of type SMM_CORE
875 SourceBuffer
= GetSectionInAnyFv (EFI_FV_FILETYPE_SMM_CORE
, EFI_SECTION_PE32
, &SourceSize
);
876 if (SourceBuffer
== NULL
) {
877 return EFI_NOT_FOUND
;
881 // Initilize ImageContext
883 ImageContext
.Handle
= SourceBuffer
;
884 ImageContext
.ImageRead
= PeCoffLoaderImageReadFromMemory
;
887 // Get information about the image being loaded
889 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
890 if (EFI_ERROR (Status
)) {
894 // if Loading module at Fixed Address feature is enabled, the SMM core driver will be loaded to
895 // the address assigned by build tool.
897 if (PcdGet64(PcdLoadModuleAtFixAddressEnable
) != 0) {
899 // Get the fixed loading address assigned by Build tool
901 Status
= GetPeCoffImageFixLoadingAssignedAddress (&ImageContext
);
902 if (!EFI_ERROR (Status
)) {
904 // Since the memory range to load SMM CORE will be cut out in SMM core, so no need to allocate and free this range
908 DEBUG ((EFI_D_INFO
, "LOADING MODULE FIXED ERROR: Loading module at fixed address at address failed\n"));
910 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
911 // specified by SmramRange
913 PageCount
= (UINTN
)EFI_SIZE_TO_PAGES(ImageContext
.ImageSize
+ ImageContext
.SectionAlignment
);
915 ASSERT ((SmramRange
->PhysicalSize
& EFI_PAGE_MASK
) == 0);
916 ASSERT (SmramRange
->PhysicalSize
> EFI_PAGES_TO_SIZE (PageCount
));
918 SmramRange
->PhysicalSize
-= EFI_PAGES_TO_SIZE (PageCount
);
919 DestinationBuffer
= SmramRange
->CpuStart
+ SmramRange
->PhysicalSize
;
922 // Align buffer on section boundry
924 ImageContext
.ImageAddress
= DestinationBuffer
;
928 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
929 // specified by SmramRange
931 PageCount
= (UINTN
)EFI_SIZE_TO_PAGES(ImageContext
.ImageSize
+ ImageContext
.SectionAlignment
);
933 ASSERT ((SmramRange
->PhysicalSize
& EFI_PAGE_MASK
) == 0);
934 ASSERT (SmramRange
->PhysicalSize
> EFI_PAGES_TO_SIZE (PageCount
));
936 SmramRange
->PhysicalSize
-= EFI_PAGES_TO_SIZE (PageCount
);
937 DestinationBuffer
= SmramRange
->CpuStart
+ SmramRange
->PhysicalSize
;
940 // Align buffer on section boundry
942 ImageContext
.ImageAddress
= DestinationBuffer
;
945 ImageContext
.ImageAddress
+= ImageContext
.SectionAlignment
- 1;
946 ImageContext
.ImageAddress
&= ~(ImageContext
.SectionAlignment
- 1);
949 // Print debug message showing SMM Core load address.
951 DEBUG ((DEBUG_INFO
, "SMM IPL loading SMM Core at SMRAM address %p\n", (VOID
*)(UINTN
)ImageContext
.ImageAddress
));
954 // Load the image to our new buffer
956 Status
= PeCoffLoaderLoadImage (&ImageContext
);
957 if (!EFI_ERROR (Status
)) {
959 // Relocate the image in our new buffer
961 Status
= PeCoffLoaderRelocateImage (&ImageContext
);
962 if (!EFI_ERROR (Status
)) {
964 // Flush the instruction cache so the image data are written before we execute it
966 InvalidateInstructionCacheRange ((VOID
*)(UINTN
)ImageContext
.ImageAddress
, (UINTN
)ImageContext
.ImageSize
);
969 // Print debug message showing SMM Core entry point address.
971 DEBUG ((DEBUG_INFO
, "SMM IPL calling SMM Core at SMRAM address %p\n", (VOID
*)(UINTN
)ImageContext
.EntryPoint
));
976 EntryPoint
= (EFI_IMAGE_ENTRY_POINT
)(UINTN
)ImageContext
.EntryPoint
;
977 Status
= EntryPoint ((EFI_HANDLE
)Context
, gST
);
982 // If the load operation, relocate operation, or the image execution return an
983 // error, then free memory allocated from the EFI_SRAM_DESCRIPTOR specified by
986 if (EFI_ERROR (Status
)) {
987 SmramRange
->PhysicalSize
+= EFI_PAGES_TO_SIZE (PageCount
);
991 // Always free memory allocted by GetFileBufferByFilePath ()
993 FreePool (SourceBuffer
);
999 The Entry Point for SMM IPL
1001 Load SMM Core into SMRAM, register SMM Core entry point for SMIs, install
1002 SMM Base 2 Protocol and SMM Communication Protocol, and register for the
1003 critical events required to coordinate between DXE and SMM environments.
1005 @param ImageHandle The firmware allocated handle for the EFI image.
1006 @param SystemTable A pointer to the EFI System Table.
1008 @retval EFI_SUCCESS The entry point is executed successfully.
1009 @retval Other Some error occurred when executing this entry point.
1015 IN EFI_HANDLE ImageHandle
,
1016 IN EFI_SYSTEM_TABLE
*SystemTable
1020 EFI_SMM_CONFIGURATION_PROTOCOL
*SmmConfiguration
;
1023 EFI_SMM_RESERVED_SMRAM_REGION
*SmramResRegion
;
1027 EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE
*LMFAConfigurationTable
;
1030 // Fill in the image handle of the SMM IPL so the SMM Core can use this as the
1031 // ParentImageHandle field of the Load Image Protocol for all SMM Drivers loaded
1034 mSmmCorePrivateData
.SmmIplImageHandle
= ImageHandle
;
1037 // Get SMM Access Protocol
1039 Status
= gBS
->LocateProtocol (&gEfiSmmAccess2ProtocolGuid
, NULL
, (VOID
**)&mSmmAccess
);
1040 ASSERT_EFI_ERROR (Status
);
1043 // Get SMM Control2 Protocol
1045 Status
= gBS
->LocateProtocol (&gEfiSmmControl2ProtocolGuid
, NULL
, (VOID
**)&mSmmControl2
);
1046 ASSERT_EFI_ERROR (Status
);
1049 // Get SMM Configuration Protocol if it is present
1051 SmmConfiguration
= NULL
;
1052 Status
= gBS
->LocateProtocol (&gEfiSmmConfigurationProtocolGuid
, NULL
, (VOID
**) &SmmConfiguration
);
1055 // Get SMRAM information
1058 Status
= mSmmAccess
->GetCapabilities (mSmmAccess
, &Size
, NULL
);
1059 ASSERT (Status
== EFI_BUFFER_TOO_SMALL
);
1061 gSmmCorePrivate
->SmramRanges
= (EFI_SMRAM_DESCRIPTOR
*)AllocatePool (Size
);
1062 ASSERT (gSmmCorePrivate
->SmramRanges
!= NULL
);
1064 Status
= mSmmAccess
->GetCapabilities (mSmmAccess
, &Size
, gSmmCorePrivate
->SmramRanges
);
1065 ASSERT_EFI_ERROR (Status
);
1067 gSmmCorePrivate
->SmramRangeCount
= Size
/ sizeof (EFI_SMRAM_DESCRIPTOR
);
1070 // Open all SMRAM ranges
1072 Status
= mSmmAccess
->Open (mSmmAccess
);
1073 ASSERT_EFI_ERROR (Status
);
1076 // Print debug message that the SMRAM window is now open.
1078 DEBUG ((DEBUG_INFO
, "SMM IPL opened SMRAM window\n"));
1081 // Subtract SMRAM any reserved SMRAM regions.
1083 if (SmmConfiguration
!= NULL
) {
1084 SmramResRegion
= SmmConfiguration
->SmramReservedRegions
;
1085 while (SmramResRegion
->SmramReservedSize
!= 0) {
1086 for (Index
= 0; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
1087 if ((SmramResRegion
->SmramReservedStart
>= gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
) && \
1088 ((SmramResRegion
->SmramReservedStart
+ SmramResRegion
->SmramReservedSize
) <= \
1089 (gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
+ gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
))) {
1091 // This range has reserved area, calculate the left free size
1093 gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
= SmramResRegion
->SmramReservedStart
- gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
;
1101 // Find the largest SMRAM range between 1MB and 4GB that is at least 256KB - 4K in size
1103 mCurrentSmramRange
= NULL
;
1104 for (Index
= 0, MaxSize
= SIZE_256KB
- EFI_PAGE_SIZE
; Index
< gSmmCorePrivate
->SmramRangeCount
; Index
++) {
1105 if (gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
>= BASE_1MB
) {
1106 if ((gSmmCorePrivate
->SmramRanges
[Index
].CpuStart
+ gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
) <= BASE_4GB
) {
1107 if (gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
>= MaxSize
) {
1108 MaxSize
= gSmmCorePrivate
->SmramRanges
[Index
].PhysicalSize
;
1109 mCurrentSmramRange
= &gSmmCorePrivate
->SmramRanges
[Index
];
1115 if (mCurrentSmramRange
!= NULL
) {
1117 // Print debug message showing SMRAM window that will be used by SMM IPL and SMM Core
1119 DEBUG ((DEBUG_INFO
, "SMM IPL found SMRAM window %p - %p\n",
1120 (VOID
*)(UINTN
)mCurrentSmramRange
->CpuStart
,
1121 (VOID
*)(UINTN
)(mCurrentSmramRange
->CpuStart
+ mCurrentSmramRange
->PhysicalSize
- 1)
1124 GetSmramCacheRange (mCurrentSmramRange
, &mSmramCacheBase
, &mSmramCacheSize
);
1126 // Attempt to set SMRAM cacheability to WB
1128 Status
= gDS
->SetMemorySpaceAttributes(
1133 if (EFI_ERROR (Status
)) {
1134 DEBUG ((DEBUG_WARN
, "SMM IPL failed to set SMRAM window to EFI_MEMORY_WB\n"));
1137 // if Loading module at Fixed Address feature is enabled, save the SMRAM base to Load
1138 // Modules At Fixed Address Configuration Table.
1140 if (PcdGet64(PcdLoadModuleAtFixAddressEnable
) != 0) {
1142 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
1144 SmmCodeSize
= LShiftU64 (PcdGet32(PcdLoadFixAddressSmmCodePageNumber
), EFI_PAGE_SHIFT
);
1146 // The SMRAM available memory is assumed to be larger than SmmCodeSize
1148 ASSERT (mCurrentSmramRange
->PhysicalSize
> SmmCodeSize
);
1150 // Retrieve Load modules At fixed address configuration table and save the SMRAM base.
1152 Status
= EfiGetSystemConfigurationTable (
1153 &gLoadFixedAddressConfigurationTableGuid
,
1154 (VOID
**) &LMFAConfigurationTable
1156 if (!EFI_ERROR (Status
) && LMFAConfigurationTable
!= NULL
) {
1157 LMFAConfigurationTable
->SmramBase
= mCurrentSmramRange
->CpuStart
;
1159 // Print the SMRAM base
1161 DEBUG ((EFI_D_INFO
, "LOADING MODULE FIXED INFO: TSEG BASE is %x. \n", LMFAConfigurationTable
->SmramBase
));
1165 // Load SMM Core into SMRAM and execute it from SMRAM
1167 Status
= ExecuteSmmCoreFromSmram (mCurrentSmramRange
, gSmmCorePrivate
);
1168 if (EFI_ERROR (Status
)) {
1170 // Print error message that the SMM Core failed to be loaded and executed.
1172 DEBUG ((DEBUG_ERROR
, "SMM IPL could not load and execute SMM Core from SMRAM\n"));
1175 // Attempt to reset SMRAM cacheability to UC
1177 Status
= gDS
->SetMemorySpaceAttributes(
1182 if (EFI_ERROR (Status
)) {
1183 DEBUG ((DEBUG_WARN
, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
1188 // Print error message that there are not enough SMRAM resources to load the SMM Core.
1190 DEBUG ((DEBUG_ERROR
, "SMM IPL could not find a large enough SMRAM region to load SMM Core\n"));
1194 // If the SMM Core could not be loaded then close SMRAM window, free allocated
1195 // resources, and return an error so SMM IPL will be unloaded.
1197 if (mCurrentSmramRange
== NULL
|| EFI_ERROR (Status
)) {
1199 // Close all SMRAM ranges
1201 Status
= mSmmAccess
->Close (mSmmAccess
);
1202 ASSERT_EFI_ERROR (Status
);
1205 // Print debug message that the SMRAM window is now closed.
1207 DEBUG ((DEBUG_INFO
, "SMM IPL closed SMRAM window\n"));
1210 // Free all allocated resources
1212 FreePool (gSmmCorePrivate
->SmramRanges
);
1214 return EFI_UNSUPPORTED
;
1218 // Install SMM Base2 Protocol and SMM Communication Protocol
1220 Status
= gBS
->InstallMultipleProtocolInterfaces (
1222 &gEfiSmmBase2ProtocolGuid
, &mSmmBase2
,
1223 &gEfiSmmCommunicationProtocolGuid
, &mSmmCommunication
,
1226 ASSERT_EFI_ERROR (Status
);
1229 // Create the set of protocol and event notififcations that the SMM IPL requires
1231 for (Index
= 0; mSmmIplEvents
[Index
].NotifyFunction
!= NULL
; Index
++) {
1232 if (mSmmIplEvents
[Index
].Protocol
) {
1233 mSmmIplEvents
[Index
].Event
= EfiCreateProtocolNotifyEvent (
1234 mSmmIplEvents
[Index
].Guid
,
1236 mSmmIplEvents
[Index
].NotifyFunction
,
1237 mSmmIplEvents
[Index
].NotifyContext
,
1241 Status
= gBS
->CreateEventEx (
1244 mSmmIplEvents
[Index
].NotifyFunction
,
1245 mSmmIplEvents
[Index
].NotifyContext
,
1246 mSmmIplEvents
[Index
].Guid
,
1247 &mSmmIplEvents
[Index
].Event
1249 ASSERT_EFI_ERROR (Status
);