]> git.proxmox.com Git - mirror_edk2.git/blame - UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
UefiCpuPkg/PiSmmCpuDxeSmm: Update to consume SpeculationBarrier
[mirror_edk2.git] / UefiCpuPkg / PiSmmCpuDxeSmm / PiSmmCpuDxeSmm.c
CommitLineData
529a5a86
MK
1/** @file\r
2Agent Module to load other modules to deploy SMM Entry Vector for X86 CPU.\r
3\r
e21e355e 4Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>\r
241f9149
LD
5Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>\r
6\r
529a5a86
MK
7This program and the accompanying materials\r
8are licensed and made available under the terms and conditions of the BSD License\r
9which accompanies this distribution. The full text of the license may be found at\r
10http://opensource.org/licenses/bsd-license.php\r
11\r
12THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
13WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
14\r
15**/\r
16\r
17#include "PiSmmCpuDxeSmm.h"\r
18\r
19//\r
20// SMM CPU Private Data structure that contains SMM Configuration Protocol\r
21// along its supporting fields.\r
22//\r
23SMM_CPU_PRIVATE_DATA mSmmCpuPrivateData = {\r
24 SMM_CPU_PRIVATE_DATA_SIGNATURE, // Signature\r
25 NULL, // SmmCpuHandle\r
26 NULL, // Pointer to ProcessorInfo array\r
27 NULL, // Pointer to Operation array\r
28 NULL, // Pointer to CpuSaveStateSize array\r
29 NULL, // Pointer to CpuSaveState array\r
30 { {0} }, // SmmReservedSmramRegion\r
31 {\r
32 SmmStartupThisAp, // SmmCoreEntryContext.SmmStartupThisAp\r
33 0, // SmmCoreEntryContext.CurrentlyExecutingCpu\r
34 0, // SmmCoreEntryContext.NumberOfCpus\r
35 NULL, // SmmCoreEntryContext.CpuSaveStateSize\r
36 NULL // SmmCoreEntryContext.CpuSaveState\r
37 },\r
38 NULL, // SmmCoreEntry\r
39 {\r
40 mSmmCpuPrivateData.SmmReservedSmramRegion, // SmmConfiguration.SmramReservedRegions\r
41 RegisterSmmEntry // SmmConfiguration.RegisterSmmEntry\r
42 },\r
43};\r
44\r
45CPU_HOT_PLUG_DATA mCpuHotPlugData = {\r
46 CPU_HOT_PLUG_DATA_REVISION_1, // Revision\r
47 0, // Array Length of SmBase and APIC ID\r
48 NULL, // Pointer to APIC ID array\r
49 NULL, // Pointer to SMBASE array\r
50 0, // Reserved\r
51 0, // SmrrBase\r
52 0 // SmrrSize\r
53};\r
54\r
55//\r
56// Global pointer used to access mSmmCpuPrivateData from outside and inside SMM\r
57//\r
58SMM_CPU_PRIVATE_DATA *gSmmCpuPrivate = &mSmmCpuPrivateData;\r
59\r
60//\r
61// SMM Relocation variables\r
62//\r
63volatile BOOLEAN *mRebased;\r
64volatile BOOLEAN mIsBsp;\r
65\r
66///\r
67/// Handle for the SMM CPU Protocol\r
68///\r
69EFI_HANDLE mSmmCpuHandle = NULL;\r
70\r
71///\r
72/// SMM CPU Protocol instance\r
73///\r
74EFI_SMM_CPU_PROTOCOL mSmmCpu = {\r
75 SmmReadSaveState,\r
76 SmmWriteSaveState\r
77};\r
78\r
827330cc
JW
79///\r
80/// SMM Memory Attribute Protocol instance\r
81///\r
82EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL mSmmMemoryAttribute = {\r
83 EdkiiSmmGetMemoryAttributes,\r
84 EdkiiSmmSetMemoryAttributes,\r
85 EdkiiSmmClearMemoryAttributes\r
86};\r
87\r
529a5a86
MK
88EFI_CPU_INTERRUPT_HANDLER mExternalVectorTable[EXCEPTION_VECTOR_NUMBER];\r
89\r
529a5a86
MK
90//\r
91// SMM stack information\r
92//\r
93UINTN mSmmStackArrayBase;\r
94UINTN mSmmStackArrayEnd;\r
95UINTN mSmmStackSize;\r
96\r
529a5a86
MK
97UINTN mMaxNumberOfCpus = 1;\r
98UINTN mNumberOfCpus = 1;\r
99\r
100//\r
101// SMM ready to lock flag\r
102//\r
103BOOLEAN mSmmReadyToLock = FALSE;\r
104\r
105//\r
106// Global used to cache PCD for SMM Code Access Check enable\r
107//\r
108BOOLEAN mSmmCodeAccessCheckEnable = FALSE;\r
109\r
241f9149
LD
110//\r
111// Global copy of the PcdPteMemoryEncryptionAddressOrMask\r
112//\r
113UINT64 mAddressEncMask = 0;\r
114\r
529a5a86
MK
115//\r
116// Spin lock used to serialize setting of SMM Code Access Check feature\r
117//\r
fe3a75bc 118SPIN_LOCK *mConfigSmmCodeAccessCheckLock = NULL;\r
529a5a86 119\r
7ed6f781
JF
120//\r
121// Saved SMM ranges information\r
122//\r
123EFI_SMRAM_DESCRIPTOR *mSmmCpuSmramRanges;\r
124UINTN mSmmCpuSmramRangeCount;\r
125\r
51ce27fd
SZ
126UINT8 mPhysicalAddressBits;\r
127\r
351b49c1
LE
128//\r
129// Control register contents saved for SMM S3 resume state initialization.\r
130//\r
f0053e83 131UINT32 mSmmCr0;\r
351b49c1
LE
132UINT32 mSmmCr4;\r
133\r
529a5a86
MK
134/**\r
135 Initialize IDT to setup exception handlers for SMM.\r
136\r
137**/\r
138VOID\r
139InitializeSmmIdt (\r
140 VOID\r
141 )\r
142{\r
143 EFI_STATUS Status;\r
144 BOOLEAN InterruptState;\r
145 IA32_DESCRIPTOR DxeIdtr;\r
717fb604
JY
146\r
147 //\r
148 // There are 32 (not 255) entries in it since only processor\r
149 // generated exceptions will be handled.\r
150 //\r
151 gcSmiIdtr.Limit = (sizeof(IA32_IDT_GATE_DESCRIPTOR) * 32) - 1;\r
152 //\r
153 // Allocate page aligned IDT, because it might be set as read only.\r
154 //\r
155 gcSmiIdtr.Base = (UINTN)AllocateCodePages (EFI_SIZE_TO_PAGES(gcSmiIdtr.Limit + 1));\r
156 ASSERT (gcSmiIdtr.Base != 0);\r
157 ZeroMem ((VOID *)gcSmiIdtr.Base, gcSmiIdtr.Limit + 1);\r
158\r
529a5a86
MK
159 //\r
160 // Disable Interrupt and save DXE IDT table\r
161 //\r
162 InterruptState = SaveAndDisableInterrupts ();\r
163 AsmReadIdtr (&DxeIdtr);\r
164 //\r
165 // Load SMM temporary IDT table\r
166 //\r
167 AsmWriteIdtr (&gcSmiIdtr);\r
168 //\r
169 // Setup SMM default exception handlers, SMM IDT table\r
170 // will be updated and saved in gcSmiIdtr\r
171 //\r
172 Status = InitializeCpuExceptionHandlers (NULL);\r
173 ASSERT_EFI_ERROR (Status);\r
174 //\r
175 // Restore DXE IDT table and CPU interrupt\r
176 //\r
177 AsmWriteIdtr ((IA32_DESCRIPTOR *) &DxeIdtr);\r
178 SetInterruptState (InterruptState);\r
179}\r
180\r
181/**\r
182 Search module name by input IP address and output it.\r
183\r
184 @param CallerIpAddress Caller instruction pointer.\r
185\r
186**/\r
187VOID\r
188DumpModuleInfoByIp (\r
189 IN UINTN CallerIpAddress\r
190 )\r
191{\r
192 UINTN Pe32Data;\r
529a5a86 193 VOID *PdbPointer;\r
529a5a86
MK
194\r
195 //\r
196 // Find Image Base\r
197 //\r
9e981317 198 Pe32Data = PeCoffSearchImageBase (CallerIpAddress);\r
529a5a86 199 if (Pe32Data != 0) {\r
b8caae19 200 DEBUG ((DEBUG_ERROR, "It is invoked from the instruction before IP(0x%p)", (VOID *) CallerIpAddress));\r
529a5a86
MK
201 PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *) Pe32Data);\r
202 if (PdbPointer != NULL) {\r
b8caae19 203 DEBUG ((DEBUG_ERROR, " in module (%a)\n", PdbPointer));\r
529a5a86
MK
204 }\r
205 }\r
206}\r
207\r
208/**\r
209 Read information from the CPU save state.\r
210\r
211 @param This EFI_SMM_CPU_PROTOCOL instance\r
212 @param Width The number of bytes to read from the CPU save state.\r
213 @param Register Specifies the CPU register to read form the save state.\r
214 @param CpuIndex Specifies the zero-based index of the CPU save state.\r
215 @param Buffer Upon return, this holds the CPU register value read from the save state.\r
216\r
217 @retval EFI_SUCCESS The register was read from Save State\r
218 @retval EFI_NOT_FOUND The register is not defined for the Save State of Processor\r
219 @retval EFI_INVALID_PARAMTER This or Buffer is NULL.\r
220\r
221**/\r
222EFI_STATUS\r
223EFIAPI\r
224SmmReadSaveState (\r
225 IN CONST EFI_SMM_CPU_PROTOCOL *This,\r
226 IN UINTN Width,\r
227 IN EFI_SMM_SAVE_STATE_REGISTER Register,\r
228 IN UINTN CpuIndex,\r
229 OUT VOID *Buffer\r
230 )\r
231{\r
232 EFI_STATUS Status;\r
233\r
234 //\r
235 // Retrieve pointer to the specified CPU's SMM Save State buffer\r
236 //\r
237 if ((CpuIndex >= gSmst->NumberOfCpus) || (Buffer == NULL)) {\r
238 return EFI_INVALID_PARAMETER;\r
239 }\r
5b02be4d 240 //\r
b70ec0de
HW
241 // The SpeculationBarrier() call here is to ensure the above check for the\r
242 // CpuIndex has been completed before the execution of subsequent codes.\r
5b02be4d 243 //\r
b70ec0de 244 SpeculationBarrier ();\r
529a5a86
MK
245\r
246 //\r
247 // Check for special EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID\r
248 //\r
249 if (Register == EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID) {\r
250 //\r
251 // The pseudo-register only supports the 64-bit size specified by Width.\r
252 //\r
253 if (Width != sizeof (UINT64)) {\r
254 return EFI_INVALID_PARAMETER;\r
255 }\r
256 //\r
257 // If the processor is in SMM at the time the SMI occurred,\r
258 // the pseudo register value for EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID is returned in Buffer.\r
259 // Otherwise, EFI_NOT_FOUND is returned.\r
260 //\r
ed3d5ecb 261 if (*(mSmmMpSyncData->CpuData[CpuIndex].Present)) {\r
529a5a86
MK
262 *(UINT64 *)Buffer = gSmmCpuPrivate->ProcessorInfo[CpuIndex].ProcessorId;\r
263 return EFI_SUCCESS;\r
264 } else {\r
265 return EFI_NOT_FOUND;\r
266 }\r
267 }\r
268\r
ed3d5ecb 269 if (!(*(mSmmMpSyncData->CpuData[CpuIndex].Present))) {\r
529a5a86
MK
270 return EFI_INVALID_PARAMETER;\r
271 }\r
272\r
273 Status = SmmCpuFeaturesReadSaveStateRegister (CpuIndex, Register, Width, Buffer);\r
274 if (Status == EFI_UNSUPPORTED) {\r
275 Status = ReadSaveStateRegister (CpuIndex, Register, Width, Buffer);\r
276 }\r
277 return Status;\r
278}\r
279\r
280/**\r
281 Write data to the CPU save state.\r
282\r
283 @param This EFI_SMM_CPU_PROTOCOL instance\r
284 @param Width The number of bytes to read from the CPU save state.\r
285 @param Register Specifies the CPU register to write to the save state.\r
286 @param CpuIndex Specifies the zero-based index of the CPU save state\r
287 @param Buffer Upon entry, this holds the new CPU register value.\r
288\r
289 @retval EFI_SUCCESS The register was written from Save State\r
290 @retval EFI_NOT_FOUND The register is not defined for the Save State of Processor\r
291 @retval EFI_INVALID_PARAMTER ProcessorIndex or Width is not correct\r
292\r
293**/\r
294EFI_STATUS\r
295EFIAPI\r
296SmmWriteSaveState (\r
297 IN CONST EFI_SMM_CPU_PROTOCOL *This,\r
298 IN UINTN Width,\r
299 IN EFI_SMM_SAVE_STATE_REGISTER Register,\r
300 IN UINTN CpuIndex,\r
301 IN CONST VOID *Buffer\r
302 )\r
303{\r
304 EFI_STATUS Status;\r
305\r
306 //\r
307 // Retrieve pointer to the specified CPU's SMM Save State buffer\r
308 //\r
309 if ((CpuIndex >= gSmst->NumberOfCpus) || (Buffer == NULL)) {\r
310 return EFI_INVALID_PARAMETER;\r
311 }\r
312\r
313 //\r
314 // Writes to EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID are ignored\r
315 //\r
316 if (Register == EFI_SMM_SAVE_STATE_REGISTER_PROCESSOR_ID) {\r
317 return EFI_SUCCESS;\r
318 }\r
319\r
320 if (!mSmmMpSyncData->CpuData[CpuIndex].Present) {\r
321 return EFI_INVALID_PARAMETER;\r
322 }\r
323\r
324 Status = SmmCpuFeaturesWriteSaveStateRegister (CpuIndex, Register, Width, Buffer);\r
325 if (Status == EFI_UNSUPPORTED) {\r
326 Status = WriteSaveStateRegister (CpuIndex, Register, Width, Buffer);\r
327 }\r
328 return Status;\r
329}\r
330\r
331\r
332/**\r
333 C function for SMI handler. To change all processor's SMMBase Register.\r
334\r
335**/\r
336VOID\r
337EFIAPI\r
338SmmInitHandler (\r
339 VOID\r
340 )\r
341{\r
342 UINT32 ApicId;\r
343 UINTN Index;\r
344\r
345 //\r
346 // Update SMM IDT entries' code segment and load IDT\r
347 //\r
348 AsmWriteIdtr (&gcSmiIdtr);\r
349 ApicId = GetApicId ();\r
350\r
bb767506 351 ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);\r
529a5a86
MK
352\r
353 for (Index = 0; Index < mNumberOfCpus; Index++) {\r
354 if (ApicId == (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) {\r
355 //\r
356 // Initialize SMM specific features on the currently executing CPU\r
357 //\r
358 SmmCpuFeaturesInitializeProcessor (\r
359 Index,\r
360 mIsBsp,\r
361 gSmmCpuPrivate->ProcessorInfo,\r
362 &mCpuHotPlugData\r
363 );\r
364\r
a46a4c90
JF
365 if (!mSmmS3Flag) {\r
366 //\r
367 // Check XD and BTS features on each processor on normal boot\r
368 //\r
51773d49 369 CheckFeatureSupported ();\r
a46a4c90
JF
370 }\r
371\r
529a5a86
MK
372 if (mIsBsp) {\r
373 //\r
374 // BSP rebase is already done above.\r
375 // Initialize private data during S3 resume\r
376 //\r
377 InitializeMpSyncData ();\r
378 }\r
379\r
380 //\r
381 // Hook return after RSM to set SMM re-based flag\r
382 //\r
383 SemaphoreHook (Index, &mRebased[Index]);\r
384\r
385 return;\r
386 }\r
387 }\r
388 ASSERT (FALSE);\r
389}\r
390\r
391/**\r
392 Relocate SmmBases for each processor.\r
393\r
394 Execute on first boot and all S3 resumes\r
395\r
396**/\r
397VOID\r
398EFIAPI\r
399SmmRelocateBases (\r
400 VOID\r
401 )\r
402{\r
403 UINT8 BakBuf[BACK_BUF_SIZE];\r
404 SMRAM_SAVE_STATE_MAP BakBuf2;\r
405 SMRAM_SAVE_STATE_MAP *CpuStatePtr;\r
406 UINT8 *U8Ptr;\r
407 UINT32 ApicId;\r
408 UINTN Index;\r
409 UINTN BspIndex;\r
410\r
411 //\r
412 // Make sure the reserved size is large enough for procedure SmmInitTemplate.\r
413 //\r
414 ASSERT (sizeof (BakBuf) >= gcSmmInitSize);\r
415\r
416 //\r
417 // Patch ASM code template with current CR0, CR3, and CR4 values\r
418 //\r
f0053e83
LE
419 mSmmCr0 = (UINT32)AsmReadCr0 ();\r
420 PatchInstructionX86 (gPatchSmmCr0, mSmmCr0, 4);\r
6b0841c1 421 PatchInstructionX86 (gPatchSmmCr3, AsmReadCr3 (), 4);\r
351b49c1
LE
422 mSmmCr4 = (UINT32)AsmReadCr4 ();\r
423 PatchInstructionX86 (gPatchSmmCr4, mSmmCr4, 4);\r
529a5a86
MK
424\r
425 //\r
426 // Patch GDTR for SMM base relocation\r
427 //\r
428 gcSmiInitGdtr.Base = gcSmiGdtr.Base;\r
429 gcSmiInitGdtr.Limit = gcSmiGdtr.Limit;\r
430\r
431 U8Ptr = (UINT8*)(UINTN)(SMM_DEFAULT_SMBASE + SMM_HANDLER_OFFSET);\r
432 CpuStatePtr = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);\r
433\r
434 //\r
435 // Backup original contents at address 0x38000\r
436 //\r
437 CopyMem (BakBuf, U8Ptr, sizeof (BakBuf));\r
438 CopyMem (&BakBuf2, CpuStatePtr, sizeof (BakBuf2));\r
439\r
440 //\r
441 // Load image for relocation\r
442 //\r
443 CopyMem (U8Ptr, gcSmmInitTemplate, gcSmmInitSize);\r
444\r
445 //\r
446 // Retrieve the local APIC ID of current processor\r
447 //\r
448 ApicId = GetApicId ();\r
449\r
450 //\r
451 // Relocate SM bases for all APs\r
452 // This is APs' 1st SMI - rebase will be done here, and APs' default SMI handler will be overridden by gcSmmInitTemplate\r
453 //\r
454 mIsBsp = FALSE;\r
455 BspIndex = (UINTN)-1;\r
456 for (Index = 0; Index < mNumberOfCpus; Index++) {\r
457 mRebased[Index] = FALSE;\r
458 if (ApicId != (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) {\r
459 SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId);\r
460 //\r
461 // Wait for this AP to finish its 1st SMI\r
462 //\r
463 while (!mRebased[Index]);\r
464 } else {\r
465 //\r
466 // BSP will be Relocated later\r
467 //\r
468 BspIndex = Index;\r
469 }\r
470 }\r
471\r
472 //\r
473 // Relocate BSP's SMM base\r
474 //\r
475 ASSERT (BspIndex != (UINTN)-1);\r
476 mIsBsp = TRUE;\r
477 SendSmiIpi (ApicId);\r
478 //\r
479 // Wait for the BSP to finish its 1st SMI\r
480 //\r
481 while (!mRebased[BspIndex]);\r
482\r
483 //\r
484 // Restore contents at address 0x38000\r
485 //\r
486 CopyMem (CpuStatePtr, &BakBuf2, sizeof (BakBuf2));\r
487 CopyMem (U8Ptr, BakBuf, sizeof (BakBuf));\r
488}\r
489\r
529a5a86
MK
490/**\r
491 SMM Ready To Lock event notification handler.\r
492\r
493 The CPU S3 data is copied to SMRAM for security and mSmmReadyToLock is set to\r
494 perform additional lock actions that must be performed from SMM on the next SMI.\r
495\r
496 @param[in] Protocol Points to the protocol's unique identifier.\r
497 @param[in] Interface Points to the interface instance.\r
498 @param[in] Handle The handle on which the interface was installed.\r
499\r
500 @retval EFI_SUCCESS Notification handler runs successfully.\r
501 **/\r
502EFI_STATUS\r
503EFIAPI\r
504SmmReadyToLockEventNotify (\r
505 IN CONST EFI_GUID *Protocol,\r
506 IN VOID *Interface,\r
507 IN EFI_HANDLE Handle\r
508 )\r
509{\r
0bdc9e75 510 GetAcpiCpuData ();\r
529a5a86 511\r
d2fc7711
JY
512 //\r
513 // Cache a copy of UEFI memory map before we start profiling feature.\r
514 //\r
515 GetUefiMemoryMap ();\r
516\r
529a5a86
MK
517 //\r
518 // Set SMM ready to lock flag and return\r
519 //\r
520 mSmmReadyToLock = TRUE;\r
521 return EFI_SUCCESS;\r
522}\r
523\r
524/**\r
525 The module Entry Point of the CPU SMM driver.\r
526\r
527 @param ImageHandle The firmware allocated handle for the EFI image.\r
528 @param SystemTable A pointer to the EFI System Table.\r
529\r
530 @retval EFI_SUCCESS The entry point is executed successfully.\r
531 @retval Other Some error occurs when executing this entry point.\r
532\r
533**/\r
534EFI_STATUS\r
535EFIAPI\r
536PiCpuSmmEntry (\r
537 IN EFI_HANDLE ImageHandle,\r
538 IN EFI_SYSTEM_TABLE *SystemTable\r
539 )\r
540{\r
541 EFI_STATUS Status;\r
542 EFI_MP_SERVICES_PROTOCOL *MpServices;\r
543 UINTN NumberOfEnabledProcessors;\r
544 UINTN Index;\r
545 VOID *Buffer;\r
ae82a30b
JY
546 UINTN BufferPages;\r
547 UINTN TileCodeSize;\r
548 UINTN TileDataSize;\r
529a5a86 549 UINTN TileSize;\r
529a5a86
MK
550 UINT8 *Stacks;\r
551 VOID *Registration;\r
552 UINT32 RegEax;\r
553 UINT32 RegEdx;\r
554 UINTN FamilyId;\r
555 UINTN ModelId;\r
556 UINT32 Cr3;\r
557\r
e21e355e
LG
558 //\r
559 // Initialize address fixup\r
560 //\r
561 PiSmmCpuSmmInitFixupAddress ();\r
562 PiSmmCpuSmiEntryFixupAddress ();\r
563\r
529a5a86
MK
564 //\r
565 // Initialize Debug Agent to support source level debug in SMM code\r
566 //\r
567 InitializeDebugAgent (DEBUG_AGENT_INIT_SMM, NULL, NULL);\r
568\r
569 //\r
570 // Report the start of CPU SMM initialization.\r
571 //\r
572 REPORT_STATUS_CODE (\r
573 EFI_PROGRESS_CODE,\r
574 EFI_COMPUTING_UNIT_HOST_PROCESSOR | EFI_CU_HP_PC_SMM_INIT\r
575 );\r
576\r
529a5a86
MK
577 //\r
578 // Find out SMRR Base and SMRR Size\r
579 //\r
580 FindSmramInfo (&mCpuHotPlugData.SmrrBase, &mCpuHotPlugData.SmrrSize);\r
581\r
582 //\r
583 // Get MP Services Protocol\r
584 //\r
585 Status = SystemTable->BootServices->LocateProtocol (&gEfiMpServiceProtocolGuid, NULL, (VOID **)&MpServices);\r
586 ASSERT_EFI_ERROR (Status);\r
587\r
588 //\r
589 // Use MP Services Protocol to retrieve the number of processors and number of enabled processors\r
590 //\r
591 Status = MpServices->GetNumberOfProcessors (MpServices, &mNumberOfCpus, &NumberOfEnabledProcessors);\r
592 ASSERT_EFI_ERROR (Status);\r
593 ASSERT (mNumberOfCpus <= PcdGet32 (PcdCpuMaxLogicalProcessorNumber));\r
594\r
595 //\r
596 // If support CPU hot plug, PcdCpuSmmEnableBspElection should be set to TRUE.\r
597 // A constant BSP index makes no sense because it may be hot removed.\r
598 //\r
599 DEBUG_CODE (\r
600 if (FeaturePcdGet (PcdCpuHotPlugSupport)) {\r
601\r
602 ASSERT (FeaturePcdGet (PcdCpuSmmEnableBspElection));\r
603 }\r
604 );\r
605\r
606 //\r
607 // Save the PcdCpuSmmCodeAccessCheckEnable value into a global variable.\r
608 //\r
609 mSmmCodeAccessCheckEnable = PcdGetBool (PcdCpuSmmCodeAccessCheckEnable);\r
610 DEBUG ((EFI_D_INFO, "PcdCpuSmmCodeAccessCheckEnable = %d\n", mSmmCodeAccessCheckEnable));\r
611\r
241f9149
LD
612 //\r
613 // Save the PcdPteMemoryEncryptionAddressOrMask value into a global variable.\r
614 // Make sure AddressEncMask is contained to smallest supported address field.\r
615 //\r
616 mAddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGING_1G_ADDRESS_MASK_64;\r
617 DEBUG ((EFI_D_INFO, "mAddressEncMask = 0x%lx\n", mAddressEncMask));\r
618\r
529a5a86
MK
619 //\r
620 // If support CPU hot plug, we need to allocate resources for possibly hot-added processors\r
621 //\r
622 if (FeaturePcdGet (PcdCpuHotPlugSupport)) {\r
623 mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);\r
624 } else {\r
625 mMaxNumberOfCpus = mNumberOfCpus;\r
626 }\r
627 gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus = mMaxNumberOfCpus;\r
628\r
629 //\r
630 // The CPU save state and code for the SMI entry point are tiled within an SMRAM\r
631 // allocated buffer. The minimum size of this buffer for a uniprocessor system\r
632 // is 32 KB, because the entry point is SMBASE + 32KB, and CPU save state area\r
633 // just below SMBASE + 64KB. If more than one CPU is present in the platform,\r
634 // then the SMI entry point and the CPU save state areas can be tiles to minimize\r
635 // the total amount SMRAM required for all the CPUs. The tile size can be computed\r
636 // by adding the // CPU save state size, any extra CPU specific context, and\r
637 // the size of code that must be placed at the SMI entry point to transfer\r
638 // control to a C function in the native SMM execution mode. This size is\r
639 // rounded up to the nearest power of 2 to give the tile size for a each CPU.\r
640 // The total amount of memory required is the maximum number of CPUs that\r
641 // platform supports times the tile size. The picture below shows the tiling,\r
642 // where m is the number of tiles that fit in 32KB.\r
643 //\r
644 // +-----------------------------+ <-- 2^n offset from Base of allocated buffer\r
645 // | CPU m+1 Save State |\r
646 // +-----------------------------+\r
647 // | CPU m+1 Extra Data |\r
648 // +-----------------------------+\r
649 // | Padding |\r
650 // +-----------------------------+\r
651 // | CPU 2m SMI Entry |\r
652 // +#############################+ <-- Base of allocated buffer + 64 KB\r
653 // | CPU m-1 Save State |\r
654 // +-----------------------------+\r
655 // | CPU m-1 Extra Data |\r
656 // +-----------------------------+\r
657 // | Padding |\r
658 // +-----------------------------+\r
659 // | CPU 2m-1 SMI Entry |\r
660 // +=============================+ <-- 2^n offset from Base of allocated buffer\r
661 // | . . . . . . . . . . . . |\r
662 // +=============================+ <-- 2^n offset from Base of allocated buffer\r
663 // | CPU 2 Save State |\r
664 // +-----------------------------+\r
665 // | CPU 2 Extra Data |\r
666 // +-----------------------------+\r
667 // | Padding |\r
668 // +-----------------------------+\r
669 // | CPU m+1 SMI Entry |\r
670 // +=============================+ <-- Base of allocated buffer + 32 KB\r
671 // | CPU 1 Save State |\r
672 // +-----------------------------+\r
673 // | CPU 1 Extra Data |\r
674 // +-----------------------------+\r
675 // | Padding |\r
676 // +-----------------------------+\r
677 // | CPU m SMI Entry |\r
678 // +#############################+ <-- Base of allocated buffer + 32 KB == CPU 0 SMBASE + 64 KB\r
679 // | CPU 0 Save State |\r
680 // +-----------------------------+\r
681 // | CPU 0 Extra Data |\r
682 // +-----------------------------+\r
683 // | Padding |\r
684 // +-----------------------------+\r
685 // | CPU m-1 SMI Entry |\r
686 // +=============================+ <-- 2^n offset from Base of allocated buffer\r
687 // | . . . . . . . . . . . . |\r
688 // +=============================+ <-- 2^n offset from Base of allocated buffer\r
689 // | Padding |\r
690 // +-----------------------------+\r
691 // | CPU 1 SMI Entry |\r
692 // +=============================+ <-- 2^n offset from Base of allocated buffer\r
693 // | Padding |\r
694 // +-----------------------------+\r
695 // | CPU 0 SMI Entry |\r
696 // +#############################+ <-- Base of allocated buffer == CPU 0 SMBASE + 32 KB\r
697 //\r
698\r
699 //\r
700 // Retrieve CPU Family\r
701 //\r
e9b3a6c9 702 AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, NULL);\r
529a5a86
MK
703 FamilyId = (RegEax >> 8) & 0xf;\r
704 ModelId = (RegEax >> 4) & 0xf;\r
705 if (FamilyId == 0x06 || FamilyId == 0x0f) {\r
706 ModelId = ModelId | ((RegEax >> 12) & 0xf0);\r
707 }\r
708\r
e9b3a6c9
MK
709 RegEdx = 0;\r
710 AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);\r
711 if (RegEax >= CPUID_EXTENDED_CPU_SIG) {\r
712 AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);\r
713 }\r
529a5a86
MK
714 //\r
715 // Determine the mode of the CPU at the time an SMI occurs\r
716 // Intel(R) 64 and IA-32 Architectures Software Developer's Manual\r
717 // Volume 3C, Section 34.4.1.1\r
718 //\r
719 mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT;\r
720 if ((RegEdx & BIT29) != 0) {\r
721 mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT;\r
722 }\r
723 if (FamilyId == 0x06) {\r
724 if (ModelId == 0x17 || ModelId == 0x0f || ModelId == 0x1c) {\r
725 mSmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT;\r
726 }\r
727 }\r
728\r
729 //\r
730 // Compute tile size of buffer required to hold the CPU SMRAM Save State Map, extra CPU\r
f12367a0
MK
731 // specific context start starts at SMBASE + SMM_PSD_OFFSET, and the SMI entry point.\r
732 // This size is rounded up to nearest power of 2.\r
529a5a86 733 //\r
ae82a30b
JY
734 TileCodeSize = GetSmiHandlerSize ();\r
735 TileCodeSize = ALIGN_VALUE(TileCodeSize, SIZE_4KB);\r
f12367a0 736 TileDataSize = (SMRAM_SAVE_STATE_MAP_OFFSET - SMM_PSD_OFFSET) + sizeof (SMRAM_SAVE_STATE_MAP);\r
ae82a30b
JY
737 TileDataSize = ALIGN_VALUE(TileDataSize, SIZE_4KB);\r
738 TileSize = TileDataSize + TileCodeSize - 1;\r
529a5a86 739 TileSize = 2 * GetPowerOfTwo32 ((UINT32)TileSize);\r
ae82a30b 740 DEBUG ((EFI_D_INFO, "SMRAM TileSize = 0x%08x (0x%08x, 0x%08x)\n", TileSize, TileCodeSize, TileDataSize));\r
529a5a86
MK
741\r
742 //\r
f12367a0
MK
743 // If the TileSize is larger than space available for the SMI Handler of\r
744 // CPU[i], the extra CPU specific context of CPU[i+1], and the SMRAM Save\r
745 // State Map of CPU[i+1], then ASSERT(). If this ASSERT() is triggered, then\r
746 // the SMI Handler size must be reduced or the size of the extra CPU specific\r
747 // context must be reduced.\r
529a5a86
MK
748 //\r
749 ASSERT (TileSize <= (SMRAM_SAVE_STATE_MAP_OFFSET + sizeof (SMRAM_SAVE_STATE_MAP) - SMM_HANDLER_OFFSET));\r
750\r
751 //\r
752 // Allocate buffer for all of the tiles.\r
753 //\r
754 // Intel(R) 64 and IA-32 Architectures Software Developer's Manual\r
755 // Volume 3C, Section 34.11 SMBASE Relocation\r
756 // For Pentium and Intel486 processors, the SMBASE values must be\r
757 // aligned on a 32-KByte boundary or the processor will enter shutdown\r
758 // state during the execution of a RSM instruction.\r
759 //\r
760 // Intel486 processors: FamilyId is 4\r
761 // Pentium processors : FamilyId is 5\r
762 //\r
ae82a30b 763 BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1));\r
529a5a86 764 if ((FamilyId == 4) || (FamilyId == 5)) {\r
717fb604 765 Buffer = AllocateAlignedCodePages (BufferPages, SIZE_32KB);\r
529a5a86 766 } else {\r
717fb604 767 Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB);\r
529a5a86
MK
768 }\r
769 ASSERT (Buffer != NULL);\r
ae82a30b 770 DEBUG ((EFI_D_INFO, "SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE(BufferPages)));\r
529a5a86
MK
771\r
772 //\r
773 // Allocate buffer for pointers to array in SMM_CPU_PRIVATE_DATA.\r
774 //\r
775 gSmmCpuPrivate->ProcessorInfo = (EFI_PROCESSOR_INFORMATION *)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION) * mMaxNumberOfCpus);\r
776 ASSERT (gSmmCpuPrivate->ProcessorInfo != NULL);\r
777\r
778 gSmmCpuPrivate->Operation = (SMM_CPU_OPERATION *)AllocatePool (sizeof (SMM_CPU_OPERATION) * mMaxNumberOfCpus);\r
779 ASSERT (gSmmCpuPrivate->Operation != NULL);\r
780\r
781 gSmmCpuPrivate->CpuSaveStateSize = (UINTN *)AllocatePool (sizeof (UINTN) * mMaxNumberOfCpus);\r
782 ASSERT (gSmmCpuPrivate->CpuSaveStateSize != NULL);\r
783\r
784 gSmmCpuPrivate->CpuSaveState = (VOID **)AllocatePool (sizeof (VOID *) * mMaxNumberOfCpus);\r
785 ASSERT (gSmmCpuPrivate->CpuSaveState != NULL);\r
786\r
787 mSmmCpuPrivateData.SmmCoreEntryContext.CpuSaveStateSize = gSmmCpuPrivate->CpuSaveStateSize;\r
788 mSmmCpuPrivateData.SmmCoreEntryContext.CpuSaveState = gSmmCpuPrivate->CpuSaveState;\r
529a5a86
MK
789\r
790 //\r
791 // Allocate buffer for pointers to array in CPU_HOT_PLUG_DATA.\r
792 //\r
793 mCpuHotPlugData.ApicId = (UINT64 *)AllocatePool (sizeof (UINT64) * mMaxNumberOfCpus);\r
794 ASSERT (mCpuHotPlugData.ApicId != NULL);\r
795 mCpuHotPlugData.SmBase = (UINTN *)AllocatePool (sizeof (UINTN) * mMaxNumberOfCpus);\r
796 ASSERT (mCpuHotPlugData.SmBase != NULL);\r
797 mCpuHotPlugData.ArrayLength = (UINT32)mMaxNumberOfCpus;\r
798\r
799 //\r
800 // Retrieve APIC ID of each enabled processor from the MP Services protocol.\r
801 // Also compute the SMBASE address, CPU Save State address, and CPU Save state\r
802 // size for each CPU in the platform\r
803 //\r
804 for (Index = 0; Index < mMaxNumberOfCpus; Index++) {\r
805 mCpuHotPlugData.SmBase[Index] = (UINTN)Buffer + Index * TileSize - SMM_HANDLER_OFFSET;\r
806 gSmmCpuPrivate->CpuSaveStateSize[Index] = sizeof(SMRAM_SAVE_STATE_MAP);\r
807 gSmmCpuPrivate->CpuSaveState[Index] = (VOID *)(mCpuHotPlugData.SmBase[Index] + SMRAM_SAVE_STATE_MAP_OFFSET);\r
808 gSmmCpuPrivate->Operation[Index] = SmmCpuNone;\r
809\r
810 if (Index < mNumberOfCpus) {\r
811 Status = MpServices->GetProcessorInfo (MpServices, Index, &gSmmCpuPrivate->ProcessorInfo[Index]);\r
812 ASSERT_EFI_ERROR (Status);\r
813 mCpuHotPlugData.ApicId[Index] = gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId;\r
814\r
815 DEBUG ((EFI_D_INFO, "CPU[%03x] APIC ID=%04x SMBASE=%08x SaveState=%08x Size=%08x\n",\r
816 Index,\r
817 (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId,\r
818 mCpuHotPlugData.SmBase[Index],\r
819 gSmmCpuPrivate->CpuSaveState[Index],\r
820 gSmmCpuPrivate->CpuSaveStateSize[Index]\r
821 ));\r
822 } else {\r
823 gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId = INVALID_APIC_ID;\r
824 mCpuHotPlugData.ApicId[Index] = INVALID_APIC_ID;\r
825 }\r
826 }\r
827\r
828 //\r
829 // Allocate SMI stacks for all processors.\r
830 //\r
831 if (FeaturePcdGet (PcdCpuSmmStackGuard)) {\r
832 //\r
833 // 2 more pages is allocated for each processor.\r
834 // one is guard page and the other is known good stack.\r
835 //\r
836 // +-------------------------------------------+-----+-------------------------------------------+\r
837 // | Known Good Stack | Guard Page | SMM Stack | ... | Known Good Stack | Guard Page | SMM Stack |\r
838 // +-------------------------------------------+-----+-------------------------------------------+\r
839 // | | | |\r
840 // |<-------------- Processor 0 -------------->| |<-------------- Processor n -------------->|\r
841 //\r
842 mSmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)) + 2);\r
843 Stacks = (UINT8 *) AllocatePages (gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus * (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)) + 2));\r
844 ASSERT (Stacks != NULL);\r
845 mSmmStackArrayBase = (UINTN)Stacks;\r
846 mSmmStackArrayEnd = mSmmStackArrayBase + gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus * mSmmStackSize - 1;\r
847 } else {\r
848 mSmmStackSize = PcdGet32 (PcdCpuSmmStackSize);\r
849 Stacks = (UINT8 *) AllocatePages (EFI_SIZE_TO_PAGES (gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus * mSmmStackSize));\r
850 ASSERT (Stacks != NULL);\r
851 }\r
852\r
853 //\r
854 // Set SMI stack for SMM base relocation\r
855 //\r
5830d2c3
LE
856 PatchInstructionX86 (\r
857 gPatchSmmInitStack,\r
858 (UINTN) (Stacks + mSmmStackSize - sizeof (UINTN)),\r
859 sizeof (UINTN)\r
860 );\r
529a5a86
MK
861\r
862 //\r
863 // Initialize IDT\r
864 //\r
865 InitializeSmmIdt ();\r
866\r
867 //\r
868 // Relocate SMM Base addresses to the ones allocated from SMRAM\r
869 //\r
870 mRebased = (BOOLEAN *)AllocateZeroPool (sizeof (BOOLEAN) * mMaxNumberOfCpus);\r
871 ASSERT (mRebased != NULL);\r
872 SmmRelocateBases ();\r
873\r
874 //\r
875 // Call hook for BSP to perform extra actions in normal mode after all\r
876 // SMM base addresses have been relocated on all CPUs\r
877 //\r
878 SmmCpuFeaturesSmmRelocationComplete ();\r
879\r
717fb604
JY
880 DEBUG ((DEBUG_INFO, "mXdSupported - 0x%x\n", mXdSupported));\r
881\r
529a5a86
MK
882 //\r
883 // SMM Time initialization\r
884 //\r
885 InitializeSmmTimer ();\r
886\r
887 //\r
888 // Initialize MP globals\r
889 //\r
890 Cr3 = InitializeMpServiceData (Stacks, mSmmStackSize);\r
891\r
892 //\r
893 // Fill in SMM Reserved Regions\r
894 //\r
895 gSmmCpuPrivate->SmmReservedSmramRegion[0].SmramReservedStart = 0;\r
896 gSmmCpuPrivate->SmmReservedSmramRegion[0].SmramReservedSize = 0;\r
897\r
898 //\r
899 // Install the SMM Configuration Protocol onto a new handle on the handle database.\r
900 // The entire SMM Configuration Protocol is allocated from SMRAM, so only a pointer\r
901 // to an SMRAM address will be present in the handle database\r
902 //\r
903 Status = SystemTable->BootServices->InstallMultipleProtocolInterfaces (\r
904 &gSmmCpuPrivate->SmmCpuHandle,\r
905 &gEfiSmmConfigurationProtocolGuid, &gSmmCpuPrivate->SmmConfiguration,\r
906 NULL\r
907 );\r
908 ASSERT_EFI_ERROR (Status);\r
909\r
910 //\r
911 // Install the SMM CPU Protocol into SMM protocol database\r
912 //\r
913 Status = gSmst->SmmInstallProtocolInterface (\r
914 &mSmmCpuHandle,\r
915 &gEfiSmmCpuProtocolGuid,\r
916 EFI_NATIVE_INTERFACE,\r
917 &mSmmCpu\r
918 );\r
919 ASSERT_EFI_ERROR (Status);\r
920\r
827330cc
JW
921 //\r
922 // Install the SMM Memory Attribute Protocol into SMM protocol database\r
923 //\r
924 Status = gSmst->SmmInstallProtocolInterface (\r
925 &mSmmCpuHandle,\r
926 &gEdkiiSmmMemoryAttributeProtocolGuid,\r
927 EFI_NATIVE_INTERFACE,\r
928 &mSmmMemoryAttribute\r
929 );\r
930 ASSERT_EFI_ERROR (Status);\r
931\r
529a5a86
MK
932 //\r
933 // Expose address of CPU Hot Plug Data structure if CPU hot plug is supported.\r
934 //\r
935 if (FeaturePcdGet (PcdCpuHotPlugSupport)) {\r
9838b016
MK
936 Status = PcdSet64S (PcdCpuHotPlugDataAddress, (UINT64)(UINTN)&mCpuHotPlugData);\r
937 ASSERT_EFI_ERROR (Status);\r
529a5a86
MK
938 }\r
939\r
940 //\r
941 // Initialize SMM CPU Services Support\r
942 //\r
943 Status = InitializeSmmCpuServices (mSmmCpuHandle);\r
944 ASSERT_EFI_ERROR (Status);\r
945\r
529a5a86
MK
946 //\r
947 // register SMM Ready To Lock Protocol notification\r
948 //\r
949 Status = gSmst->SmmRegisterProtocolNotify (\r
950 &gEfiSmmReadyToLockProtocolGuid,\r
951 SmmReadyToLockEventNotify,\r
952 &Registration\r
953 );\r
954 ASSERT_EFI_ERROR (Status);\r
955\r
529a5a86
MK
956 //\r
957 // Initialize SMM Profile feature\r
958 //\r
959 InitSmmProfile (Cr3);\r
960\r
b10d5ddc 961 GetAcpiS3EnableFlag ();\r
0bdc9e75 962 InitSmmS3ResumeState (Cr3);\r
529a5a86
MK
963\r
964 DEBUG ((EFI_D_INFO, "SMM CPU Module exit from SMRAM with EFI_SUCCESS\n"));\r
965\r
966 return EFI_SUCCESS;\r
967}\r
968\r
969/**\r
970\r
971 Find out SMRAM information including SMRR base and SMRR size.\r
972\r
973 @param SmrrBase SMRR base\r
974 @param SmrrSize SMRR size\r
975\r
976**/\r
977VOID\r
978FindSmramInfo (\r
979 OUT UINT32 *SmrrBase,\r
980 OUT UINT32 *SmrrSize\r
981 )\r
982{\r
983 EFI_STATUS Status;\r
984 UINTN Size;\r
985 EFI_SMM_ACCESS2_PROTOCOL *SmmAccess;\r
986 EFI_SMRAM_DESCRIPTOR *CurrentSmramRange;\r
529a5a86
MK
987 UINTN Index;\r
988 UINT64 MaxSize;\r
989 BOOLEAN Found;\r
990\r
991 //\r
992 // Get SMM Access Protocol\r
993 //\r
994 Status = gBS->LocateProtocol (&gEfiSmmAccess2ProtocolGuid, NULL, (VOID **)&SmmAccess);\r
995 ASSERT_EFI_ERROR (Status);\r
996\r
997 //\r
998 // Get SMRAM information\r
999 //\r
1000 Size = 0;\r
1001 Status = SmmAccess->GetCapabilities (SmmAccess, &Size, NULL);\r
1002 ASSERT (Status == EFI_BUFFER_TOO_SMALL);\r
1003\r
7ed6f781
JF
1004 mSmmCpuSmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocatePool (Size);\r
1005 ASSERT (mSmmCpuSmramRanges != NULL);\r
529a5a86 1006\r
7ed6f781 1007 Status = SmmAccess->GetCapabilities (SmmAccess, &Size, mSmmCpuSmramRanges);\r
529a5a86
MK
1008 ASSERT_EFI_ERROR (Status);\r
1009\r
7ed6f781 1010 mSmmCpuSmramRangeCount = Size / sizeof (EFI_SMRAM_DESCRIPTOR);\r
529a5a86
MK
1011\r
1012 //\r
1013 // Find the largest SMRAM range between 1MB and 4GB that is at least 256K - 4K in size\r
1014 //\r
1015 CurrentSmramRange = NULL;\r
7ed6f781 1016 for (Index = 0, MaxSize = SIZE_256KB - EFI_PAGE_SIZE; Index < mSmmCpuSmramRangeCount; Index++) {\r
529a5a86
MK
1017 //\r
1018 // Skip any SMRAM region that is already allocated, needs testing, or needs ECC initialization\r
1019 //\r
7ed6f781 1020 if ((mSmmCpuSmramRanges[Index].RegionState & (EFI_ALLOCATED | EFI_NEEDS_TESTING | EFI_NEEDS_ECC_INITIALIZATION)) != 0) {\r
529a5a86
MK
1021 continue;\r
1022 }\r
1023\r
7ed6f781
JF
1024 if (mSmmCpuSmramRanges[Index].CpuStart >= BASE_1MB) {\r
1025 if ((mSmmCpuSmramRanges[Index].CpuStart + mSmmCpuSmramRanges[Index].PhysicalSize) <= SMRR_MAX_ADDRESS) {\r
1026 if (mSmmCpuSmramRanges[Index].PhysicalSize >= MaxSize) {\r
1027 MaxSize = mSmmCpuSmramRanges[Index].PhysicalSize;\r
1028 CurrentSmramRange = &mSmmCpuSmramRanges[Index];\r
529a5a86
MK
1029 }\r
1030 }\r
1031 }\r
1032 }\r
1033\r
1034 ASSERT (CurrentSmramRange != NULL);\r
1035\r
1036 *SmrrBase = (UINT32)CurrentSmramRange->CpuStart;\r
1037 *SmrrSize = (UINT32)CurrentSmramRange->PhysicalSize;\r
1038\r
1039 do {\r
1040 Found = FALSE;\r
7ed6f781
JF
1041 for (Index = 0; Index < mSmmCpuSmramRangeCount; Index++) {\r
1042 if (mSmmCpuSmramRanges[Index].CpuStart < *SmrrBase &&\r
1043 *SmrrBase == (mSmmCpuSmramRanges[Index].CpuStart + mSmmCpuSmramRanges[Index].PhysicalSize)) {\r
1044 *SmrrBase = (UINT32)mSmmCpuSmramRanges[Index].CpuStart;\r
1045 *SmrrSize = (UINT32)(*SmrrSize + mSmmCpuSmramRanges[Index].PhysicalSize);\r
529a5a86 1046 Found = TRUE;\r
7ed6f781
JF
1047 } else if ((*SmrrBase + *SmrrSize) == mSmmCpuSmramRanges[Index].CpuStart && mSmmCpuSmramRanges[Index].PhysicalSize > 0) {\r
1048 *SmrrSize = (UINT32)(*SmrrSize + mSmmCpuSmramRanges[Index].PhysicalSize);\r
529a5a86
MK
1049 Found = TRUE;\r
1050 }\r
1051 }\r
1052 } while (Found);\r
1053\r
1054 DEBUG ((EFI_D_INFO, "SMRR Base: 0x%x, SMRR Size: 0x%x\n", *SmrrBase, *SmrrSize));\r
1055}\r
1056\r
1057/**\r
1058Configure SMM Code Access Check feature on an AP.\r
1059SMM Feature Control MSR will be locked after configuration.\r
1060\r
1061@param[in,out] Buffer Pointer to private data buffer.\r
1062**/\r
1063VOID\r
1064EFIAPI\r
1065ConfigSmmCodeAccessCheckOnCurrentProcessor (\r
1066 IN OUT VOID *Buffer\r
1067 )\r
1068{\r
1069 UINTN CpuIndex;\r
1070 UINT64 SmmFeatureControlMsr;\r
1071 UINT64 NewSmmFeatureControlMsr;\r
1072\r
1073 //\r
1074 // Retrieve the CPU Index from the context passed in\r
1075 //\r
1076 CpuIndex = *(UINTN *)Buffer;\r
1077\r
1078 //\r
1079 // Get the current SMM Feature Control MSR value\r
1080 //\r
1081 SmmFeatureControlMsr = SmmCpuFeaturesGetSmmRegister (CpuIndex, SmmRegFeatureControl);\r
1082\r
1083 //\r
1084 // Compute the new SMM Feature Control MSR value\r
1085 //\r
1086 NewSmmFeatureControlMsr = SmmFeatureControlMsr;\r
1087 if (mSmmCodeAccessCheckEnable) {\r
1088 NewSmmFeatureControlMsr |= SMM_CODE_CHK_EN_BIT;\r
f6bc3a6d
JF
1089 if (FeaturePcdGet (PcdCpuSmmFeatureControlMsrLock)) {\r
1090 NewSmmFeatureControlMsr |= SMM_FEATURE_CONTROL_LOCK_BIT;\r
1091 }\r
529a5a86
MK
1092 }\r
1093\r
1094 //\r
1095 // Only set the SMM Feature Control MSR value if the new value is different than the current value\r
1096 //\r
1097 if (NewSmmFeatureControlMsr != SmmFeatureControlMsr) {\r
1098 SmmCpuFeaturesSetSmmRegister (CpuIndex, SmmRegFeatureControl, NewSmmFeatureControlMsr);\r
1099 }\r
1100\r
1101 //\r
1102 // Release the spin lock user to serialize the updates to the SMM Feature Control MSR\r
1103 //\r
fe3a75bc 1104 ReleaseSpinLock (mConfigSmmCodeAccessCheckLock);\r
529a5a86
MK
1105}\r
1106\r
1107/**\r
1108Configure SMM Code Access Check feature for all processors.\r
1109SMM Feature Control MSR will be locked after configuration.\r
1110**/\r
1111VOID\r
1112ConfigSmmCodeAccessCheck (\r
1113 VOID\r
1114 )\r
1115{\r
1116 UINTN Index;\r
1117 EFI_STATUS Status;\r
1118\r
1119 //\r
1120 // Check to see if the Feature Control MSR is supported on this CPU\r
1121 //\r
f6b0cb17 1122 Index = gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu;\r
529a5a86
MK
1123 if (!SmmCpuFeaturesIsSmmRegisterSupported (Index, SmmRegFeatureControl)) {\r
1124 mSmmCodeAccessCheckEnable = FALSE;\r
1125 return;\r
1126 }\r
1127\r
1128 //\r
1129 // Check to see if the CPU supports the SMM Code Access Check feature\r
1130 // Do not access this MSR unless the CPU supports the SmmRegFeatureControl\r
1131 //\r
1132 if ((AsmReadMsr64 (EFI_MSR_SMM_MCA_CAP) & SMM_CODE_ACCESS_CHK_BIT) == 0) {\r
1133 mSmmCodeAccessCheckEnable = FALSE;\r
529a5a86
MK
1134 return;\r
1135 }\r
1136\r
1137 //\r
1138 // Initialize the lock used to serialize the MSR programming in BSP and all APs\r
1139 //\r
fe3a75bc 1140 InitializeSpinLock (mConfigSmmCodeAccessCheckLock);\r
529a5a86
MK
1141\r
1142 //\r
1143 // Acquire Config SMM Code Access Check spin lock. The BSP will release the\r
1144 // spin lock when it is done executing ConfigSmmCodeAccessCheckOnCurrentProcessor().\r
1145 //\r
fe3a75bc 1146 AcquireSpinLock (mConfigSmmCodeAccessCheckLock);\r
529a5a86
MK
1147\r
1148 //\r
1149 // Enable SMM Code Access Check feature on the BSP.\r
1150 //\r
1151 ConfigSmmCodeAccessCheckOnCurrentProcessor (&Index);\r
1152\r
1153 //\r
1154 // Enable SMM Code Access Check feature for the APs.\r
1155 //\r
1156 for (Index = 0; Index < gSmst->NumberOfCpus; Index++) {\r
f6b0cb17 1157 if (Index != gSmmCpuPrivate->SmmCoreEntryContext.CurrentlyExecutingCpu) {\r
b7025df8
JF
1158 if (gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId == INVALID_APIC_ID) {\r
1159 //\r
1160 // If this processor does not exist\r
1161 //\r
1162 continue;\r
1163 }\r
529a5a86
MK
1164 //\r
1165 // Acquire Config SMM Code Access Check spin lock. The AP will release the\r
1166 // spin lock when it is done executing ConfigSmmCodeAccessCheckOnCurrentProcessor().\r
1167 //\r
fe3a75bc 1168 AcquireSpinLock (mConfigSmmCodeAccessCheckLock);\r
529a5a86
MK
1169\r
1170 //\r
1171 // Call SmmStartupThisAp() to enable SMM Code Access Check on an AP.\r
1172 //\r
1173 Status = gSmst->SmmStartupThisAp (ConfigSmmCodeAccessCheckOnCurrentProcessor, Index, &Index);\r
1174 ASSERT_EFI_ERROR (Status);\r
1175\r
1176 //\r
1177 // Wait for the AP to release the Config SMM Code Access Check spin lock.\r
1178 //\r
fe3a75bc 1179 while (!AcquireSpinLockOrFail (mConfigSmmCodeAccessCheckLock)) {\r
529a5a86
MK
1180 CpuPause ();\r
1181 }\r
1182\r
1183 //\r
1184 // Release the Config SMM Code Access Check spin lock.\r
1185 //\r
fe3a75bc 1186 ReleaseSpinLock (mConfigSmmCodeAccessCheckLock);\r
529a5a86
MK
1187 }\r
1188 }\r
1189}\r
1190\r
21c17193
JY
1191/**\r
1192 This API provides a way to allocate memory for page table.\r
1193\r
1194 This API can be called more once to allocate memory for page tables.\r
1195\r
1196 Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the\r
1197 allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL\r
1198 is returned. If there is not enough memory remaining to satisfy the request, then NULL is\r
1199 returned.\r
1200\r
1201 @param Pages The number of 4 KB pages to allocate.\r
1202\r
1203 @return A pointer to the allocated buffer or NULL if allocation fails.\r
1204\r
1205**/\r
1206VOID *\r
1207AllocatePageTableMemory (\r
1208 IN UINTN Pages\r
1209 )\r
1210{\r
1211 VOID *Buffer;\r
1212\r
1213 Buffer = SmmCpuFeaturesAllocatePageTableMemory (Pages);\r
1214 if (Buffer != NULL) {\r
1215 return Buffer;\r
1216 }\r
1217 return AllocatePages (Pages);\r
1218}\r
1219\r
717fb604
JY
1220/**\r
1221 Allocate pages for code.\r
1222\r
1223 @param[in] Pages Number of pages to be allocated.\r
1224\r
1225 @return Allocated memory.\r
1226**/\r
1227VOID *\r
1228AllocateCodePages (\r
1229 IN UINTN Pages\r
1230 )\r
1231{\r
1232 EFI_STATUS Status;\r
1233 EFI_PHYSICAL_ADDRESS Memory;\r
1234\r
1235 if (Pages == 0) {\r
1236 return NULL;\r
1237 }\r
1238\r
1239 Status = gSmst->SmmAllocatePages (AllocateAnyPages, EfiRuntimeServicesCode, Pages, &Memory);\r
1240 if (EFI_ERROR (Status)) {\r
1241 return NULL;\r
1242 }\r
1243 return (VOID *) (UINTN) Memory;\r
1244}\r
1245\r
1246/**\r
1247 Allocate aligned pages for code.\r
1248\r
1249 @param[in] Pages Number of pages to be allocated.\r
1250 @param[in] Alignment The requested alignment of the allocation.\r
1251 Must be a power of two.\r
1252 If Alignment is zero, then byte alignment is used.\r
1253\r
1254 @return Allocated memory.\r
1255**/\r
1256VOID *\r
1257AllocateAlignedCodePages (\r
1258 IN UINTN Pages,\r
1259 IN UINTN Alignment\r
1260 )\r
1261{\r
1262 EFI_STATUS Status;\r
1263 EFI_PHYSICAL_ADDRESS Memory;\r
1264 UINTN AlignedMemory;\r
1265 UINTN AlignmentMask;\r
1266 UINTN UnalignedPages;\r
1267 UINTN RealPages;\r
1268\r
1269 //\r
1270 // Alignment must be a power of two or zero.\r
1271 //\r
1272 ASSERT ((Alignment & (Alignment - 1)) == 0);\r
1273\r
1274 if (Pages == 0) {\r
1275 return NULL;\r
1276 }\r
1277 if (Alignment > EFI_PAGE_SIZE) {\r
1278 //\r
1279 // Calculate the total number of pages since alignment is larger than page size.\r
1280 //\r
1281 AlignmentMask = Alignment - 1;\r
1282 RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment);\r
1283 //\r
1284 // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow.\r
1285 //\r
1286 ASSERT (RealPages > Pages);\r
1287\r
1288 Status = gSmst->SmmAllocatePages (AllocateAnyPages, EfiRuntimeServicesCode, RealPages, &Memory);\r
1289 if (EFI_ERROR (Status)) {\r
1290 return NULL;\r
1291 }\r
1292 AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask;\r
1293 UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory);\r
1294 if (UnalignedPages > 0) {\r
1295 //\r
1296 // Free first unaligned page(s).\r
1297 //\r
1298 Status = gSmst->SmmFreePages (Memory, UnalignedPages);\r
1299 ASSERT_EFI_ERROR (Status);\r
1300 }\r
8491e302 1301 Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages);\r
717fb604
JY
1302 UnalignedPages = RealPages - Pages - UnalignedPages;\r
1303 if (UnalignedPages > 0) {\r
1304 //\r
1305 // Free last unaligned page(s).\r
1306 //\r
1307 Status = gSmst->SmmFreePages (Memory, UnalignedPages);\r
1308 ASSERT_EFI_ERROR (Status);\r
1309 }\r
1310 } else {\r
1311 //\r
1312 // Do not over-allocate pages in this case.\r
1313 //\r
1314 Status = gSmst->SmmAllocatePages (AllocateAnyPages, EfiRuntimeServicesCode, Pages, &Memory);\r
1315 if (EFI_ERROR (Status)) {\r
1316 return NULL;\r
1317 }\r
1318 AlignedMemory = (UINTN) Memory;\r
1319 }\r
1320 return (VOID *) AlignedMemory;\r
1321}\r
1322\r
529a5a86
MK
1323/**\r
1324 Perform the remaining tasks.\r
1325\r
1326**/\r
1327VOID\r
1328PerformRemainingTasks (\r
1329 VOID\r
1330 )\r
1331{\r
1332 if (mSmmReadyToLock) {\r
1333 //\r
1334 // Start SMM Profile feature\r
1335 //\r
1336 if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {\r
1337 SmmProfileStart ();\r
1338 }\r
1339 //\r
1340 // Create a mix of 2MB and 4KB page table. Update some memory ranges absent and execute-disable.\r
1341 //\r
1342 InitPaging ();\r
717fb604
JY
1343\r
1344 //\r
1345 // Mark critical region to be read-only in page table\r
1346 //\r
d2fc7711
JY
1347 SetMemMapAttributes ();\r
1348\r
1349 //\r
1350 // For outside SMRAM, we only map SMM communication buffer or MMIO.\r
1351 //\r
1352 SetUefiMemMapAttributes ();\r
717fb604
JY
1353\r
1354 //\r
1355 // Set page table itself to be read-only\r
1356 //\r
1357 SetPageTableAttributes ();\r
1358\r
529a5a86
MK
1359 //\r
1360 // Configure SMM Code Access Check feature if available.\r
1361 //\r
1362 ConfigSmmCodeAccessCheck ();\r
1363\r
21c17193
JY
1364 SmmCpuFeaturesCompleteSmmReadyToLock ();\r
1365\r
529a5a86
MK
1366 //\r
1367 // Clean SMM ready to lock flag\r
1368 //\r
1369 mSmmReadyToLock = FALSE;\r
1370 }\r
1371}\r
9f419739
JY
1372\r
1373/**\r
1374 Perform the pre tasks.\r
1375\r
1376**/\r
1377VOID\r
1378PerformPreTasks (\r
1379 VOID\r
1380 )\r
1381{\r
0bdc9e75 1382 RestoreSmmConfigurationInS3 ();\r
9f419739 1383}\r