2 SMM Base Helper SMM driver.
4 This driver is the counterpart of the SMM Base On SMM Base2 Thunk driver. It
5 provides helping services in SMM to the SMM Base On SMM Base2 Thunk driver.
7 Caution: This module requires additional review when modified.
8 This driver will have external input - communicate buffer in SMM mode.
9 This external input must be validated carefully to avoid security issue like
10 buffer overflow, integer overflow.
12 SmmHandlerEntry() will receive untrusted input and do validation.
14 Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
15 This program and the accompanying materials
16 are licensed and made available under the terms and conditions of the BSD License
17 which accompanies this distribution. The full text of the license may be found at
18 http://opensource.org/licenses/bsd-license.php
20 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
21 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
26 #include <Library/DebugLib.h>
27 #include <Library/UefiBootServicesTableLib.h>
28 #include <Library/SmmServicesTableLib.h>
29 #include <Library/BaseLib.h>
30 #include <Library/BaseMemoryLib.h>
31 #include <Library/PeCoffLib.h>
32 #include <Library/DevicePathLib.h>
33 #include <Library/CacheMaintenanceLib.h>
34 #include <Library/MemoryAllocationLib.h>
35 #include <Library/SynchronizationLib.h>
36 #include <Library/CpuLib.h>
37 #include <Guid/SmmBaseThunkCommunication.h>
38 #include <Protocol/SmmBaseHelperReady.h>
39 #include <Protocol/SmmCpu.h>
40 #include <Protocol/LoadedImage.h>
41 #include <Protocol/SmmCpuSaveState.h>
42 #include <Protocol/MpService.h>
43 #include <Protocol/LoadPe32Image.h>
44 #include <Protocol/SmmReadyToLock.h>
45 #include <Protocol/SmmAccess2.h>
48 /// Structure for tracking paired information of registered Framework SMI handler
49 /// and correpsonding dispatch handle for SMI handler thunk.
53 EFI_HANDLE DispatchHandle
;
54 EFI_HANDLE SmmImageHandle
;
55 EFI_SMM_CALLBACK_ENTRY_POINT CallbackAddress
;
56 VOID
*CommunicationBuffer
;
62 /// PI SMM CPU Save State register index
64 EFI_SMM_SAVE_STATE_REGISTER Register
;
66 /// Offset in Framework SMST
69 } CPU_SAVE_STATE_CONVERSION
;
71 #define CPU_SAVE_STATE_GET_OFFSET(Field) (UINTN)(&(((EFI_SMM_CPU_SAVE_STATE *) 0)->Ia32SaveState.Field))
74 EFI_HANDLE mDispatchHandle
;
75 EFI_SMM_CPU_PROTOCOL
*mSmmCpu
;
76 EFI_PE32_IMAGE_PROTOCOL
*mLoadPe32Image
;
77 EFI_GUID mEfiSmmCpuIoGuid
= EFI_SMM_CPU_IO_GUID
;
78 EFI_SMM_BASE_HELPER_READY_PROTOCOL
*mSmmBaseHelperReady
;
79 EFI_SMM_SYSTEM_TABLE
*mFrameworkSmst
;
80 UINTN mNumberOfProcessors
;
81 BOOLEAN mLocked
= FALSE
;
82 BOOLEAN mPageTableHookEnabled
;
83 BOOLEAN mHookInitialized
;
84 UINT64
*mCpuStatePageTable
;
87 VOID
*mOriginalHandler
;
88 EFI_SMM_CPU_SAVE_STATE
*mShadowSaveState
;
89 EFI_SMRAM_DESCRIPTOR
*mSmramRanges
;
90 UINTN mSmramRangeCount
;
92 LIST_ENTRY mCallbackInfoListHead
= INITIALIZE_LIST_HEAD_VARIABLE (mCallbackInfoListHead
);
94 CPU_SAVE_STATE_CONVERSION mCpuSaveStateConvTable
[] = {
95 {EFI_SMM_SAVE_STATE_REGISTER_LDTBASE
, CPU_SAVE_STATE_GET_OFFSET(LDTBase
)},
96 {EFI_SMM_SAVE_STATE_REGISTER_ES
, CPU_SAVE_STATE_GET_OFFSET(ES
)},
97 {EFI_SMM_SAVE_STATE_REGISTER_CS
, CPU_SAVE_STATE_GET_OFFSET(CS
)},
98 {EFI_SMM_SAVE_STATE_REGISTER_SS
, CPU_SAVE_STATE_GET_OFFSET(SS
)},
99 {EFI_SMM_SAVE_STATE_REGISTER_DS
, CPU_SAVE_STATE_GET_OFFSET(DS
)},
100 {EFI_SMM_SAVE_STATE_REGISTER_FS
, CPU_SAVE_STATE_GET_OFFSET(FS
)},
101 {EFI_SMM_SAVE_STATE_REGISTER_GS
, CPU_SAVE_STATE_GET_OFFSET(GS
)},
102 {EFI_SMM_SAVE_STATE_REGISTER_TR_SEL
, CPU_SAVE_STATE_GET_OFFSET(TR
)},
103 {EFI_SMM_SAVE_STATE_REGISTER_DR7
, CPU_SAVE_STATE_GET_OFFSET(DR7
)},
104 {EFI_SMM_SAVE_STATE_REGISTER_DR6
, CPU_SAVE_STATE_GET_OFFSET(DR6
)},
105 {EFI_SMM_SAVE_STATE_REGISTER_RAX
, CPU_SAVE_STATE_GET_OFFSET(EAX
)},
106 {EFI_SMM_SAVE_STATE_REGISTER_RBX
, CPU_SAVE_STATE_GET_OFFSET(EBX
)},
107 {EFI_SMM_SAVE_STATE_REGISTER_RCX
, CPU_SAVE_STATE_GET_OFFSET(ECX
)},
108 {EFI_SMM_SAVE_STATE_REGISTER_RDX
, CPU_SAVE_STATE_GET_OFFSET(EDX
)},
109 {EFI_SMM_SAVE_STATE_REGISTER_RSP
, CPU_SAVE_STATE_GET_OFFSET(ESP
)},
110 {EFI_SMM_SAVE_STATE_REGISTER_RBP
, CPU_SAVE_STATE_GET_OFFSET(EBP
)},
111 {EFI_SMM_SAVE_STATE_REGISTER_RSI
, CPU_SAVE_STATE_GET_OFFSET(ESI
)},
112 {EFI_SMM_SAVE_STATE_REGISTER_RDI
, CPU_SAVE_STATE_GET_OFFSET(EDI
)},
113 {EFI_SMM_SAVE_STATE_REGISTER_RIP
, CPU_SAVE_STATE_GET_OFFSET(EIP
)},
114 {EFI_SMM_SAVE_STATE_REGISTER_RFLAGS
, CPU_SAVE_STATE_GET_OFFSET(EFLAGS
)},
115 {EFI_SMM_SAVE_STATE_REGISTER_CR0
, CPU_SAVE_STATE_GET_OFFSET(CR0
)},
116 {EFI_SMM_SAVE_STATE_REGISTER_CR3
, CPU_SAVE_STATE_GET_OFFSET(CR3
)}
124 PageFaultHandlerHook (
129 Read CpuSaveStates from PI for Framework use.
131 The function reads PI style CpuSaveStates of CpuIndex-th CPU for Framework driver use. If
132 ToRead is specified, the CpuSaveStates will be copied to ToRead, otherwise copied to
133 mFrameworkSmst->CpuSaveState[CpuIndex].
135 @param[in] CpuIndex The zero-based CPU index.
136 @param[in, out] ToRead If not NULL, CpuSaveStates will be copied to it.
142 IN OUT EFI_SMM_CPU_SAVE_STATE
*ToRead
147 EFI_SMM_CPU_STATE
*State
;
148 EFI_SMI_CPU_SAVE_STATE
*SaveState
;
150 State
= (EFI_SMM_CPU_STATE
*)gSmst
->CpuSaveState
[CpuIndex
];
151 if (ToRead
!= NULL
) {
152 SaveState
= &ToRead
->Ia32SaveState
;
154 SaveState
= &mFrameworkSmst
->CpuSaveState
[CpuIndex
].Ia32SaveState
;
158 // Note that SMBASE/SMMRevId/IORestart/AutoHALTRestart are in same location in IA32 and X64 CPU Save State Map.
160 SaveState
->SMBASE
= State
->x86
.SMBASE
;
161 SaveState
->SMMRevId
= State
->x86
.SMMRevId
;
162 SaveState
->IORestart
= State
->x86
.IORestart
;
163 SaveState
->AutoHALTRestart
= State
->x86
.AutoHALTRestart
;
165 for (Index
= 0; Index
< sizeof (mCpuSaveStateConvTable
) / sizeof (CPU_SAVE_STATE_CONVERSION
); Index
++) {
167 /// Try to use SMM CPU Protocol to access CPU save states if possible
169 Status
= mSmmCpu
->ReadSaveState (
171 (UINTN
)sizeof (UINT32
),
172 mCpuSaveStateConvTable
[Index
].Register
,
174 ((UINT8
*)SaveState
) + mCpuSaveStateConvTable
[Index
].Offset
176 ASSERT_EFI_ERROR (Status
);
181 Write CpuSaveStates from Framework into PI.
183 The function writes back CpuSaveStates of CpuIndex-th CPU from PI to Framework. If
184 ToWrite is specified, it contains the CpuSaveStates to write from, otherwise CpuSaveStates
185 to write from mFrameworkSmst->CpuSaveState[CpuIndex].
187 @param[in] CpuIndex The zero-based CPU index.
188 @param[in] ToWrite If not NULL, CpuSaveStates to write from.
194 IN EFI_SMM_CPU_SAVE_STATE
*ToWrite
199 EFI_SMM_CPU_STATE
*State
;
200 EFI_SMI_CPU_SAVE_STATE
*SaveState
;
202 State
= (EFI_SMM_CPU_STATE
*)gSmst
->CpuSaveState
[CpuIndex
];
204 if (ToWrite
!= NULL
) {
205 SaveState
= &ToWrite
->Ia32SaveState
;
207 SaveState
= &mFrameworkSmst
->CpuSaveState
[CpuIndex
].Ia32SaveState
;
211 // SMMRevId is read-only.
212 // Note that SMBASE/IORestart/AutoHALTRestart are in same location in IA32 and X64 CPU Save State Map.
214 State
->x86
.SMBASE
= SaveState
->SMBASE
;
215 State
->x86
.IORestart
= SaveState
->IORestart
;
216 State
->x86
.AutoHALTRestart
= SaveState
->AutoHALTRestart
;
218 for (Index
= 0; Index
< sizeof (mCpuSaveStateConvTable
) / sizeof (CPU_SAVE_STATE_CONVERSION
); Index
++) {
219 Status
= mSmmCpu
->WriteSaveState (
221 (UINTN
)sizeof (UINT32
),
222 mCpuSaveStateConvTable
[Index
].Register
,
224 ((UINT8
*)SaveState
) +
225 mCpuSaveStateConvTable
[Index
].Offset
231 Read or write a page that contains CpuSaveStates. Read is from PI to Framework.
232 Write is from Framework to PI.
234 This function reads or writes a page that contains CpuSaveStates. The page contains Framework
235 CpuSaveStates. On read, it reads PI style CpuSaveStates and fill the page up. On write, it
236 writes back from the page content to PI CpuSaveStates struct.
237 The first Framework CpuSaveStates (for CPU 0) is from mFrameworkSmst->CpuSaveState which is
238 page aligned. Because Framework CpuSaveStates are continuous, we can know which CPUs' SaveStates
239 are in the page start from PageAddress.
241 @param[in] PageAddress The base address for a page.
242 @param[in] IsRead TRUE for Read, FALSE for Write.
246 ReadWriteCpuStatePage (
247 IN UINT64 PageAddress
,
251 UINTN FirstSSIndex
; // Index of first CpuSaveState in the page
252 UINTN LastSSIndex
; // Index of last CpuSaveState in the page
253 BOOLEAN FirstSSAligned
; // Whether first CpuSaveState is page-aligned
254 BOOLEAN LastSSAligned
; // Whether the end of last CpuSaveState is page-aligned
258 FirstSSIndex
= ((UINTN
)PageAddress
- (UINTN
)mFrameworkSmst
->CpuSaveState
) / sizeof (EFI_SMM_CPU_SAVE_STATE
);
259 FirstSSAligned
= TRUE
;
260 if (((UINTN
)PageAddress
- (UINTN
)mFrameworkSmst
->CpuSaveState
) % sizeof (EFI_SMM_CPU_SAVE_STATE
) != 0) {
262 FirstSSAligned
= FALSE
;
264 LastSSIndex
= ((UINTN
)PageAddress
+ SIZE_4KB
- (UINTN
)mFrameworkSmst
->CpuSaveState
- 1) / sizeof (EFI_SMM_CPU_SAVE_STATE
);
265 LastSSAligned
= TRUE
;
266 if (((UINTN
)PageAddress
+ SIZE_4KB
- (UINTN
)mFrameworkSmst
->CpuSaveState
) % sizeof (EFI_SMM_CPU_SAVE_STATE
) != 0) {
268 LastSSAligned
= FALSE
;
270 for (CpuIndex
= FirstSSIndex
; CpuIndex
<= LastSSIndex
&& CpuIndex
< mNumberOfProcessors
; CpuIndex
++) {
272 ReadCpuSaveState (CpuIndex
, NULL
);
274 WriteCpuSaveState (CpuIndex
, NULL
);
277 if (!FirstSSAligned
) {
278 ReadCpuSaveState (FirstSSIndex
- 1, mShadowSaveState
);
279 ClippedSize
= (UINTN
)&mFrameworkSmst
->CpuSaveState
[FirstSSIndex
] & (SIZE_4KB
- 1);
281 CopyMem ((VOID
*)(UINTN
)PageAddress
, (VOID
*)((UINTN
)(mShadowSaveState
+ 1) - ClippedSize
), ClippedSize
);
283 CopyMem ((VOID
*)((UINTN
)(mShadowSaveState
+ 1) - ClippedSize
), (VOID
*)(UINTN
)PageAddress
, ClippedSize
);
284 WriteCpuSaveState (FirstSSIndex
- 1, mShadowSaveState
);
287 if (!LastSSAligned
&& LastSSIndex
+ 1 < mNumberOfProcessors
) {
288 ReadCpuSaveState (LastSSIndex
+ 1, mShadowSaveState
);
289 ClippedSize
= SIZE_4KB
- ((UINTN
)&mFrameworkSmst
->CpuSaveState
[LastSSIndex
+ 1] & (SIZE_4KB
- 1));
291 CopyMem (&mFrameworkSmst
->CpuSaveState
[LastSSIndex
+ 1], mShadowSaveState
, ClippedSize
);
293 CopyMem (mShadowSaveState
, &mFrameworkSmst
->CpuSaveState
[LastSSIndex
+ 1], ClippedSize
);
294 WriteCpuSaveState (LastSSIndex
+ 1, mShadowSaveState
);
300 The page fault handler that on-demand read PI CpuSaveStates for framework use. If the fault
301 is not targeted to mFrameworkSmst->CpuSaveState range, the function will return FALSE to let
302 PageFaultHandlerHook know it needs to pass the fault over to original page fault handler.
304 @retval TRUE The page fault is correctly handled.
305 @retval FALSE The page fault is not handled and is passed through to original handler.
316 UINTN NumCpuStatePages
;
318 ASSERT (mPageTableHookEnabled
);
319 AcquireSpinLock (&mPFLock
);
321 PageTable
= (UINT64
*)(UINTN
)(AsmReadCr3 () & mPhyMask
);
322 PFAddress
= AsmReadCr2 ();
323 NumCpuStatePages
= EFI_SIZE_TO_PAGES (mNumberOfProcessors
* sizeof (EFI_SMM_CPU_SAVE_STATE
));
325 if (((UINTN
)mFrameworkSmst
->CpuSaveState
& ~(SIZE_2MB
-1)) == (PFAddress
& ~(SIZE_2MB
-1))) {
326 if ((UINTN
)mFrameworkSmst
->CpuSaveState
<= PFAddress
&&
327 PFAddress
< (UINTN
)mFrameworkSmst
->CpuSaveState
+ EFI_PAGES_TO_SIZE (NumCpuStatePages
)
329 mCpuStatePageTable
[BitFieldRead64 (PFAddress
, 12, 20)] |= BIT0
| BIT1
; // present and rw
331 ReadWriteCpuStatePage (PFAddress
& ~(SIZE_4KB
-1), TRUE
);
338 ReleaseSpinLock (&mPFLock
);
343 Write back the dirty Framework CpuSaveStates to PI.
345 The function scans the page table for dirty pages in mFrameworkSmst->CpuSaveState
346 to write back to PI CpuSaveStates. It is meant to be called on each SmmBaseHelper SMI
347 callback after Framework handler is called.
351 WriteBackDirtyPages (
355 UINTN NumCpuStatePages
;
360 NumCpuStatePages
= EFI_SIZE_TO_PAGES (mNumberOfProcessors
* sizeof (EFI_SMM_CPU_SAVE_STATE
));
361 PTStartIndex
= (UINTN
)BitFieldRead64 ((UINT64
) (UINTN
) mFrameworkSmst
->CpuSaveState
, 12, 20);
362 PTEndIndex
= (UINTN
)BitFieldRead64 ((UINT64
) (UINTN
) mFrameworkSmst
->CpuSaveState
+ EFI_PAGES_TO_SIZE(NumCpuStatePages
) - 1, 12, 20);
363 for (PTIndex
= PTStartIndex
; PTIndex
<= PTEndIndex
; PTIndex
++) {
364 if ((mCpuStatePageTable
[PTIndex
] & (BIT0
|BIT6
)) == (BIT0
|BIT6
)) { // present and dirty?
365 ReadWriteCpuStatePage (mCpuStatePageTable
[PTIndex
] & mPhyMask
, FALSE
);
371 Hook IDT with our page fault handler so that the on-demand paging works on page fault.
373 The function hooks the IDT with PageFaultHandlerHook to get on-demand paging work for
374 PI<->Framework CpuSaveStates marshalling. It also saves original handler for pass-through
379 HookPageFaultHandler (
383 IA32_DESCRIPTOR Idtr
;
384 IA32_IDT_GATE_DESCRIPTOR
*IdtGateDesc
;
387 InitializeSpinLock (&mPFLock
);
390 IdtGateDesc
= (IA32_IDT_GATE_DESCRIPTOR
*) Idtr
.Base
;
391 OffsetUpper
= *(UINT32
*)((UINT64
*)IdtGateDesc
+ 1);
392 mOriginalHandler
= (VOID
*)(UINTN
)(LShiftU64 (OffsetUpper
, 32) + IdtGateDesc
[14].Bits
.OffsetLow
+ (IdtGateDesc
[14].Bits
.OffsetHigh
<< 16));
393 IdtGateDesc
[14].Bits
.OffsetLow
= (UINT32
)((UINTN
)PageFaultHandlerHook
& ((1 << 16) - 1));
394 IdtGateDesc
[14].Bits
.OffsetHigh
= (UINT32
)(((UINTN
)PageFaultHandlerHook
>> 16) & ((1 << 16) - 1));
398 Initialize page table for pages contain HookData.
400 The function initialize PDE for 2MB range that contains HookData. If the related PDE points
401 to a 2MB page, a page table will be allocated and initialized for 4KB pages. Otherwise we juse
402 use the original page table.
404 @param[in] HookData Based on which to initialize page table.
406 @return The pointer to a Page Table that points to 4KB pages which contain HookData.
409 InitCpuStatePageTable (
421 // Initialize physical address mask
422 // NOTE: Physical memory above virtual address limit is not supported !!!
424 AsmCpuid (0x80000008, (UINT32
*)&Index
, NULL
, NULL
, NULL
);
425 mPhyMask
= LShiftU64 (1, (UINT8
)Index
) - 1;
426 mPhyMask
&= (1ull << 48) - EFI_PAGE_SIZE
;
428 HookAddress
= (UINT64
)(UINTN
)HookData
;
429 PageTable
= (UINT64
*)(UINTN
)(AsmReadCr3 () & mPhyMask
);
430 PageTable
= (UINT64
*)(UINTN
)(PageTable
[BitFieldRead64 (HookAddress
, 39, 47)] & mPhyMask
);
431 PageTable
= (UINT64
*)(UINTN
)(PageTable
[BitFieldRead64 (HookAddress
, 30, 38)] & mPhyMask
);
433 Pdpte
= (UINT64
*)(UINTN
)PageTable
;
434 Pde
= Pdpte
[BitFieldRead64 (HookAddress
, 21, 29)];
435 ASSERT ((Pde
& BIT0
) != 0); // Present and 2M Page
437 if ((Pde
& BIT7
) == 0) { // 4KB Page Directory
438 PageTable
= (UINT64
*)(UINTN
)(Pde
& mPhyMask
);
440 ASSERT ((Pde
& mPhyMask
) == (HookAddress
& ~(SIZE_2MB
-1))); // 2MB Page Point to HookAddress
441 PageTable
= AllocatePages (1);
442 ASSERT (PageTable
!= NULL
);
443 Address
= HookAddress
& ~(SIZE_2MB
-1);
444 for (Index
= 0; Index
< 512; Index
++) {
445 PageTable
[Index
] = Address
| BIT0
| BIT1
; // Present and RW
448 Pdpte
[BitFieldRead64 (HookAddress
, 21, 29)] = (UINT64
)(UINTN
)PageTable
| BIT0
| BIT1
; // Present and RW
454 Mark all the CpuSaveStates as not present.
456 The function marks all CpuSaveStates memory range as not present so that page fault can be triggered
457 on CpuSaveStates access. It is meant to be called on each SmmBaseHelper SMI callback before Framework
460 @param[in] CpuSaveState The base of CpuSaveStates.
465 IN EFI_SMM_CPU_SAVE_STATE
*CpuSaveState
472 PTStartIndex
= BitFieldRead64 ((UINTN
)CpuSaveState
, 12, 20);
473 PTEndIndex
= BitFieldRead64 ((UINTN
)CpuSaveState
+ mNumberOfProcessors
* sizeof (EFI_SMM_CPU_SAVE_STATE
) - 1, 12, 20);
474 for (Index
= PTStartIndex
; Index
<= PTEndIndex
; Index
++) {
475 mCpuStatePageTable
[Index
] &= ~(BIT0
|BIT5
|BIT6
); // not present nor accessed nor dirty
480 Framework SMST SmmInstallConfigurationTable() Thunk.
482 This thunk calls the PI SMM SmmInstallConfigurationTable() and then update the configuration
483 table related fields in the Framework SMST because the PI SMM SmmInstallConfigurationTable()
484 function may modify these fields.
486 @param[in] SystemTable A pointer to the SMM System Table.
487 @param[in] Guid A pointer to the GUID for the entry to add, update, or remove.
488 @param[in] Table A pointer to the buffer of the table to add.
489 @param[in] TableSize The size of the table to install.
491 @retval EFI_SUCCESS The (Guid, Table) pair was added, updated, or removed.
492 @retval EFI_INVALID_PARAMETER Guid is not valid.
493 @retval EFI_NOT_FOUND An attempt was made to delete a non-existent entry.
494 @retval EFI_OUT_OF_RESOURCES There is not enough memory available to complete the operation.
498 SmmInstallConfigurationTable (
499 IN EFI_SMM_SYSTEM_TABLE
*SystemTable
,
507 Status
= gSmst
->SmmInstallConfigurationTable (gSmst
, Guid
, Table
, TableSize
);
508 if (!EFI_ERROR (Status
)) {
509 mFrameworkSmst
->NumberOfTableEntries
= gSmst
->NumberOfTableEntries
;
510 mFrameworkSmst
->SmmConfigurationTable
= gSmst
->SmmConfigurationTable
;
516 Initialize all the stuff needed for on-demand paging hooks for PI<->Framework
517 CpuSaveStates marshalling.
519 @param[in] FrameworkSmst Framework SMM system table pointer.
524 IN EFI_SMM_SYSTEM_TABLE
*FrameworkSmst
527 UINTN NumCpuStatePages
;
532 mPageTableHookEnabled
= FALSE
;
533 NumCpuStatePages
= EFI_SIZE_TO_PAGES (mNumberOfProcessors
* sizeof (EFI_SMM_CPU_SAVE_STATE
));
535 // Only hook page table for X64 image and less than 2MB needed to hold all CPU Save States
537 if (EFI_IMAGE_MACHINE_TYPE_SUPPORTED(EFI_IMAGE_MACHINE_X64
) && NumCpuStatePages
<= EFI_SIZE_TO_PAGES (SIZE_2MB
)) {
539 // Allocate double page size to make sure all CPU Save States are in one 2MB page.
541 CpuStatePage
= (UINTN
)AllocatePages (NumCpuStatePages
* 2);
542 ASSERT (CpuStatePage
!= 0);
543 Bottom2MPage
= CpuStatePage
& ~(SIZE_2MB
-1);
544 Top2MPage
= (CpuStatePage
+ EFI_PAGES_TO_SIZE (NumCpuStatePages
* 2) - 1) & ~(SIZE_2MB
-1);
545 if (Bottom2MPage
== Top2MPage
||
546 CpuStatePage
+ EFI_PAGES_TO_SIZE (NumCpuStatePages
* 2) - Top2MPage
>= EFI_PAGES_TO_SIZE (NumCpuStatePages
)
549 // If the allocated 4KB pages are within the same 2MB page or higher portion is larger, use higher portion pages.
551 FrameworkSmst
->CpuSaveState
= (EFI_SMM_CPU_SAVE_STATE
*)(CpuStatePage
+ EFI_PAGES_TO_SIZE (NumCpuStatePages
));
552 FreePages ((VOID
*)CpuStatePage
, NumCpuStatePages
);
554 FrameworkSmst
->CpuSaveState
= (EFI_SMM_CPU_SAVE_STATE
*)CpuStatePage
;
555 FreePages ((VOID
*)(CpuStatePage
+ EFI_PAGES_TO_SIZE (NumCpuStatePages
)), NumCpuStatePages
);
558 // Add temporary working buffer for hooking
560 mShadowSaveState
= (EFI_SMM_CPU_SAVE_STATE
*) AllocatePool (sizeof (EFI_SMM_CPU_SAVE_STATE
));
561 ASSERT (mShadowSaveState
!= NULL
);
563 // Allocate and initialize 4KB Page Table for hooking CpuSaveState.
564 // Replace the original 2MB PDE with new 4KB page table.
566 mCpuStatePageTable
= InitCpuStatePageTable (FrameworkSmst
->CpuSaveState
);
568 // Mark PTE for CpuSaveState as non-exist.
570 HookCpuStateMemory (FrameworkSmst
->CpuSaveState
);
571 HookPageFaultHandler ();
573 mPageTableHookEnabled
= TRUE
;
575 mHookInitialized
= TRUE
;
579 Construct a Framework SMST based on the PI SMM SMST.
581 @return Pointer to the constructed Framework SMST.
583 EFI_SMM_SYSTEM_TABLE
*
584 ConstructFrameworkSmst (
588 EFI_SMM_SYSTEM_TABLE
*FrameworkSmst
;
590 FrameworkSmst
= (EFI_SMM_SYSTEM_TABLE
*)AllocatePool (sizeof (EFI_SMM_SYSTEM_TABLE
));
591 ASSERT (FrameworkSmst
!= NULL
);
594 /// Copy same things from PI SMST to Framework SMST
596 CopyMem (FrameworkSmst
, gSmst
, (UINTN
)(&((EFI_SMM_SYSTEM_TABLE
*)0)->SmmIo
));
598 &FrameworkSmst
->SmmIo
,
600 sizeof (EFI_SMM_SYSTEM_TABLE
) - (UINTN
)(&((EFI_SMM_SYSTEM_TABLE
*)0)->SmmIo
)
604 /// Update Framework SMST
606 FrameworkSmst
->Hdr
.Revision
= EFI_SMM_SYSTEM_TABLE_REVISION
;
607 CopyGuid (&FrameworkSmst
->EfiSmmCpuIoGuid
, &mEfiSmmCpuIoGuid
);
609 mHookInitialized
= FALSE
;
610 FrameworkSmst
->CpuSaveState
= (EFI_SMM_CPU_SAVE_STATE
*)AllocateZeroPool (mNumberOfProcessors
* sizeof (EFI_SMM_CPU_SAVE_STATE
));
611 ASSERT (FrameworkSmst
->CpuSaveState
!= NULL
);
614 /// Do not support floating point state now
616 FrameworkSmst
->CpuOptionalFloatingPointState
= NULL
;
618 FrameworkSmst
->SmmInstallConfigurationTable
= SmmInstallConfigurationTable
;
620 return FrameworkSmst
;
624 Load a given Framework SMM driver into SMRAM and invoke its entry point.
626 @param[in] ParentImageHandle Parent Image Handle.
627 @param[in] FilePath Location of the image to be installed as the handler.
628 @param[in] SourceBuffer Optional source buffer in case the image file
630 @param[in] SourceSize Size of the source image file, if in memory.
631 @param[out] ImageHandle The handle that the base driver uses to decode
632 the handler. Unique among SMM handlers only,
633 not unique across DXE/EFI.
635 @retval EFI_SUCCESS The operation was successful.
636 @retval EFI_OUT_OF_RESOURCES There were no additional SMRAM resources to load the handler
637 @retval EFI_UNSUPPORTED Can not find its copy in normal memory.
638 @retval EFI_INVALID_PARAMETER The handlers was not the correct image type
642 IN EFI_HANDLE ParentImageHandle
,
643 IN EFI_DEVICE_PATH_PROTOCOL
*FilePath
,
644 IN VOID
*SourceBuffer
,
646 OUT EFI_HANDLE
*ImageHandle
652 EFI_PHYSICAL_ADDRESS DstBuffer
;
654 if (FilePath
== NULL
|| ImageHandle
== NULL
) {
655 return EFI_INVALID_PARAMETER
;
660 OrgPageCount
= PageCount
;
661 DstBuffer
= (UINTN
)-1;
662 Status
= gSmst
->SmmAllocatePages (
664 EfiRuntimeServicesCode
,
668 if (EFI_ERROR (Status
)) {
672 Status
= mLoadPe32Image
->LoadPeImage (
682 EFI_LOAD_PE_IMAGE_ATTRIBUTE_NONE
684 if (EFI_ERROR (Status
)) {
685 FreePages ((VOID
*)(UINTN
)DstBuffer
, OrgPageCount
);
687 } while (Status
== EFI_BUFFER_TOO_SMALL
);
689 if (!EFI_ERROR (Status
)) {
691 /// Update MP state in Framework SMST before transferring control to Framework SMM driver entry point
693 mFrameworkSmst
->SmmStartupThisAp
= gSmst
->SmmStartupThisAp
;
694 mFrameworkSmst
->NumberOfCpus
= mNumberOfProcessors
;
695 mFrameworkSmst
->CurrentlyExecutingCpu
= gSmst
->CurrentlyExecutingCpu
;
697 Status
= gBS
->StartImage (*ImageHandle
, NULL
, NULL
);
698 if (EFI_ERROR (Status
)) {
699 mLoadPe32Image
->UnLoadPeImage (mLoadPe32Image
, *ImageHandle
);
701 FreePages ((VOID
*)(UINTN
)DstBuffer
, PageCount
);
709 This function check if the address is in SMRAM.
711 @param Buffer the buffer address to be checked.
712 @param Length the buffer length to be checked.
714 @retval TRUE this address is in SMRAM.
715 @retval FALSE this address is NOT in SMRAM.
719 IN EFI_PHYSICAL_ADDRESS Buffer
,
725 for (Index
= 0; Index
< mSmramRangeCount
; Index
++) {
726 if (((Buffer
>= mSmramRanges
[Index
].CpuStart
) && (Buffer
< mSmramRanges
[Index
].CpuStart
+ mSmramRanges
[Index
].PhysicalSize
)) ||
727 ((mSmramRanges
[Index
].CpuStart
>= Buffer
) && (mSmramRanges
[Index
].CpuStart
< Buffer
+ Length
))) {
736 Thunk service of EFI_SMM_BASE_PROTOCOL.Register().
738 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
742 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
747 if (mLocked
|| FunctionData
->Args
.Register
.LegacyIA32Binary
) {
748 Status
= EFI_UNSUPPORTED
;
751 FunctionData
->SmmBaseImageHandle
,
752 FunctionData
->Args
.Register
.FilePath
,
753 FunctionData
->Args
.Register
.SourceBuffer
,
754 FunctionData
->Args
.Register
.SourceSize
,
755 FunctionData
->Args
.Register
.ImageHandle
758 FunctionData
->Status
= Status
;
762 Thunk service of EFI_SMM_BASE_PROTOCOL.UnRegister().
764 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
768 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
772 /// Unregister not supported now
774 FunctionData
->Status
= EFI_UNSUPPORTED
;
778 Search for Framework SMI handler information according to specific PI SMM dispatch handle.
780 @param[in] DispatchHandle The unique handle assigned by SmiHandlerRegister().
782 @return Pointer to CALLBACK_INFO. If NULL, no callback info record is found.
786 IN EFI_HANDLE DispatchHandle
791 Node
= GetFirstNode (&mCallbackInfoListHead
);
792 while (!IsNull (&mCallbackInfoListHead
, Node
)) {
793 if (((CALLBACK_INFO
*)Node
)->DispatchHandle
== DispatchHandle
) {
794 return (CALLBACK_INFO
*)Node
;
796 Node
= GetNextNode (&mCallbackInfoListHead
, Node
);
802 Callback thunk for Framework SMI handler.
804 This thunk functions calls the Framework SMI handler and converts the return value
805 defined from Framework SMI handlers to a correpsonding return value defined by PI SMM.
807 @param[in] DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
808 @param[in] Context Points to an optional handler context which was specified when the
809 handler was registered.
810 @param[in, out] CommBuffer A pointer to a collection of data in memory that will
811 be conveyed from a non-SMM environment into an SMM environment.
812 @param[in, out] CommBufferSize The size of the CommBuffer.
814 @retval EFI_SUCCESS The interrupt was handled and quiesced. No other handlers
815 should still be called.
816 @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED The interrupt has been quiesced but other handlers should
818 @retval EFI_WARN_INTERRUPT_SOURCE_PENDING The interrupt is still pending and other handlers should still
820 @retval EFI_INTERRUPT_PENDING The interrupt could not be quiesced.
825 IN EFI_HANDLE DispatchHandle
,
826 IN CONST VOID
*Context OPTIONAL
,
827 IN OUT VOID
*CommBuffer OPTIONAL
,
828 IN OUT UINTN
*CommBufferSize OPTIONAL
832 CALLBACK_INFO
*CallbackInfo
;
836 /// Before transferring the control into the Framework SMI handler, update CPU Save States
837 /// and MP states in the Framework SMST.
840 if (!mHookInitialized
) {
841 InitHook (mFrameworkSmst
);
843 if (mPageTableHookEnabled
) {
844 HookCpuStateMemory (mFrameworkSmst
->CpuSaveState
);
847 for (CpuIndex
= 0; CpuIndex
< mNumberOfProcessors
; CpuIndex
++) {
848 ReadCpuSaveState (CpuIndex
, NULL
);
852 mFrameworkSmst
->SmmStartupThisAp
= gSmst
->SmmStartupThisAp
;
853 mFrameworkSmst
->NumberOfCpus
= mNumberOfProcessors
;
854 mFrameworkSmst
->CurrentlyExecutingCpu
= gSmst
->CurrentlyExecutingCpu
;
857 /// Search for Framework SMI handler information
859 CallbackInfo
= GetCallbackInfo (DispatchHandle
);
860 ASSERT (CallbackInfo
!= NULL
);
863 /// Thunk into original Framwork SMI handler
865 Status
= (CallbackInfo
->CallbackAddress
) (
866 CallbackInfo
->SmmImageHandle
,
867 CallbackInfo
->CommunicationBuffer
,
868 CallbackInfo
->SourceSize
871 /// Save CPU Save States in case any of them was modified
873 if (mPageTableHookEnabled
) {
874 WriteBackDirtyPages ();
876 for (CpuIndex
= 0; CpuIndex
< mNumberOfProcessors
; CpuIndex
++) {
877 WriteCpuSaveState (CpuIndex
, NULL
);
882 /// Conversion of returned status code
885 case EFI_HANDLER_SUCCESS
:
886 Status
= EFI_WARN_INTERRUPT_SOURCE_QUIESCED
;
888 case EFI_HANDLER_CRITICAL_EXIT
:
889 case EFI_HANDLER_SOURCE_QUIESCED
:
890 Status
= EFI_SUCCESS
;
892 case EFI_HANDLER_SOURCE_PENDING
:
893 Status
= EFI_WARN_INTERRUPT_SOURCE_PENDING
;
900 Thunk service of EFI_SMM_BASE_PROTOCOL.RegisterCallback().
902 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
906 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
909 CALLBACK_INFO
*Buffer
;
912 FunctionData
->Status
= EFI_UNSUPPORTED
;
917 /// Note that MakeLast and FloatingPointSave options are not supported in PI SMM
921 /// Allocate buffer for callback thunk information
923 Buffer
= (CALLBACK_INFO
*)AllocateZeroPool (sizeof (CALLBACK_INFO
));
924 if (Buffer
== NULL
) {
925 FunctionData
->Status
= EFI_OUT_OF_RESOURCES
;
930 /// Fill SmmImageHandle and CallbackAddress into the thunk
932 Buffer
->SmmImageHandle
= FunctionData
->Args
.RegisterCallback
.SmmImageHandle
;
933 Buffer
->CallbackAddress
= FunctionData
->Args
.RegisterCallback
.CallbackAddress
;
936 /// Register the thunk code as a root SMI handler
938 FunctionData
->Status
= gSmst
->SmiHandlerRegister (
941 &Buffer
->DispatchHandle
943 if (EFI_ERROR (FunctionData
->Status
)) {
949 /// Save this callback info
951 InsertTailList (&mCallbackInfoListHead
, &Buffer
->Link
);
956 Thunk service of EFI_SMM_BASE_PROTOCOL.SmmAllocatePool().
958 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
962 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
966 FunctionData
->Status
= EFI_UNSUPPORTED
;
968 FunctionData
->Status
= gSmst
->SmmAllocatePool (
969 FunctionData
->Args
.AllocatePool
.PoolType
,
970 FunctionData
->Args
.AllocatePool
.Size
,
971 FunctionData
->Args
.AllocatePool
.Buffer
977 Thunk service of EFI_SMM_BASE_PROTOCOL.SmmFreePool().
979 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
983 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
987 FunctionData
->Status
= EFI_UNSUPPORTED
;
989 FreePool (FunctionData
->Args
.FreePool
.Buffer
);
990 FunctionData
->Status
= EFI_SUCCESS
;
995 Thunk service of EFI_SMM_BASE_PROTOCOL.Communicate().
997 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
1001 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
1005 CALLBACK_INFO
*CallbackInfo
;
1007 if (FunctionData
->Args
.Communicate
.CommunicationBuffer
== NULL
) {
1008 FunctionData
->Status
= EFI_INVALID_PARAMETER
;
1012 Node
= GetFirstNode (&mCallbackInfoListHead
);
1013 while (!IsNull (&mCallbackInfoListHead
, Node
)) {
1014 CallbackInfo
= (CALLBACK_INFO
*)Node
;
1016 if (FunctionData
->Args
.Communicate
.ImageHandle
== CallbackInfo
->SmmImageHandle
) {
1017 CallbackInfo
->CommunicationBuffer
= FunctionData
->Args
.Communicate
.CommunicationBuffer
;
1018 CallbackInfo
->SourceSize
= FunctionData
->Args
.Communicate
.SourceSize
;
1021 /// The message was successfully posted.
1023 FunctionData
->Status
= EFI_SUCCESS
;
1026 Node
= GetNextNode (&mCallbackInfoListHead
, Node
);
1029 FunctionData
->Status
= EFI_INVALID_PARAMETER
;
1033 Communication service SMI Handler entry.
1035 This SMI handler provides services for the SMM Base Thunk driver.
1037 Caution: This function may receive untrusted input during runtime.
1038 The communicate buffer is external input, so this function will do operations only if the communicate
1039 buffer is outside of SMRAM so that returning the status code in the buffer won't overwrite anywhere in SMRAM.
1041 @param[in] DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
1042 @param[in] RegisterContext Points to an optional handler context which was specified when the
1043 handler was registered.
1044 @param[in, out] CommBuffer A pointer to a collection of data in memory that will
1045 be conveyed from a non-SMM environment into an SMM environment.
1046 @param[in, out] CommBufferSize The size of the CommBuffer.
1048 @retval EFI_SUCCESS The interrupt was handled and quiesced. No other handlers
1049 should still be called.
1050 @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED The interrupt has been quiesced but other handlers should
1052 @retval EFI_WARN_INTERRUPT_SOURCE_PENDING The interrupt is still pending and other handlers should still
1054 @retval EFI_INTERRUPT_PENDING The interrupt could not be quiesced.
1059 IN EFI_HANDLE DispatchHandle
,
1060 IN CONST VOID
*RegisterContext
,
1061 IN OUT VOID
*CommBuffer
,
1062 IN OUT UINTN
*CommBufferSize
1065 SMMBASE_FUNCTION_DATA
*FunctionData
;
1067 ASSERT (CommBuffer
!= NULL
);
1068 ASSERT (CommBufferSize
!= NULL
);
1070 if (*CommBufferSize
== sizeof (SMMBASE_FUNCTION_DATA
) &&
1071 !IsAddressInSmram ((EFI_PHYSICAL_ADDRESS
)(UINTN
)CommBuffer
, *CommBufferSize
)) {
1072 FunctionData
= (SMMBASE_FUNCTION_DATA
*)CommBuffer
;
1074 switch (FunctionData
->Function
) {
1075 case SmmBaseFunctionRegister
:
1076 Register (FunctionData
);
1078 case SmmBaseFunctionUnregister
:
1079 UnRegister (FunctionData
);
1081 case SmmBaseFunctionRegisterCallback
:
1082 RegisterCallback (FunctionData
);
1084 case SmmBaseFunctionAllocatePool
:
1085 HelperAllocatePool (FunctionData
);
1087 case SmmBaseFunctionFreePool
:
1088 HelperFreePool (FunctionData
);
1090 case SmmBaseFunctionCommunicate
:
1091 HelperCommunicate (FunctionData
);
1094 DEBUG ((EFI_D_WARN
, "SmmBaseHelper: invalid SMM Base function.\n"));
1095 FunctionData
->Status
= EFI_UNSUPPORTED
;
1102 Smm Ready To Lock event notification handler.
1104 It sets a flag indicating that SMRAM has been locked.
1106 @param[in] Protocol Points to the protocol's unique identifier.
1107 @param[in] Interface Points to the interface instance.
1108 @param[in] Handle The handle on which the interface was installed.
1110 @retval EFI_SUCCESS Notification handler runs successfully.
1114 SmmReadyToLockEventNotify (
1115 IN CONST EFI_GUID
*Protocol
,
1117 IN EFI_HANDLE Handle
1125 Entry point function of the SMM Base Helper SMM driver.
1127 @param[in] ImageHandle The firmware allocated handle for the EFI image.
1128 @param[in] SystemTable A pointer to the EFI System Table.
1130 @retval EFI_SUCCESS The entry point is executed successfully.
1131 @retval other Some error occurs when executing this entry point.
1136 IN EFI_HANDLE ImageHandle
,
1137 IN EFI_SYSTEM_TABLE
*SystemTable
1141 EFI_MP_SERVICES_PROTOCOL
*MpServices
;
1143 UINTN NumberOfEnabledProcessors
;
1145 EFI_SMM_ACCESS2_PROTOCOL
*SmmAccess
;
1150 /// Locate SMM CPU Protocol which is used later to retrieve/update CPU Save States
1152 Status
= gSmst
->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid
, NULL
, (VOID
**) &mSmmCpu
);
1153 ASSERT_EFI_ERROR (Status
);
1156 /// Locate PE32 Image Protocol which is used later to load Framework SMM driver
1158 Status
= SystemTable
->BootServices
->LocateProtocol (&gEfiLoadPeImageProtocolGuid
, NULL
, (VOID
**) &mLoadPe32Image
);
1159 ASSERT_EFI_ERROR (Status
);
1162 // Get MP Services Protocol
1164 Status
= SystemTable
->BootServices
->LocateProtocol (&gEfiMpServiceProtocolGuid
, NULL
, (VOID
**)&MpServices
);
1165 ASSERT_EFI_ERROR (Status
);
1168 // Use MP Services Protocol to retrieve the number of processors and number of enabled processors
1170 Status
= MpServices
->GetNumberOfProcessors (MpServices
, &mNumberOfProcessors
, &NumberOfEnabledProcessors
);
1171 ASSERT_EFI_ERROR (Status
);
1174 /// Interface structure of SMM BASE Helper Ready Protocol is allocated from UEFI pool
1175 /// instead of SMM pool so that SMM Base Thunk driver can access it in Non-SMM mode.
1177 Status
= gBS
->AllocatePool (
1178 EfiBootServicesData
,
1179 sizeof (EFI_SMM_BASE_HELPER_READY_PROTOCOL
),
1180 (VOID
**)&mSmmBaseHelperReady
1182 ASSERT_EFI_ERROR (Status
);
1185 /// Construct Framework SMST from PI SMST
1187 mFrameworkSmst
= ConstructFrameworkSmst ();
1188 mSmmBaseHelperReady
->FrameworkSmst
= mFrameworkSmst
;
1189 mSmmBaseHelperReady
->ServiceEntry
= SmmHandlerEntry
;
1192 // Get SMRAM information
1194 Status
= gBS
->LocateProtocol (&gEfiSmmAccess2ProtocolGuid
, NULL
, (VOID
**)&SmmAccess
);
1195 ASSERT_EFI_ERROR (Status
);
1198 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, NULL
);
1199 ASSERT (Status
== EFI_BUFFER_TOO_SMALL
);
1201 Status
= gSmst
->SmmAllocatePool (
1202 EfiRuntimeServicesData
,
1204 (VOID
**)&mSmramRanges
1206 ASSERT_EFI_ERROR (Status
);
1208 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, mSmramRanges
);
1209 ASSERT_EFI_ERROR (Status
);
1211 mSmramRangeCount
= Size
/ sizeof (EFI_SMRAM_DESCRIPTOR
);
1214 // Register SMM Ready To Lock Protocol notification
1216 Status
= gSmst
->SmmRegisterProtocolNotify (
1217 &gEfiSmmReadyToLockProtocolGuid
,
1218 SmmReadyToLockEventNotify
,
1221 ASSERT_EFI_ERROR (Status
);
1224 /// Register SMM Base Helper services for SMM Base Thunk driver
1226 Status
= gSmst
->SmiHandlerRegister (SmmHandlerEntry
, &gEfiSmmBaseThunkCommunicationGuid
, &mDispatchHandle
);
1227 ASSERT_EFI_ERROR (Status
);
1230 /// Install EFI SMM Base Helper Protocol in the UEFI handle database
1232 Status
= gBS
->InstallProtocolInterface (
1234 &gEfiSmmBaseHelperReadyProtocolGuid
,
1235 EFI_NATIVE_INTERFACE
,
1238 ASSERT_EFI_ERROR (Status
);