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