2 Agent Module to load other modules to deploy SMM Entry Vector for X86 CPU.
4 Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
5 Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
7 This program and the accompanying materials
8 are licensed and made available under the terms and conditions of the BSD License
9 which accompanies this distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17 #include "PiSmmCpuDxeSmm.h"
20 // SMM CPU Private Data structure that contains SMM Configuration Protocol
21 // along its supporting fields.
23 SMM_CPU_PRIVATE_DATA mSmmCpuPrivateData
= {
24 SMM_CPU_PRIVATE_DATA_SIGNATURE
, // Signature
26 NULL
, // Pointer to ProcessorInfo array
27 NULL
, // Pointer to Operation array
28 NULL
, // Pointer to CpuSaveStateSize array
29 NULL
, // Pointer to CpuSaveState array
30 { {0} }, // SmmReservedSmramRegion
32 SmmStartupThisAp
, // SmmCoreEntryContext.SmmStartupThisAp
33 0, // SmmCoreEntryContext.CurrentlyExecutingCpu
34 0, // SmmCoreEntryContext.NumberOfCpus
35 NULL
, // SmmCoreEntryContext.CpuSaveStateSize
36 NULL
// SmmCoreEntryContext.CpuSaveState
40 mSmmCpuPrivateData
.SmmReservedSmramRegion
, // SmmConfiguration.SmramReservedRegions
41 RegisterSmmEntry
// SmmConfiguration.RegisterSmmEntry
45 CPU_HOT_PLUG_DATA mCpuHotPlugData
= {
46 CPU_HOT_PLUG_DATA_REVISION_1
, // Revision
47 0, // Array Length of SmBase and APIC ID
48 NULL
, // Pointer to APIC ID array
49 NULL
, // Pointer to SMBASE array
56 // Global pointer used to access mSmmCpuPrivateData from outside and inside SMM
58 SMM_CPU_PRIVATE_DATA
*gSmmCpuPrivate
= &mSmmCpuPrivateData
;
61 // SMM Relocation variables
63 volatile BOOLEAN
*mRebased
;
64 volatile BOOLEAN mIsBsp
;
67 /// Handle for the SMM CPU Protocol
69 EFI_HANDLE mSmmCpuHandle
= NULL
;
72 /// SMM CPU Protocol instance
74 EFI_SMM_CPU_PROTOCOL mSmmCpu
= {
79 EFI_CPU_INTERRUPT_HANDLER mExternalVectorTable
[EXCEPTION_VECTOR_NUMBER
];
82 // SMM stack information
84 UINTN mSmmStackArrayBase
;
85 UINTN mSmmStackArrayEnd
;
88 UINTN mMaxNumberOfCpus
= 1;
89 UINTN mNumberOfCpus
= 1;
92 // SMM ready to lock flag
94 BOOLEAN mSmmReadyToLock
= FALSE
;
97 // Global used to cache PCD for SMM Code Access Check enable
99 BOOLEAN mSmmCodeAccessCheckEnable
= FALSE
;
102 // Global copy of the PcdPteMemoryEncryptionAddressOrMask
104 UINT64 mAddressEncMask
= 0;
107 // Spin lock used to serialize setting of SMM Code Access Check feature
109 SPIN_LOCK
*mConfigSmmCodeAccessCheckLock
= NULL
;
112 // Saved SMM ranges information
114 EFI_SMRAM_DESCRIPTOR
*mSmmCpuSmramRanges
;
115 UINTN mSmmCpuSmramRangeCount
;
118 Initialize IDT to setup exception handlers for SMM.
127 BOOLEAN InterruptState
;
128 IA32_DESCRIPTOR DxeIdtr
;
131 // There are 32 (not 255) entries in it since only processor
132 // generated exceptions will be handled.
134 gcSmiIdtr
.Limit
= (sizeof(IA32_IDT_GATE_DESCRIPTOR
) * 32) - 1;
136 // Allocate page aligned IDT, because it might be set as read only.
138 gcSmiIdtr
.Base
= (UINTN
)AllocateCodePages (EFI_SIZE_TO_PAGES(gcSmiIdtr
.Limit
+ 1));
139 ASSERT (gcSmiIdtr
.Base
!= 0);
140 ZeroMem ((VOID
*)gcSmiIdtr
.Base
, gcSmiIdtr
.Limit
+ 1);
143 // Disable Interrupt and save DXE IDT table
145 InterruptState
= SaveAndDisableInterrupts ();
146 AsmReadIdtr (&DxeIdtr
);
148 // Load SMM temporary IDT table
150 AsmWriteIdtr (&gcSmiIdtr
);
152 // Setup SMM default exception handlers, SMM IDT table
153 // will be updated and saved in gcSmiIdtr
155 Status
= InitializeCpuExceptionHandlers (NULL
);
156 ASSERT_EFI_ERROR (Status
);
158 // Restore DXE IDT table and CPU interrupt
160 AsmWriteIdtr ((IA32_DESCRIPTOR
*) &DxeIdtr
);
161 SetInterruptState (InterruptState
);
165 Search module name by input IP address and output it.
167 @param CallerIpAddress Caller instruction pointer.
172 IN UINTN CallerIpAddress
181 Pe32Data
= PeCoffSearchImageBase (CallerIpAddress
);
183 DEBUG ((DEBUG_ERROR
, "It is invoked from the instruction before IP(0x%p)", (VOID
*) CallerIpAddress
));
184 PdbPointer
= PeCoffLoaderGetPdbPointer ((VOID
*) Pe32Data
);
185 if (PdbPointer
!= NULL
) {
186 DEBUG ((DEBUG_ERROR
, " in module (%a)\n", PdbPointer
));
192 Read information from the CPU save state.
194 @param This EFI_SMM_CPU_PROTOCOL instance
195 @param Width The number of bytes to read from the CPU save state.
196 @param Register Specifies the CPU register to read form the save state.
197 @param CpuIndex Specifies the zero-based index of the CPU save state.
198 @param Buffer Upon return, this holds the CPU register value read from the save state.
200 @retval EFI_SUCCESS The register was read from Save State
201 @retval EFI_NOT_FOUND The register is not defined for the Save State of Processor
202 @retval EFI_INVALID_PARAMTER This or Buffer is NULL.
208 IN CONST EFI_SMM_CPU_PROTOCOL
*This
,
210 IN EFI_SMM_SAVE_STATE_REGISTER Register
,
218 // Retrieve pointer to the specified CPU's SMM Save State buffer
220 if ((CpuIndex
>= gSmst
->NumberOfCpus
) || (Buffer
== NULL
)) {
221 return EFI_INVALID_PARAMETER
;
225 // Check for special EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID
227 if (Register
== EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID
) {
229 // The pseudo-register only supports the 64-bit size specified by Width.
231 if (Width
!= sizeof (UINT64
)) {
232 return EFI_INVALID_PARAMETER
;
235 // If the processor is in SMM at the time the SMI occurred,
236 // the pseudo register value for EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID is returned in Buffer.
237 // Otherwise, EFI_NOT_FOUND is returned.
239 if (*(mSmmMpSyncData
->CpuData
[CpuIndex
].Present
)) {
240 *(UINT64
*)Buffer
= gSmmCpuPrivate
->ProcessorInfo
[CpuIndex
].ProcessorId
;
243 return EFI_NOT_FOUND
;
247 if (!(*(mSmmMpSyncData
->CpuData
[CpuIndex
].Present
))) {
248 return EFI_INVALID_PARAMETER
;
251 Status
= SmmCpuFeaturesReadSaveStateRegister (CpuIndex
, Register
, Width
, Buffer
);
252 if (Status
== EFI_UNSUPPORTED
) {
253 Status
= ReadSaveStateRegister (CpuIndex
, Register
, Width
, Buffer
);
259 Write data to the CPU save state.
261 @param This EFI_SMM_CPU_PROTOCOL instance
262 @param Width The number of bytes to read from the CPU save state.
263 @param Register Specifies the CPU register to write to the save state.
264 @param CpuIndex Specifies the zero-based index of the CPU save state
265 @param Buffer Upon entry, this holds the new CPU register value.
267 @retval EFI_SUCCESS The register was written from Save State
268 @retval EFI_NOT_FOUND The register is not defined for the Save State of Processor
269 @retval EFI_INVALID_PARAMTER ProcessorIndex or Width is not correct
275 IN CONST EFI_SMM_CPU_PROTOCOL
*This
,
277 IN EFI_SMM_SAVE_STATE_REGISTER Register
,
279 IN CONST VOID
*Buffer
285 // Retrieve pointer to the specified CPU's SMM Save State buffer
287 if ((CpuIndex
>= gSmst
->NumberOfCpus
) || (Buffer
== NULL
)) {
288 return EFI_INVALID_PARAMETER
;
292 // Writes to EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID are ignored
294 if (Register
== EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID
) {
298 if (!mSmmMpSyncData
->CpuData
[CpuIndex
].Present
) {
299 return EFI_INVALID_PARAMETER
;
302 Status
= SmmCpuFeaturesWriteSaveStateRegister (CpuIndex
, Register
, Width
, Buffer
);
303 if (Status
== EFI_UNSUPPORTED
) {
304 Status
= WriteSaveStateRegister (CpuIndex
, Register
, Width
, Buffer
);
311 C function for SMI handler. To change all processor's SMMBase Register.
324 // Update SMM IDT entries' code segment and load IDT
326 AsmWriteIdtr (&gcSmiIdtr
);
327 ApicId
= GetApicId ();
329 ASSERT (mNumberOfCpus
<= mMaxNumberOfCpus
);
331 for (Index
= 0; Index
< mNumberOfCpus
; Index
++) {
332 if (ApicId
== (UINT32
)gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
) {
334 // Initialize SMM specific features on the currently executing CPU
336 SmmCpuFeaturesInitializeProcessor (
339 gSmmCpuPrivate
->ProcessorInfo
,
345 // Check XD and BTS features on each processor on normal boot
347 CheckFeatureSupported ();
352 // BSP rebase is already done above.
353 // Initialize private data during S3 resume
355 InitializeMpSyncData ();
359 // Hook return after RSM to set SMM re-based flag
361 SemaphoreHook (Index
, &mRebased
[Index
]);
370 Relocate SmmBases for each processor.
372 Execute on first boot and all S3 resumes
381 UINT8 BakBuf
[BACK_BUF_SIZE
];
382 SMRAM_SAVE_STATE_MAP BakBuf2
;
383 SMRAM_SAVE_STATE_MAP
*CpuStatePtr
;
390 // Make sure the reserved size is large enough for procedure SmmInitTemplate.
392 ASSERT (sizeof (BakBuf
) >= gcSmmInitSize
);
395 // Patch ASM code template with current CR0, CR3, and CR4 values
397 gSmmCr0
= (UINT32
)AsmReadCr0 ();
398 gSmmCr3
= (UINT32
)AsmReadCr3 ();
399 gSmmCr4
= (UINT32
)AsmReadCr4 ();
402 // Patch GDTR for SMM base relocation
404 gcSmiInitGdtr
.Base
= gcSmiGdtr
.Base
;
405 gcSmiInitGdtr
.Limit
= gcSmiGdtr
.Limit
;
407 U8Ptr
= (UINT8
*)(UINTN
)(SMM_DEFAULT_SMBASE
+ SMM_HANDLER_OFFSET
);
408 CpuStatePtr
= (SMRAM_SAVE_STATE_MAP
*)(UINTN
)(SMM_DEFAULT_SMBASE
+ SMRAM_SAVE_STATE_MAP_OFFSET
);
411 // Backup original contents at address 0x38000
413 CopyMem (BakBuf
, U8Ptr
, sizeof (BakBuf
));
414 CopyMem (&BakBuf2
, CpuStatePtr
, sizeof (BakBuf2
));
417 // Load image for relocation
419 CopyMem (U8Ptr
, gcSmmInitTemplate
, gcSmmInitSize
);
422 // Retrieve the local APIC ID of current processor
424 ApicId
= GetApicId ();
427 // Relocate SM bases for all APs
428 // This is APs' 1st SMI - rebase will be done here, and APs' default SMI handler will be overridden by gcSmmInitTemplate
431 BspIndex
= (UINTN
)-1;
432 for (Index
= 0; Index
< mNumberOfCpus
; Index
++) {
433 mRebased
[Index
] = FALSE
;
434 if (ApicId
!= (UINT32
)gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
) {
435 SendSmiIpi ((UINT32
)gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
);
437 // Wait for this AP to finish its 1st SMI
439 while (!mRebased
[Index
]);
442 // BSP will be Relocated later
449 // Relocate BSP's SMM base
451 ASSERT (BspIndex
!= (UINTN
)-1);
455 // Wait for the BSP to finish its 1st SMI
457 while (!mRebased
[BspIndex
]);
460 // Restore contents at address 0x38000
462 CopyMem (CpuStatePtr
, &BakBuf2
, sizeof (BakBuf2
));
463 CopyMem (U8Ptr
, BakBuf
, sizeof (BakBuf
));
467 SMM Ready To Lock event notification handler.
469 The CPU S3 data is copied to SMRAM for security and mSmmReadyToLock is set to
470 perform additional lock actions that must be performed from SMM on the next SMI.
472 @param[in] Protocol Points to the protocol's unique identifier.
473 @param[in] Interface Points to the interface instance.
474 @param[in] Handle The handle on which the interface was installed.
476 @retval EFI_SUCCESS Notification handler runs successfully.
480 SmmReadyToLockEventNotify (
481 IN CONST EFI_GUID
*Protocol
,
489 // Cache a copy of UEFI memory map before we start profiling feature.
494 // Set SMM ready to lock flag and return
496 mSmmReadyToLock
= TRUE
;
501 The module Entry Point of the CPU SMM driver.
503 @param ImageHandle The firmware allocated handle for the EFI image.
504 @param SystemTable A pointer to the EFI System Table.
506 @retval EFI_SUCCESS The entry point is executed successfully.
507 @retval Other Some error occurs when executing this entry point.
513 IN EFI_HANDLE ImageHandle
,
514 IN EFI_SYSTEM_TABLE
*SystemTable
518 EFI_MP_SERVICES_PROTOCOL
*MpServices
;
519 UINTN NumberOfEnabledProcessors
;
535 // Initialize Debug Agent to support source level debug in SMM code
537 InitializeDebugAgent (DEBUG_AGENT_INIT_SMM
, NULL
, NULL
);
540 // Report the start of CPU SMM initialization.
544 EFI_COMPUTING_UNIT_HOST_PROCESSOR
| EFI_CU_HP_PC_SMM_INIT
548 // Fix segment address of the long-mode-switch jump
550 if (sizeof (UINTN
) == sizeof (UINT64
)) {
551 gSmmJmpAddr
.Segment
= LONG_MODE_CODE_SEGMENT
;
555 // Find out SMRR Base and SMRR Size
557 FindSmramInfo (&mCpuHotPlugData
.SmrrBase
, &mCpuHotPlugData
.SmrrSize
);
560 // Get MP Services Protocol
562 Status
= SystemTable
->BootServices
->LocateProtocol (&gEfiMpServiceProtocolGuid
, NULL
, (VOID
**)&MpServices
);
563 ASSERT_EFI_ERROR (Status
);
566 // Use MP Services Protocol to retrieve the number of processors and number of enabled processors
568 Status
= MpServices
->GetNumberOfProcessors (MpServices
, &mNumberOfCpus
, &NumberOfEnabledProcessors
);
569 ASSERT_EFI_ERROR (Status
);
570 ASSERT (mNumberOfCpus
<= PcdGet32 (PcdCpuMaxLogicalProcessorNumber
));
573 // If support CPU hot plug, PcdCpuSmmEnableBspElection should be set to TRUE.
574 // A constant BSP index makes no sense because it may be hot removed.
577 if (FeaturePcdGet (PcdCpuHotPlugSupport
)) {
579 ASSERT (FeaturePcdGet (PcdCpuSmmEnableBspElection
));
584 // Save the PcdCpuSmmCodeAccessCheckEnable value into a global variable.
586 mSmmCodeAccessCheckEnable
= PcdGetBool (PcdCpuSmmCodeAccessCheckEnable
);
587 DEBUG ((EFI_D_INFO
, "PcdCpuSmmCodeAccessCheckEnable = %d\n", mSmmCodeAccessCheckEnable
));
590 // Save the PcdPteMemoryEncryptionAddressOrMask value into a global variable.
591 // Make sure AddressEncMask is contained to smallest supported address field.
593 mAddressEncMask
= PcdGet64 (PcdPteMemoryEncryptionAddressOrMask
) & PAGING_1G_ADDRESS_MASK_64
;
594 DEBUG ((EFI_D_INFO
, "mAddressEncMask = 0x%lx\n", mAddressEncMask
));
597 // If support CPU hot plug, we need to allocate resources for possibly hot-added processors
599 if (FeaturePcdGet (PcdCpuHotPlugSupport
)) {
600 mMaxNumberOfCpus
= PcdGet32 (PcdCpuMaxLogicalProcessorNumber
);
602 mMaxNumberOfCpus
= mNumberOfCpus
;
604 gSmmCpuPrivate
->SmmCoreEntryContext
.NumberOfCpus
= mMaxNumberOfCpus
;
607 // The CPU save state and code for the SMI entry point are tiled within an SMRAM
608 // allocated buffer. The minimum size of this buffer for a uniprocessor system
609 // is 32 KB, because the entry point is SMBASE + 32KB, and CPU save state area
610 // just below SMBASE + 64KB. If more than one CPU is present in the platform,
611 // then the SMI entry point and the CPU save state areas can be tiles to minimize
612 // the total amount SMRAM required for all the CPUs. The tile size can be computed
613 // by adding the // CPU save state size, any extra CPU specific context, and
614 // the size of code that must be placed at the SMI entry point to transfer
615 // control to a C function in the native SMM execution mode. This size is
616 // rounded up to the nearest power of 2 to give the tile size for a each CPU.
617 // The total amount of memory required is the maximum number of CPUs that
618 // platform supports times the tile size. The picture below shows the tiling,
619 // where m is the number of tiles that fit in 32KB.
621 // +-----------------------------+ <-- 2^n offset from Base of allocated buffer
622 // | CPU m+1 Save State |
623 // +-----------------------------+
624 // | CPU m+1 Extra Data |
625 // +-----------------------------+
627 // +-----------------------------+
628 // | CPU 2m SMI Entry |
629 // +#############################+ <-- Base of allocated buffer + 64 KB
630 // | CPU m-1 Save State |
631 // +-----------------------------+
632 // | CPU m-1 Extra Data |
633 // +-----------------------------+
635 // +-----------------------------+
636 // | CPU 2m-1 SMI Entry |
637 // +=============================+ <-- 2^n offset from Base of allocated buffer
638 // | . . . . . . . . . . . . |
639 // +=============================+ <-- 2^n offset from Base of allocated buffer
640 // | CPU 2 Save State |
641 // +-----------------------------+
642 // | CPU 2 Extra Data |
643 // +-----------------------------+
645 // +-----------------------------+
646 // | CPU m+1 SMI Entry |
647 // +=============================+ <-- Base of allocated buffer + 32 KB
648 // | CPU 1 Save State |
649 // +-----------------------------+
650 // | CPU 1 Extra Data |
651 // +-----------------------------+
653 // +-----------------------------+
654 // | CPU m SMI Entry |
655 // +#############################+ <-- Base of allocated buffer + 32 KB == CPU 0 SMBASE + 64 KB
656 // | CPU 0 Save State |
657 // +-----------------------------+
658 // | CPU 0 Extra Data |
659 // +-----------------------------+
661 // +-----------------------------+
662 // | CPU m-1 SMI Entry |
663 // +=============================+ <-- 2^n offset from Base of allocated buffer
664 // | . . . . . . . . . . . . |
665 // +=============================+ <-- 2^n offset from Base of allocated buffer
667 // +-----------------------------+
668 // | CPU 1 SMI Entry |
669 // +=============================+ <-- 2^n offset from Base of allocated buffer
671 // +-----------------------------+
672 // | CPU 0 SMI Entry |
673 // +#############################+ <-- Base of allocated buffer == CPU 0 SMBASE + 32 KB
677 // Retrieve CPU Family
679 AsmCpuid (CPUID_VERSION_INFO
, &RegEax
, NULL
, NULL
, NULL
);
680 FamilyId
= (RegEax
>> 8) & 0xf;
681 ModelId
= (RegEax
>> 4) & 0xf;
682 if (FamilyId
== 0x06 || FamilyId
== 0x0f) {
683 ModelId
= ModelId
| ((RegEax
>> 12) & 0xf0);
687 AsmCpuid (CPUID_EXTENDED_FUNCTION
, &RegEax
, NULL
, NULL
, NULL
);
688 if (RegEax
>= CPUID_EXTENDED_CPU_SIG
) {
689 AsmCpuid (CPUID_EXTENDED_CPU_SIG
, NULL
, NULL
, NULL
, &RegEdx
);
692 // Determine the mode of the CPU at the time an SMI occurs
693 // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
694 // Volume 3C, Section 34.4.1.1
696 mSmmSaveStateRegisterLma
= EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT
;
697 if ((RegEdx
& BIT29
) != 0) {
698 mSmmSaveStateRegisterLma
= EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT
;
700 if (FamilyId
== 0x06) {
701 if (ModelId
== 0x17 || ModelId
== 0x0f || ModelId
== 0x1c) {
702 mSmmSaveStateRegisterLma
= EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT
;
707 // Compute tile size of buffer required to hold the CPU SMRAM Save State Map, extra CPU
708 // specific context start starts at SMBASE + SMM_PSD_OFFSET, and the SMI entry point.
709 // This size is rounded up to nearest power of 2.
711 TileCodeSize
= GetSmiHandlerSize ();
712 TileCodeSize
= ALIGN_VALUE(TileCodeSize
, SIZE_4KB
);
713 TileDataSize
= (SMRAM_SAVE_STATE_MAP_OFFSET
- SMM_PSD_OFFSET
) + sizeof (SMRAM_SAVE_STATE_MAP
);
714 TileDataSize
= ALIGN_VALUE(TileDataSize
, SIZE_4KB
);
715 TileSize
= TileDataSize
+ TileCodeSize
- 1;
716 TileSize
= 2 * GetPowerOfTwo32 ((UINT32
)TileSize
);
717 DEBUG ((EFI_D_INFO
, "SMRAM TileSize = 0x%08x (0x%08x, 0x%08x)\n", TileSize
, TileCodeSize
, TileDataSize
));
720 // If the TileSize is larger than space available for the SMI Handler of
721 // CPU[i], the extra CPU specific context of CPU[i+1], and the SMRAM Save
722 // State Map of CPU[i+1], then ASSERT(). If this ASSERT() is triggered, then
723 // the SMI Handler size must be reduced or the size of the extra CPU specific
724 // context must be reduced.
726 ASSERT (TileSize
<= (SMRAM_SAVE_STATE_MAP_OFFSET
+ sizeof (SMRAM_SAVE_STATE_MAP
) - SMM_HANDLER_OFFSET
));
729 // Allocate buffer for all of the tiles.
731 // Intel(R) 64 and IA-32 Architectures Software Developer's Manual
732 // Volume 3C, Section 34.11 SMBASE Relocation
733 // For Pentium and Intel486 processors, the SMBASE values must be
734 // aligned on a 32-KByte boundary or the processor will enter shutdown
735 // state during the execution of a RSM instruction.
737 // Intel486 processors: FamilyId is 4
738 // Pentium processors : FamilyId is 5
740 BufferPages
= EFI_SIZE_TO_PAGES (SIZE_32KB
+ TileSize
* (mMaxNumberOfCpus
- 1));
741 if ((FamilyId
== 4) || (FamilyId
== 5)) {
742 Buffer
= AllocateAlignedCodePages (BufferPages
, SIZE_32KB
);
744 Buffer
= AllocateAlignedCodePages (BufferPages
, SIZE_4KB
);
746 ASSERT (Buffer
!= NULL
);
747 DEBUG ((EFI_D_INFO
, "SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer
, EFI_PAGES_TO_SIZE(BufferPages
)));
750 // Allocate buffer for pointers to array in SMM_CPU_PRIVATE_DATA.
752 gSmmCpuPrivate
->ProcessorInfo
= (EFI_PROCESSOR_INFORMATION
*)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION
) * mMaxNumberOfCpus
);
753 ASSERT (gSmmCpuPrivate
->ProcessorInfo
!= NULL
);
755 gSmmCpuPrivate
->Operation
= (SMM_CPU_OPERATION
*)AllocatePool (sizeof (SMM_CPU_OPERATION
) * mMaxNumberOfCpus
);
756 ASSERT (gSmmCpuPrivate
->Operation
!= NULL
);
758 gSmmCpuPrivate
->CpuSaveStateSize
= (UINTN
*)AllocatePool (sizeof (UINTN
) * mMaxNumberOfCpus
);
759 ASSERT (gSmmCpuPrivate
->CpuSaveStateSize
!= NULL
);
761 gSmmCpuPrivate
->CpuSaveState
= (VOID
**)AllocatePool (sizeof (VOID
*) * mMaxNumberOfCpus
);
762 ASSERT (gSmmCpuPrivate
->CpuSaveState
!= NULL
);
764 mSmmCpuPrivateData
.SmmCoreEntryContext
.CpuSaveStateSize
= gSmmCpuPrivate
->CpuSaveStateSize
;
765 mSmmCpuPrivateData
.SmmCoreEntryContext
.CpuSaveState
= gSmmCpuPrivate
->CpuSaveState
;
768 // Allocate buffer for pointers to array in CPU_HOT_PLUG_DATA.
770 mCpuHotPlugData
.ApicId
= (UINT64
*)AllocatePool (sizeof (UINT64
) * mMaxNumberOfCpus
);
771 ASSERT (mCpuHotPlugData
.ApicId
!= NULL
);
772 mCpuHotPlugData
.SmBase
= (UINTN
*)AllocatePool (sizeof (UINTN
) * mMaxNumberOfCpus
);
773 ASSERT (mCpuHotPlugData
.SmBase
!= NULL
);
774 mCpuHotPlugData
.ArrayLength
= (UINT32
)mMaxNumberOfCpus
;
777 // Retrieve APIC ID of each enabled processor from the MP Services protocol.
778 // Also compute the SMBASE address, CPU Save State address, and CPU Save state
779 // size for each CPU in the platform
781 for (Index
= 0; Index
< mMaxNumberOfCpus
; Index
++) {
782 mCpuHotPlugData
.SmBase
[Index
] = (UINTN
)Buffer
+ Index
* TileSize
- SMM_HANDLER_OFFSET
;
783 gSmmCpuPrivate
->CpuSaveStateSize
[Index
] = sizeof(SMRAM_SAVE_STATE_MAP
);
784 gSmmCpuPrivate
->CpuSaveState
[Index
] = (VOID
*)(mCpuHotPlugData
.SmBase
[Index
] + SMRAM_SAVE_STATE_MAP_OFFSET
);
785 gSmmCpuPrivate
->Operation
[Index
] = SmmCpuNone
;
787 if (Index
< mNumberOfCpus
) {
788 Status
= MpServices
->GetProcessorInfo (MpServices
, Index
, &gSmmCpuPrivate
->ProcessorInfo
[Index
]);
789 ASSERT_EFI_ERROR (Status
);
790 mCpuHotPlugData
.ApicId
[Index
] = gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
;
792 DEBUG ((EFI_D_INFO
, "CPU[%03x] APIC ID=%04x SMBASE=%08x SaveState=%08x Size=%08x\n",
794 (UINT32
)gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
,
795 mCpuHotPlugData
.SmBase
[Index
],
796 gSmmCpuPrivate
->CpuSaveState
[Index
],
797 gSmmCpuPrivate
->CpuSaveStateSize
[Index
]
800 gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
= INVALID_APIC_ID
;
801 mCpuHotPlugData
.ApicId
[Index
] = INVALID_APIC_ID
;
806 // Allocate SMI stacks for all processors.
808 if (FeaturePcdGet (PcdCpuSmmStackGuard
)) {
810 // 2 more pages is allocated for each processor.
811 // one is guard page and the other is known good stack.
813 // +-------------------------------------------+-----+-------------------------------------------+
814 // | Known Good Stack | Guard Page | SMM Stack | ... | Known Good Stack | Guard Page | SMM Stack |
815 // +-------------------------------------------+-----+-------------------------------------------+
817 // |<-------------- Processor 0 -------------->| |<-------------- Processor n -------------->|
819 mSmmStackSize
= EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize
)) + 2);
820 Stacks
= (UINT8
*) AllocatePages (gSmmCpuPrivate
->SmmCoreEntryContext
.NumberOfCpus
* (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize
)) + 2));
821 ASSERT (Stacks
!= NULL
);
822 mSmmStackArrayBase
= (UINTN
)Stacks
;
823 mSmmStackArrayEnd
= mSmmStackArrayBase
+ gSmmCpuPrivate
->SmmCoreEntryContext
.NumberOfCpus
* mSmmStackSize
- 1;
825 mSmmStackSize
= PcdGet32 (PcdCpuSmmStackSize
);
826 Stacks
= (UINT8
*) AllocatePages (EFI_SIZE_TO_PAGES (gSmmCpuPrivate
->SmmCoreEntryContext
.NumberOfCpus
* mSmmStackSize
));
827 ASSERT (Stacks
!= NULL
);
831 // Set SMI stack for SMM base relocation
833 gSmmInitStack
= (UINTN
) (Stacks
+ mSmmStackSize
- sizeof (UINTN
));
841 // Relocate SMM Base addresses to the ones allocated from SMRAM
843 mRebased
= (BOOLEAN
*)AllocateZeroPool (sizeof (BOOLEAN
) * mMaxNumberOfCpus
);
844 ASSERT (mRebased
!= NULL
);
848 // Call hook for BSP to perform extra actions in normal mode after all
849 // SMM base addresses have been relocated on all CPUs
851 SmmCpuFeaturesSmmRelocationComplete ();
853 DEBUG ((DEBUG_INFO
, "mXdSupported - 0x%x\n", mXdSupported
));
856 // SMM Time initialization
858 InitializeSmmTimer ();
861 // Initialize MP globals
863 Cr3
= InitializeMpServiceData (Stacks
, mSmmStackSize
);
866 // Fill in SMM Reserved Regions
868 gSmmCpuPrivate
->SmmReservedSmramRegion
[0].SmramReservedStart
= 0;
869 gSmmCpuPrivate
->SmmReservedSmramRegion
[0].SmramReservedSize
= 0;
872 // Install the SMM Configuration Protocol onto a new handle on the handle database.
873 // The entire SMM Configuration Protocol is allocated from SMRAM, so only a pointer
874 // to an SMRAM address will be present in the handle database
876 Status
= SystemTable
->BootServices
->InstallMultipleProtocolInterfaces (
877 &gSmmCpuPrivate
->SmmCpuHandle
,
878 &gEfiSmmConfigurationProtocolGuid
, &gSmmCpuPrivate
->SmmConfiguration
,
881 ASSERT_EFI_ERROR (Status
);
884 // Install the SMM CPU Protocol into SMM protocol database
886 Status
= gSmst
->SmmInstallProtocolInterface (
888 &gEfiSmmCpuProtocolGuid
,
889 EFI_NATIVE_INTERFACE
,
892 ASSERT_EFI_ERROR (Status
);
895 // Expose address of CPU Hot Plug Data structure if CPU hot plug is supported.
897 if (FeaturePcdGet (PcdCpuHotPlugSupport
)) {
898 Status
= PcdSet64S (PcdCpuHotPlugDataAddress
, (UINT64
)(UINTN
)&mCpuHotPlugData
);
899 ASSERT_EFI_ERROR (Status
);
903 // Initialize SMM CPU Services Support
905 Status
= InitializeSmmCpuServices (mSmmCpuHandle
);
906 ASSERT_EFI_ERROR (Status
);
909 // register SMM Ready To Lock Protocol notification
911 Status
= gSmst
->SmmRegisterProtocolNotify (
912 &gEfiSmmReadyToLockProtocolGuid
,
913 SmmReadyToLockEventNotify
,
916 ASSERT_EFI_ERROR (Status
);
919 // Initialize SMM Profile feature
921 InitSmmProfile (Cr3
);
923 GetAcpiS3EnableFlag ();
924 InitSmmS3ResumeState (Cr3
);
926 DEBUG ((EFI_D_INFO
, "SMM CPU Module exit from SMRAM with EFI_SUCCESS\n"));
933 Find out SMRAM information including SMRR base and SMRR size.
935 @param SmrrBase SMRR base
936 @param SmrrSize SMRR size
941 OUT UINT32
*SmrrBase
,
947 EFI_SMM_ACCESS2_PROTOCOL
*SmmAccess
;
948 EFI_SMRAM_DESCRIPTOR
*CurrentSmramRange
;
954 // Get SMM Access Protocol
956 Status
= gBS
->LocateProtocol (&gEfiSmmAccess2ProtocolGuid
, NULL
, (VOID
**)&SmmAccess
);
957 ASSERT_EFI_ERROR (Status
);
960 // Get SMRAM information
963 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, NULL
);
964 ASSERT (Status
== EFI_BUFFER_TOO_SMALL
);
966 mSmmCpuSmramRanges
= (EFI_SMRAM_DESCRIPTOR
*)AllocatePool (Size
);
967 ASSERT (mSmmCpuSmramRanges
!= NULL
);
969 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, mSmmCpuSmramRanges
);
970 ASSERT_EFI_ERROR (Status
);
972 mSmmCpuSmramRangeCount
= Size
/ sizeof (EFI_SMRAM_DESCRIPTOR
);
975 // Find the largest SMRAM range between 1MB and 4GB that is at least 256K - 4K in size
977 CurrentSmramRange
= NULL
;
978 for (Index
= 0, MaxSize
= SIZE_256KB
- EFI_PAGE_SIZE
; Index
< mSmmCpuSmramRangeCount
; Index
++) {
980 // Skip any SMRAM region that is already allocated, needs testing, or needs ECC initialization
982 if ((mSmmCpuSmramRanges
[Index
].RegionState
& (EFI_ALLOCATED
| EFI_NEEDS_TESTING
| EFI_NEEDS_ECC_INITIALIZATION
)) != 0) {
986 if (mSmmCpuSmramRanges
[Index
].CpuStart
>= BASE_1MB
) {
987 if ((mSmmCpuSmramRanges
[Index
].CpuStart
+ mSmmCpuSmramRanges
[Index
].PhysicalSize
) <= SMRR_MAX_ADDRESS
) {
988 if (mSmmCpuSmramRanges
[Index
].PhysicalSize
>= MaxSize
) {
989 MaxSize
= mSmmCpuSmramRanges
[Index
].PhysicalSize
;
990 CurrentSmramRange
= &mSmmCpuSmramRanges
[Index
];
996 ASSERT (CurrentSmramRange
!= NULL
);
998 *SmrrBase
= (UINT32
)CurrentSmramRange
->CpuStart
;
999 *SmrrSize
= (UINT32
)CurrentSmramRange
->PhysicalSize
;
1003 for (Index
= 0; Index
< mSmmCpuSmramRangeCount
; Index
++) {
1004 if (mSmmCpuSmramRanges
[Index
].CpuStart
< *SmrrBase
&&
1005 *SmrrBase
== (mSmmCpuSmramRanges
[Index
].CpuStart
+ mSmmCpuSmramRanges
[Index
].PhysicalSize
)) {
1006 *SmrrBase
= (UINT32
)mSmmCpuSmramRanges
[Index
].CpuStart
;
1007 *SmrrSize
= (UINT32
)(*SmrrSize
+ mSmmCpuSmramRanges
[Index
].PhysicalSize
);
1009 } else if ((*SmrrBase
+ *SmrrSize
) == mSmmCpuSmramRanges
[Index
].CpuStart
&& mSmmCpuSmramRanges
[Index
].PhysicalSize
> 0) {
1010 *SmrrSize
= (UINT32
)(*SmrrSize
+ mSmmCpuSmramRanges
[Index
].PhysicalSize
);
1016 DEBUG ((EFI_D_INFO
, "SMRR Base: 0x%x, SMRR Size: 0x%x\n", *SmrrBase
, *SmrrSize
));
1020 Configure SMM Code Access Check feature on an AP.
1021 SMM Feature Control MSR will be locked after configuration.
1023 @param[in,out] Buffer Pointer to private data buffer.
1027 ConfigSmmCodeAccessCheckOnCurrentProcessor (
1032 UINT64 SmmFeatureControlMsr
;
1033 UINT64 NewSmmFeatureControlMsr
;
1036 // Retrieve the CPU Index from the context passed in
1038 CpuIndex
= *(UINTN
*)Buffer
;
1041 // Get the current SMM Feature Control MSR value
1043 SmmFeatureControlMsr
= SmmCpuFeaturesGetSmmRegister (CpuIndex
, SmmRegFeatureControl
);
1046 // Compute the new SMM Feature Control MSR value
1048 NewSmmFeatureControlMsr
= SmmFeatureControlMsr
;
1049 if (mSmmCodeAccessCheckEnable
) {
1050 NewSmmFeatureControlMsr
|= SMM_CODE_CHK_EN_BIT
;
1051 if (FeaturePcdGet (PcdCpuSmmFeatureControlMsrLock
)) {
1052 NewSmmFeatureControlMsr
|= SMM_FEATURE_CONTROL_LOCK_BIT
;
1057 // Only set the SMM Feature Control MSR value if the new value is different than the current value
1059 if (NewSmmFeatureControlMsr
!= SmmFeatureControlMsr
) {
1060 SmmCpuFeaturesSetSmmRegister (CpuIndex
, SmmRegFeatureControl
, NewSmmFeatureControlMsr
);
1064 // Release the spin lock user to serialize the updates to the SMM Feature Control MSR
1066 ReleaseSpinLock (mConfigSmmCodeAccessCheckLock
);
1070 Configure SMM Code Access Check feature for all processors.
1071 SMM Feature Control MSR will be locked after configuration.
1074 ConfigSmmCodeAccessCheck (
1082 // Check to see if the Feature Control MSR is supported on this CPU
1084 Index
= gSmmCpuPrivate
->SmmCoreEntryContext
.CurrentlyExecutingCpu
;
1085 if (!SmmCpuFeaturesIsSmmRegisterSupported (Index
, SmmRegFeatureControl
)) {
1086 mSmmCodeAccessCheckEnable
= FALSE
;
1091 // Check to see if the CPU supports the SMM Code Access Check feature
1092 // Do not access this MSR unless the CPU supports the SmmRegFeatureControl
1094 if ((AsmReadMsr64 (EFI_MSR_SMM_MCA_CAP
) & SMM_CODE_ACCESS_CHK_BIT
) == 0) {
1095 mSmmCodeAccessCheckEnable
= FALSE
;
1100 // Initialize the lock used to serialize the MSR programming in BSP and all APs
1102 InitializeSpinLock (mConfigSmmCodeAccessCheckLock
);
1105 // Acquire Config SMM Code Access Check spin lock. The BSP will release the
1106 // spin lock when it is done executing ConfigSmmCodeAccessCheckOnCurrentProcessor().
1108 AcquireSpinLock (mConfigSmmCodeAccessCheckLock
);
1111 // Enable SMM Code Access Check feature on the BSP.
1113 ConfigSmmCodeAccessCheckOnCurrentProcessor (&Index
);
1116 // Enable SMM Code Access Check feature for the APs.
1118 for (Index
= 0; Index
< gSmst
->NumberOfCpus
; Index
++) {
1119 if (Index
!= gSmmCpuPrivate
->SmmCoreEntryContext
.CurrentlyExecutingCpu
) {
1120 if (gSmmCpuPrivate
->ProcessorInfo
[Index
].ProcessorId
== INVALID_APIC_ID
) {
1122 // If this processor does not exist
1127 // Acquire Config SMM Code Access Check spin lock. The AP will release the
1128 // spin lock when it is done executing ConfigSmmCodeAccessCheckOnCurrentProcessor().
1130 AcquireSpinLock (mConfigSmmCodeAccessCheckLock
);
1133 // Call SmmStartupThisAp() to enable SMM Code Access Check on an AP.
1135 Status
= gSmst
->SmmStartupThisAp (ConfigSmmCodeAccessCheckOnCurrentProcessor
, Index
, &Index
);
1136 ASSERT_EFI_ERROR (Status
);
1139 // Wait for the AP to release the Config SMM Code Access Check spin lock.
1141 while (!AcquireSpinLockOrFail (mConfigSmmCodeAccessCheckLock
)) {
1146 // Release the Config SMM Code Access Check spin lock.
1148 ReleaseSpinLock (mConfigSmmCodeAccessCheckLock
);
1154 This API provides a way to allocate memory for page table.
1156 This API can be called more once to allocate memory for page tables.
1158 Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
1159 allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
1160 is returned. If there is not enough memory remaining to satisfy the request, then NULL is
1163 @param Pages The number of 4 KB pages to allocate.
1165 @return A pointer to the allocated buffer or NULL if allocation fails.
1169 AllocatePageTableMemory (
1175 Buffer
= SmmCpuFeaturesAllocatePageTableMemory (Pages
);
1176 if (Buffer
!= NULL
) {
1179 return AllocatePages (Pages
);
1183 Allocate pages for code.
1185 @param[in] Pages Number of pages to be allocated.
1187 @return Allocated memory.
1195 EFI_PHYSICAL_ADDRESS Memory
;
1201 Status
= gSmst
->SmmAllocatePages (AllocateAnyPages
, EfiRuntimeServicesCode
, Pages
, &Memory
);
1202 if (EFI_ERROR (Status
)) {
1205 return (VOID
*) (UINTN
) Memory
;
1209 Allocate aligned pages for code.
1211 @param[in] Pages Number of pages to be allocated.
1212 @param[in] Alignment The requested alignment of the allocation.
1213 Must be a power of two.
1214 If Alignment is zero, then byte alignment is used.
1216 @return Allocated memory.
1219 AllocateAlignedCodePages (
1225 EFI_PHYSICAL_ADDRESS Memory
;
1226 UINTN AlignedMemory
;
1227 UINTN AlignmentMask
;
1228 UINTN UnalignedPages
;
1232 // Alignment must be a power of two or zero.
1234 ASSERT ((Alignment
& (Alignment
- 1)) == 0);
1239 if (Alignment
> EFI_PAGE_SIZE
) {
1241 // Calculate the total number of pages since alignment is larger than page size.
1243 AlignmentMask
= Alignment
- 1;
1244 RealPages
= Pages
+ EFI_SIZE_TO_PAGES (Alignment
);
1246 // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow.
1248 ASSERT (RealPages
> Pages
);
1250 Status
= gSmst
->SmmAllocatePages (AllocateAnyPages
, EfiRuntimeServicesCode
, RealPages
, &Memory
);
1251 if (EFI_ERROR (Status
)) {
1254 AlignedMemory
= ((UINTN
) Memory
+ AlignmentMask
) & ~AlignmentMask
;
1255 UnalignedPages
= EFI_SIZE_TO_PAGES (AlignedMemory
- (UINTN
) Memory
);
1256 if (UnalignedPages
> 0) {
1258 // Free first unaligned page(s).
1260 Status
= gSmst
->SmmFreePages (Memory
, UnalignedPages
);
1261 ASSERT_EFI_ERROR (Status
);
1263 Memory
= AlignedMemory
+ EFI_PAGES_TO_SIZE (Pages
);
1264 UnalignedPages
= RealPages
- Pages
- UnalignedPages
;
1265 if (UnalignedPages
> 0) {
1267 // Free last unaligned page(s).
1269 Status
= gSmst
->SmmFreePages (Memory
, UnalignedPages
);
1270 ASSERT_EFI_ERROR (Status
);
1274 // Do not over-allocate pages in this case.
1276 Status
= gSmst
->SmmAllocatePages (AllocateAnyPages
, EfiRuntimeServicesCode
, Pages
, &Memory
);
1277 if (EFI_ERROR (Status
)) {
1280 AlignedMemory
= (UINTN
) Memory
;
1282 return (VOID
*) AlignedMemory
;
1286 Perform the remaining tasks.
1290 PerformRemainingTasks (
1294 if (mSmmReadyToLock
) {
1296 // Start SMM Profile feature
1298 if (FeaturePcdGet (PcdCpuSmmProfileEnable
)) {
1302 // Create a mix of 2MB and 4KB page table. Update some memory ranges absent and execute-disable.
1307 // Mark critical region to be read-only in page table
1309 SetMemMapAttributes ();
1312 // For outside SMRAM, we only map SMM communication buffer or MMIO.
1314 SetUefiMemMapAttributes ();
1317 // Set page table itself to be read-only
1319 SetPageTableAttributes ();
1322 // Configure SMM Code Access Check feature if available.
1324 ConfigSmmCodeAccessCheck ();
1326 SmmCpuFeaturesCompleteSmmReadyToLock ();
1329 // Clean SMM ready to lock flag
1331 mSmmReadyToLock
= FALSE
;
1336 Perform the pre tasks.
1344 RestoreSmmConfigurationInS3 ();