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 - 2013, 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 This function check if the address refered by Buffer and Length is valid.
738 @param Buffer the buffer address to be checked.
739 @param Length the buffer length to be checked.
741 @retval TRUE this address is valid.
742 @retval FALSE this address is NOT valid.
750 if (Buffer
> (MAX_ADDRESS
- Length
)) {
756 if (IsAddressInSmram ((EFI_PHYSICAL_ADDRESS
)Buffer
, (UINT64
)Length
)) {
763 Thunk service of EFI_SMM_BASE_PROTOCOL.Register().
765 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
769 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
774 if (mLocked
|| FunctionData
->Args
.Register
.LegacyIA32Binary
) {
775 Status
= EFI_UNSUPPORTED
;
778 FunctionData
->SmmBaseImageHandle
,
779 FunctionData
->Args
.Register
.FilePath
,
780 FunctionData
->Args
.Register
.SourceBuffer
,
781 FunctionData
->Args
.Register
.SourceSize
,
782 FunctionData
->Args
.Register
.ImageHandle
785 FunctionData
->Status
= Status
;
789 Thunk service of EFI_SMM_BASE_PROTOCOL.UnRegister().
791 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
795 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
799 /// Unregister not supported now
801 FunctionData
->Status
= EFI_UNSUPPORTED
;
805 Search for Framework SMI handler information according to specific PI SMM dispatch handle.
807 @param[in] DispatchHandle The unique handle assigned by SmiHandlerRegister().
809 @return Pointer to CALLBACK_INFO. If NULL, no callback info record is found.
813 IN EFI_HANDLE DispatchHandle
818 Node
= GetFirstNode (&mCallbackInfoListHead
);
819 while (!IsNull (&mCallbackInfoListHead
, Node
)) {
820 if (((CALLBACK_INFO
*)Node
)->DispatchHandle
== DispatchHandle
) {
821 return (CALLBACK_INFO
*)Node
;
823 Node
= GetNextNode (&mCallbackInfoListHead
, Node
);
829 Callback thunk for Framework SMI handler.
831 This thunk functions calls the Framework SMI handler and converts the return value
832 defined from Framework SMI handlers to a correpsonding return value defined by PI SMM.
834 @param[in] DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
835 @param[in] Context Points to an optional handler context which was specified when the
836 handler was registered.
837 @param[in, out] CommBuffer A pointer to a collection of data in memory that will
838 be conveyed from a non-SMM environment into an SMM environment.
839 @param[in, out] CommBufferSize The size of the CommBuffer.
841 @retval EFI_SUCCESS The interrupt was handled and quiesced. No other handlers
842 should still be called.
843 @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED The interrupt has been quiesced but other handlers should
845 @retval EFI_WARN_INTERRUPT_SOURCE_PENDING The interrupt is still pending and other handlers should still
847 @retval EFI_INTERRUPT_PENDING The interrupt could not be quiesced.
852 IN EFI_HANDLE DispatchHandle
,
853 IN CONST VOID
*Context OPTIONAL
,
854 IN OUT VOID
*CommBuffer OPTIONAL
,
855 IN OUT UINTN
*CommBufferSize OPTIONAL
859 CALLBACK_INFO
*CallbackInfo
;
863 /// Before transferring the control into the Framework SMI handler, update CPU Save States
864 /// and MP states in the Framework SMST.
867 if (!mHookInitialized
) {
868 InitHook (mFrameworkSmst
);
870 if (mPageTableHookEnabled
) {
871 HookCpuStateMemory (mFrameworkSmst
->CpuSaveState
);
874 for (CpuIndex
= 0; CpuIndex
< mNumberOfProcessors
; CpuIndex
++) {
875 ReadCpuSaveState (CpuIndex
, NULL
);
879 mFrameworkSmst
->SmmStartupThisAp
= gSmst
->SmmStartupThisAp
;
880 mFrameworkSmst
->NumberOfCpus
= mNumberOfProcessors
;
881 mFrameworkSmst
->CurrentlyExecutingCpu
= gSmst
->CurrentlyExecutingCpu
;
884 /// Search for Framework SMI handler information
886 CallbackInfo
= GetCallbackInfo (DispatchHandle
);
887 ASSERT (CallbackInfo
!= NULL
);
890 /// Thunk into original Framwork SMI handler
892 Status
= (CallbackInfo
->CallbackAddress
) (
893 CallbackInfo
->SmmImageHandle
,
894 CallbackInfo
->CommunicationBuffer
,
895 CallbackInfo
->SourceSize
898 /// Save CPU Save States in case any of them was modified
900 if (mPageTableHookEnabled
) {
901 WriteBackDirtyPages ();
903 for (CpuIndex
= 0; CpuIndex
< mNumberOfProcessors
; CpuIndex
++) {
904 WriteCpuSaveState (CpuIndex
, NULL
);
909 /// Conversion of returned status code
912 case EFI_HANDLER_SUCCESS
:
913 Status
= EFI_WARN_INTERRUPT_SOURCE_QUIESCED
;
915 case EFI_HANDLER_CRITICAL_EXIT
:
916 case EFI_HANDLER_SOURCE_QUIESCED
:
917 Status
= EFI_SUCCESS
;
919 case EFI_HANDLER_SOURCE_PENDING
:
920 Status
= EFI_WARN_INTERRUPT_SOURCE_PENDING
;
927 Thunk service of EFI_SMM_BASE_PROTOCOL.RegisterCallback().
929 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
933 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
936 CALLBACK_INFO
*Buffer
;
939 FunctionData
->Status
= EFI_UNSUPPORTED
;
944 /// Note that MakeLast and FloatingPointSave options are not supported in PI SMM
948 /// Allocate buffer for callback thunk information
950 Buffer
= (CALLBACK_INFO
*)AllocateZeroPool (sizeof (CALLBACK_INFO
));
951 if (Buffer
== NULL
) {
952 FunctionData
->Status
= EFI_OUT_OF_RESOURCES
;
957 /// Fill SmmImageHandle and CallbackAddress into the thunk
959 Buffer
->SmmImageHandle
= FunctionData
->Args
.RegisterCallback
.SmmImageHandle
;
960 Buffer
->CallbackAddress
= FunctionData
->Args
.RegisterCallback
.CallbackAddress
;
963 /// Register the thunk code as a root SMI handler
965 FunctionData
->Status
= gSmst
->SmiHandlerRegister (
968 &Buffer
->DispatchHandle
970 if (EFI_ERROR (FunctionData
->Status
)) {
976 /// Save this callback info
978 InsertTailList (&mCallbackInfoListHead
, &Buffer
->Link
);
983 Thunk service of EFI_SMM_BASE_PROTOCOL.SmmAllocatePool().
985 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
989 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
993 FunctionData
->Status
= EFI_UNSUPPORTED
;
995 FunctionData
->Status
= gSmst
->SmmAllocatePool (
996 FunctionData
->Args
.AllocatePool
.PoolType
,
997 FunctionData
->Args
.AllocatePool
.Size
,
998 FunctionData
->Args
.AllocatePool
.Buffer
1004 Thunk service of EFI_SMM_BASE_PROTOCOL.SmmFreePool().
1006 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
1010 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
1014 FunctionData
->Status
= EFI_UNSUPPORTED
;
1016 FreePool (FunctionData
->Args
.FreePool
.Buffer
);
1017 FunctionData
->Status
= EFI_SUCCESS
;
1022 Thunk service of EFI_SMM_BASE_PROTOCOL.Communicate().
1024 @param[in, out] FunctionData Pointer to SMMBASE_FUNCTION_DATA.
1028 IN OUT SMMBASE_FUNCTION_DATA
*FunctionData
1032 CALLBACK_INFO
*CallbackInfo
;
1034 if (FunctionData
->Args
.Communicate
.CommunicationBuffer
== NULL
) {
1035 FunctionData
->Status
= EFI_INVALID_PARAMETER
;
1039 Node
= GetFirstNode (&mCallbackInfoListHead
);
1040 while (!IsNull (&mCallbackInfoListHead
, Node
)) {
1041 CallbackInfo
= (CALLBACK_INFO
*)Node
;
1043 if (FunctionData
->Args
.Communicate
.ImageHandle
== CallbackInfo
->SmmImageHandle
) {
1044 CallbackInfo
->CommunicationBuffer
= FunctionData
->Args
.Communicate
.CommunicationBuffer
;
1045 CallbackInfo
->SourceSize
= FunctionData
->Args
.Communicate
.SourceSize
;
1048 /// The message was successfully posted.
1050 FunctionData
->Status
= EFI_SUCCESS
;
1053 Node
= GetNextNode (&mCallbackInfoListHead
, Node
);
1056 FunctionData
->Status
= EFI_INVALID_PARAMETER
;
1060 Communication service SMI Handler entry.
1062 This SMI handler provides services for the SMM Base Thunk driver.
1064 Caution: This function may receive untrusted input during runtime.
1065 The communicate buffer is external input, so this function will do operations only if the communicate
1066 buffer is outside of SMRAM so that returning the status code in the buffer won't overwrite anywhere in SMRAM.
1068 @param[in] DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
1069 @param[in] RegisterContext Points to an optional handler context which was specified when the
1070 handler was registered.
1071 @param[in, out] CommBuffer A pointer to a collection of data in memory that will
1072 be conveyed from a non-SMM environment into an SMM environment.
1073 @param[in, out] CommBufferSize The size of the CommBuffer.
1075 @retval EFI_SUCCESS The interrupt was handled and quiesced. No other handlers
1076 should still be called.
1077 @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED The interrupt has been quiesced but other handlers should
1079 @retval EFI_WARN_INTERRUPT_SOURCE_PENDING The interrupt is still pending and other handlers should still
1081 @retval EFI_INTERRUPT_PENDING The interrupt could not be quiesced.
1086 IN EFI_HANDLE DispatchHandle
,
1087 IN CONST VOID
*RegisterContext
,
1088 IN OUT VOID
*CommBuffer
,
1089 IN OUT UINTN
*CommBufferSize
1092 SMMBASE_FUNCTION_DATA
*FunctionData
;
1094 ASSERT (CommBuffer
!= NULL
);
1095 ASSERT (CommBufferSize
!= NULL
);
1097 if (*CommBufferSize
== sizeof (SMMBASE_FUNCTION_DATA
) &&
1098 IsAddressValid ((UINTN
)CommBuffer
, *CommBufferSize
)) {
1099 FunctionData
= (SMMBASE_FUNCTION_DATA
*)CommBuffer
;
1101 switch (FunctionData
->Function
) {
1102 case SmmBaseFunctionRegister
:
1103 Register (FunctionData
);
1105 case SmmBaseFunctionUnregister
:
1106 UnRegister (FunctionData
);
1108 case SmmBaseFunctionRegisterCallback
:
1109 RegisterCallback (FunctionData
);
1111 case SmmBaseFunctionAllocatePool
:
1112 HelperAllocatePool (FunctionData
);
1114 case SmmBaseFunctionFreePool
:
1115 HelperFreePool (FunctionData
);
1117 case SmmBaseFunctionCommunicate
:
1118 HelperCommunicate (FunctionData
);
1121 DEBUG ((EFI_D_WARN
, "SmmBaseHelper: invalid SMM Base function.\n"));
1122 FunctionData
->Status
= EFI_UNSUPPORTED
;
1129 Smm Ready To Lock event notification handler.
1131 It sets a flag indicating that SMRAM has been locked.
1133 @param[in] Protocol Points to the protocol's unique identifier.
1134 @param[in] Interface Points to the interface instance.
1135 @param[in] Handle The handle on which the interface was installed.
1137 @retval EFI_SUCCESS Notification handler runs successfully.
1141 SmmReadyToLockEventNotify (
1142 IN CONST EFI_GUID
*Protocol
,
1144 IN EFI_HANDLE Handle
1152 Entry point function of the SMM Base Helper SMM driver.
1154 @param[in] ImageHandle The firmware allocated handle for the EFI image.
1155 @param[in] SystemTable A pointer to the EFI System Table.
1157 @retval EFI_SUCCESS The entry point is executed successfully.
1158 @retval other Some error occurs when executing this entry point.
1163 IN EFI_HANDLE ImageHandle
,
1164 IN EFI_SYSTEM_TABLE
*SystemTable
1168 EFI_MP_SERVICES_PROTOCOL
*MpServices
;
1170 UINTN NumberOfEnabledProcessors
;
1172 EFI_SMM_ACCESS2_PROTOCOL
*SmmAccess
;
1177 /// Locate SMM CPU Protocol which is used later to retrieve/update CPU Save States
1179 Status
= gSmst
->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid
, NULL
, (VOID
**) &mSmmCpu
);
1180 ASSERT_EFI_ERROR (Status
);
1183 /// Locate PE32 Image Protocol which is used later to load Framework SMM driver
1185 Status
= SystemTable
->BootServices
->LocateProtocol (&gEfiLoadPeImageProtocolGuid
, NULL
, (VOID
**) &mLoadPe32Image
);
1186 ASSERT_EFI_ERROR (Status
);
1189 // Get MP Services Protocol
1191 Status
= SystemTable
->BootServices
->LocateProtocol (&gEfiMpServiceProtocolGuid
, NULL
, (VOID
**)&MpServices
);
1192 ASSERT_EFI_ERROR (Status
);
1195 // Use MP Services Protocol to retrieve the number of processors and number of enabled processors
1197 Status
= MpServices
->GetNumberOfProcessors (MpServices
, &mNumberOfProcessors
, &NumberOfEnabledProcessors
);
1198 ASSERT_EFI_ERROR (Status
);
1201 /// Interface structure of SMM BASE Helper Ready Protocol is allocated from UEFI pool
1202 /// instead of SMM pool so that SMM Base Thunk driver can access it in Non-SMM mode.
1204 Status
= gBS
->AllocatePool (
1205 EfiBootServicesData
,
1206 sizeof (EFI_SMM_BASE_HELPER_READY_PROTOCOL
),
1207 (VOID
**)&mSmmBaseHelperReady
1209 ASSERT_EFI_ERROR (Status
);
1212 /// Construct Framework SMST from PI SMST
1214 mFrameworkSmst
= ConstructFrameworkSmst ();
1215 mSmmBaseHelperReady
->FrameworkSmst
= mFrameworkSmst
;
1216 mSmmBaseHelperReady
->ServiceEntry
= SmmHandlerEntry
;
1219 // Get SMRAM information
1221 Status
= gBS
->LocateProtocol (&gEfiSmmAccess2ProtocolGuid
, NULL
, (VOID
**)&SmmAccess
);
1222 ASSERT_EFI_ERROR (Status
);
1225 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, NULL
);
1226 ASSERT (Status
== EFI_BUFFER_TOO_SMALL
);
1228 Status
= gSmst
->SmmAllocatePool (
1229 EfiRuntimeServicesData
,
1231 (VOID
**)&mSmramRanges
1233 ASSERT_EFI_ERROR (Status
);
1235 Status
= SmmAccess
->GetCapabilities (SmmAccess
, &Size
, mSmramRanges
);
1236 ASSERT_EFI_ERROR (Status
);
1238 mSmramRangeCount
= Size
/ sizeof (EFI_SMRAM_DESCRIPTOR
);
1241 // Register SMM Ready To Lock Protocol notification
1243 Status
= gSmst
->SmmRegisterProtocolNotify (
1244 &gEfiSmmReadyToLockProtocolGuid
,
1245 SmmReadyToLockEventNotify
,
1248 ASSERT_EFI_ERROR (Status
);
1251 /// Register SMM Base Helper services for SMM Base Thunk driver
1253 Status
= gSmst
->SmiHandlerRegister (SmmHandlerEntry
, &gEfiSmmBaseThunkCommunicationGuid
, &mDispatchHandle
);
1254 ASSERT_EFI_ERROR (Status
);
1257 /// Install EFI SMM Base Helper Protocol in the UEFI handle database
1259 Status
= gBS
->InstallProtocolInterface (
1261 &gEfiSmmBaseHelperReadyProtocolGuid
,
1262 EFI_NATIVE_INTERFACE
,
1265 ASSERT_EFI_ERROR (Status
);