]> git.proxmox.com Git - mirror_edk2.git/blob - UefiCpuPkg/Library/MpInitLib/MpLib.c
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / UefiCpuPkg / Library / MpInitLib / MpLib.c
1 /** @file
2 CPU MP Initialize Library common functions.
3
4 Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.<BR>
5 Copyright (c) 2020, AMD Inc. All rights reserved.<BR>
6
7 SPDX-License-Identifier: BSD-2-Clause-Patent
8
9 **/
10
11 #include "MpLib.h"
12 #include <Library/VmgExitLib.h>
13 #include <Register/Amd/Fam17Msr.h>
14 #include <Register/Amd/Ghcb.h>
15
16 EFI_GUID mCpuInitMpLibHobGuid = CPU_INIT_MP_LIB_HOB_GUID;
17
18 /**
19 The function will check if BSP Execute Disable is enabled.
20
21 DxeIpl may have enabled Execute Disable for BSP, APs need to
22 get the status and sync up the settings.
23 If BSP's CR0.Paging is not set, BSP execute Disble feature is
24 not working actually.
25
26 @retval TRUE BSP Execute Disable is enabled.
27 @retval FALSE BSP Execute Disable is not enabled.
28 **/
29 BOOLEAN
30 IsBspExecuteDisableEnabled (
31 VOID
32 )
33 {
34 UINT32 Eax;
35 CPUID_EXTENDED_CPU_SIG_EDX Edx;
36 MSR_IA32_EFER_REGISTER EferMsr;
37 BOOLEAN Enabled;
38 IA32_CR0 Cr0;
39
40 Enabled = FALSE;
41 Cr0.UintN = AsmReadCr0 ();
42 if (Cr0.Bits.PG != 0) {
43 //
44 // If CR0 Paging bit is set
45 //
46 AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
47 if (Eax >= CPUID_EXTENDED_CPU_SIG) {
48 AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &Edx.Uint32);
49 //
50 // CPUID 0x80000001
51 // Bit 20: Execute Disable Bit available.
52 //
53 if (Edx.Bits.NX != 0) {
54 EferMsr.Uint64 = AsmReadMsr64 (MSR_IA32_EFER);
55 //
56 // MSR 0xC0000080
57 // Bit 11: Execute Disable Bit enable.
58 //
59 if (EferMsr.Bits.NXE != 0) {
60 Enabled = TRUE;
61 }
62 }
63 }
64 }
65
66 return Enabled;
67 }
68
69 /**
70 Worker function for SwitchBSP().
71
72 Worker function for SwitchBSP(), assigned to the AP which is intended
73 to become BSP.
74
75 @param[in] Buffer Pointer to CPU MP Data
76 **/
77 VOID
78 EFIAPI
79 FutureBSPProc (
80 IN VOID *Buffer
81 )
82 {
83 CPU_MP_DATA *DataInHob;
84
85 DataInHob = (CPU_MP_DATA *)Buffer;
86 AsmExchangeRole (&DataInHob->APInfo, &DataInHob->BSPInfo);
87 }
88
89 /**
90 Get the Application Processors state.
91
92 @param[in] CpuData The pointer to CPU_AP_DATA of specified AP
93
94 @return The AP status
95 **/
96 CPU_STATE
97 GetApState (
98 IN CPU_AP_DATA *CpuData
99 )
100 {
101 return CpuData->State;
102 }
103
104 /**
105 Set the Application Processors state.
106
107 @param[in] CpuData The pointer to CPU_AP_DATA of specified AP
108 @param[in] State The AP status
109 **/
110 VOID
111 SetApState (
112 IN CPU_AP_DATA *CpuData,
113 IN CPU_STATE State
114 )
115 {
116 AcquireSpinLock (&CpuData->ApLock);
117 CpuData->State = State;
118 ReleaseSpinLock (&CpuData->ApLock);
119 }
120
121 /**
122 Save BSP's local APIC timer setting.
123
124 @param[in] CpuMpData Pointer to CPU MP Data
125 **/
126 VOID
127 SaveLocalApicTimerSetting (
128 IN CPU_MP_DATA *CpuMpData
129 )
130 {
131 //
132 // Record the current local APIC timer setting of BSP
133 //
134 GetApicTimerState (
135 &CpuMpData->DivideValue,
136 &CpuMpData->PeriodicMode,
137 &CpuMpData->Vector
138 );
139 CpuMpData->CurrentTimerCount = GetApicTimerCurrentCount ();
140 CpuMpData->TimerInterruptState = GetApicTimerInterruptState ();
141 }
142
143 /**
144 Sync local APIC timer setting from BSP to AP.
145
146 @param[in] CpuMpData Pointer to CPU MP Data
147 **/
148 VOID
149 SyncLocalApicTimerSetting (
150 IN CPU_MP_DATA *CpuMpData
151 )
152 {
153 //
154 // Sync local APIC timer setting from BSP to AP
155 //
156 InitializeApicTimer (
157 CpuMpData->DivideValue,
158 CpuMpData->CurrentTimerCount,
159 CpuMpData->PeriodicMode,
160 CpuMpData->Vector
161 );
162 //
163 // Disable AP's local APIC timer interrupt
164 //
165 DisableApicTimerInterrupt ();
166 }
167
168 /**
169 Save the volatile registers required to be restored following INIT IPI.
170
171 @param[out] VolatileRegisters Returns buffer saved the volatile resisters
172 **/
173 VOID
174 SaveVolatileRegisters (
175 OUT CPU_VOLATILE_REGISTERS *VolatileRegisters
176 )
177 {
178 CPUID_VERSION_INFO_EDX VersionInfoEdx;
179
180 VolatileRegisters->Cr0 = AsmReadCr0 ();
181 VolatileRegisters->Cr3 = AsmReadCr3 ();
182 VolatileRegisters->Cr4 = AsmReadCr4 ();
183
184 AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &VersionInfoEdx.Uint32);
185 if (VersionInfoEdx.Bits.DE != 0) {
186 //
187 // If processor supports Debugging Extensions feature
188 // by CPUID.[EAX=01H]:EDX.BIT2
189 //
190 VolatileRegisters->Dr0 = AsmReadDr0 ();
191 VolatileRegisters->Dr1 = AsmReadDr1 ();
192 VolatileRegisters->Dr2 = AsmReadDr2 ();
193 VolatileRegisters->Dr3 = AsmReadDr3 ();
194 VolatileRegisters->Dr6 = AsmReadDr6 ();
195 VolatileRegisters->Dr7 = AsmReadDr7 ();
196 }
197
198 AsmReadGdtr (&VolatileRegisters->Gdtr);
199 AsmReadIdtr (&VolatileRegisters->Idtr);
200 VolatileRegisters->Tr = AsmReadTr ();
201 }
202
203 /**
204 Restore the volatile registers following INIT IPI.
205
206 @param[in] VolatileRegisters Pointer to volatile resisters
207 @param[in] IsRestoreDr TRUE: Restore DRx if supported
208 FALSE: Do not restore DRx
209 **/
210 VOID
211 RestoreVolatileRegisters (
212 IN CPU_VOLATILE_REGISTERS *VolatileRegisters,
213 IN BOOLEAN IsRestoreDr
214 )
215 {
216 CPUID_VERSION_INFO_EDX VersionInfoEdx;
217 IA32_TSS_DESCRIPTOR *Tss;
218
219 AsmWriteCr3 (VolatileRegisters->Cr3);
220 AsmWriteCr4 (VolatileRegisters->Cr4);
221 AsmWriteCr0 (VolatileRegisters->Cr0);
222
223 if (IsRestoreDr) {
224 AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &VersionInfoEdx.Uint32);
225 if (VersionInfoEdx.Bits.DE != 0) {
226 //
227 // If processor supports Debugging Extensions feature
228 // by CPUID.[EAX=01H]:EDX.BIT2
229 //
230 AsmWriteDr0 (VolatileRegisters->Dr0);
231 AsmWriteDr1 (VolatileRegisters->Dr1);
232 AsmWriteDr2 (VolatileRegisters->Dr2);
233 AsmWriteDr3 (VolatileRegisters->Dr3);
234 AsmWriteDr6 (VolatileRegisters->Dr6);
235 AsmWriteDr7 (VolatileRegisters->Dr7);
236 }
237 }
238
239 AsmWriteGdtr (&VolatileRegisters->Gdtr);
240 AsmWriteIdtr (&VolatileRegisters->Idtr);
241 if ((VolatileRegisters->Tr != 0) &&
242 (VolatileRegisters->Tr < VolatileRegisters->Gdtr.Limit))
243 {
244 Tss = (IA32_TSS_DESCRIPTOR *)(VolatileRegisters->Gdtr.Base +
245 VolatileRegisters->Tr);
246 if (Tss->Bits.P == 1) {
247 Tss->Bits.Type &= 0xD; // 1101 - Clear busy bit just in case
248 AsmWriteTr (VolatileRegisters->Tr);
249 }
250 }
251 }
252
253 /**
254 Detect whether Mwait-monitor feature is supported.
255
256 @retval TRUE Mwait-monitor feature is supported.
257 @retval FALSE Mwait-monitor feature is not supported.
258 **/
259 BOOLEAN
260 IsMwaitSupport (
261 VOID
262 )
263 {
264 CPUID_VERSION_INFO_ECX VersionInfoEcx;
265
266 AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, &VersionInfoEcx.Uint32, NULL);
267 return (VersionInfoEcx.Bits.MONITOR == 1) ? TRUE : FALSE;
268 }
269
270 /**
271 Get AP loop mode.
272
273 @param[out] MonitorFilterSize Returns the largest monitor-line size in bytes.
274
275 @return The AP loop mode.
276 **/
277 UINT8
278 GetApLoopMode (
279 OUT UINT32 *MonitorFilterSize
280 )
281 {
282 UINT8 ApLoopMode;
283 CPUID_MONITOR_MWAIT_EBX MonitorMwaitEbx;
284
285 ASSERT (MonitorFilterSize != NULL);
286
287 ApLoopMode = PcdGet8 (PcdCpuApLoopMode);
288 ASSERT (ApLoopMode >= ApInHltLoop && ApLoopMode <= ApInRunLoop);
289 if (ApLoopMode == ApInMwaitLoop) {
290 if (!IsMwaitSupport ()) {
291 //
292 // If processor does not support MONITOR/MWAIT feature,
293 // force AP in Hlt-loop mode
294 //
295 ApLoopMode = ApInHltLoop;
296 }
297
298 if (ConfidentialComputingGuestHas (CCAttrAmdSevEs) &&
299 !ConfidentialComputingGuestHas (CCAttrAmdSevSnp))
300 {
301 //
302 // For SEV-ES (SEV-SNP is also considered SEV-ES), force AP in Hlt-loop
303 // mode in order to use the GHCB protocol for starting APs
304 //
305 ApLoopMode = ApInHltLoop;
306 }
307 }
308
309 if (ApLoopMode != ApInMwaitLoop) {
310 *MonitorFilterSize = sizeof (UINT32);
311 } else {
312 //
313 // CPUID.[EAX=05H]:EBX.BIT0-15: Largest monitor-line size in bytes
314 // CPUID.[EAX=05H].EDX: C-states supported using MWAIT
315 //
316 AsmCpuid (CPUID_MONITOR_MWAIT, NULL, &MonitorMwaitEbx.Uint32, NULL, NULL);
317 *MonitorFilterSize = MonitorMwaitEbx.Bits.LargestMonitorLineSize;
318 }
319
320 return ApLoopMode;
321 }
322
323 /**
324 Sort the APIC ID of all processors.
325
326 This function sorts the APIC ID of all processors so that processor number is
327 assigned in the ascending order of APIC ID which eases MP debugging.
328
329 @param[in] CpuMpData Pointer to PEI CPU MP Data
330 **/
331 VOID
332 SortApicId (
333 IN CPU_MP_DATA *CpuMpData
334 )
335 {
336 UINTN Index1;
337 UINTN Index2;
338 UINTN Index3;
339 UINT32 ApicId;
340 CPU_INFO_IN_HOB CpuInfo;
341 UINT32 ApCount;
342 CPU_INFO_IN_HOB *CpuInfoInHob;
343 volatile UINT32 *StartupApSignal;
344
345 ApCount = CpuMpData->CpuCount - 1;
346 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
347 if (ApCount != 0) {
348 for (Index1 = 0; Index1 < ApCount; Index1++) {
349 Index3 = Index1;
350 //
351 // Sort key is the hardware default APIC ID
352 //
353 ApicId = CpuInfoInHob[Index1].ApicId;
354 for (Index2 = Index1 + 1; Index2 <= ApCount; Index2++) {
355 if (ApicId > CpuInfoInHob[Index2].ApicId) {
356 Index3 = Index2;
357 ApicId = CpuInfoInHob[Index2].ApicId;
358 }
359 }
360
361 if (Index3 != Index1) {
362 CopyMem (&CpuInfo, &CpuInfoInHob[Index3], sizeof (CPU_INFO_IN_HOB));
363 CopyMem (
364 &CpuInfoInHob[Index3],
365 &CpuInfoInHob[Index1],
366 sizeof (CPU_INFO_IN_HOB)
367 );
368 CopyMem (&CpuInfoInHob[Index1], &CpuInfo, sizeof (CPU_INFO_IN_HOB));
369
370 //
371 // Also exchange the StartupApSignal.
372 //
373 StartupApSignal = CpuMpData->CpuData[Index3].StartupApSignal;
374 CpuMpData->CpuData[Index3].StartupApSignal =
375 CpuMpData->CpuData[Index1].StartupApSignal;
376 CpuMpData->CpuData[Index1].StartupApSignal = StartupApSignal;
377 }
378 }
379
380 //
381 // Get the processor number for the BSP
382 //
383 ApicId = GetInitialApicId ();
384 for (Index1 = 0; Index1 < CpuMpData->CpuCount; Index1++) {
385 if (CpuInfoInHob[Index1].ApicId == ApicId) {
386 CpuMpData->BspNumber = (UINT32)Index1;
387 break;
388 }
389 }
390 }
391 }
392
393 /**
394 Enable x2APIC mode on APs.
395
396 @param[in, out] Buffer Pointer to private data buffer.
397 **/
398 VOID
399 EFIAPI
400 ApFuncEnableX2Apic (
401 IN OUT VOID *Buffer
402 )
403 {
404 SetApicMode (LOCAL_APIC_MODE_X2APIC);
405 }
406
407 /**
408 Do sync on APs.
409
410 @param[in, out] Buffer Pointer to private data buffer.
411 **/
412 VOID
413 EFIAPI
414 ApInitializeSync (
415 IN OUT VOID *Buffer
416 )
417 {
418 CPU_MP_DATA *CpuMpData;
419 UINTN ProcessorNumber;
420 EFI_STATUS Status;
421
422 CpuMpData = (CPU_MP_DATA *)Buffer;
423 Status = GetProcessorNumber (CpuMpData, &ProcessorNumber);
424 ASSERT_EFI_ERROR (Status);
425 //
426 // Load microcode on AP
427 //
428 MicrocodeDetect (CpuMpData, ProcessorNumber);
429 //
430 // Sync BSP's MTRR table to AP
431 //
432 MtrrSetAllMtrrs (&CpuMpData->MtrrTable);
433 }
434
435 /**
436 Find the current Processor number by APIC ID.
437
438 @param[in] CpuMpData Pointer to PEI CPU MP Data
439 @param[out] ProcessorNumber Return the pocessor number found
440
441 @retval EFI_SUCCESS ProcessorNumber is found and returned.
442 @retval EFI_NOT_FOUND ProcessorNumber is not found.
443 **/
444 EFI_STATUS
445 GetProcessorNumber (
446 IN CPU_MP_DATA *CpuMpData,
447 OUT UINTN *ProcessorNumber
448 )
449 {
450 UINTN TotalProcessorNumber;
451 UINTN Index;
452 CPU_INFO_IN_HOB *CpuInfoInHob;
453 UINT32 CurrentApicId;
454
455 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
456
457 TotalProcessorNumber = CpuMpData->CpuCount;
458 CurrentApicId = GetApicId ();
459 for (Index = 0; Index < TotalProcessorNumber; Index++) {
460 if (CpuInfoInHob[Index].ApicId == CurrentApicId) {
461 *ProcessorNumber = Index;
462 return EFI_SUCCESS;
463 }
464 }
465
466 return EFI_NOT_FOUND;
467 }
468
469 /**
470 This function will get CPU count in the system.
471
472 @param[in] CpuMpData Pointer to PEI CPU MP Data
473
474 @return CPU count detected
475 **/
476 UINTN
477 CollectProcessorCount (
478 IN CPU_MP_DATA *CpuMpData
479 )
480 {
481 UINTN Index;
482 CPU_INFO_IN_HOB *CpuInfoInHob;
483 BOOLEAN X2Apic;
484
485 //
486 // Send 1st broadcast IPI to APs to wakeup APs
487 //
488 CpuMpData->InitFlag = ApInitConfig;
489 WakeUpAP (CpuMpData, TRUE, 0, NULL, NULL, TRUE);
490 CpuMpData->InitFlag = ApInitDone;
491 //
492 // When InitFlag == ApInitConfig, WakeUpAP () guarantees all APs are checked in.
493 // FinishedCount is the number of check-in APs.
494 //
495 CpuMpData->CpuCount = CpuMpData->FinishedCount + 1;
496 ASSERT (CpuMpData->CpuCount <= PcdGet32 (PcdCpuMaxLogicalProcessorNumber));
497
498 //
499 // Enable x2APIC mode if
500 // 1. Number of CPU is greater than 255; or
501 // 2. There are any logical processors reporting an Initial APIC ID of 255 or greater.
502 //
503 X2Apic = FALSE;
504 if (CpuMpData->CpuCount > 255) {
505 //
506 // If there are more than 255 processor found, force to enable X2APIC
507 //
508 X2Apic = TRUE;
509 } else {
510 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
511 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
512 if (CpuInfoInHob[Index].InitialApicId >= 0xFF) {
513 X2Apic = TRUE;
514 break;
515 }
516 }
517 }
518
519 if (X2Apic) {
520 DEBUG ((DEBUG_INFO, "Force x2APIC mode!\n"));
521 //
522 // Wakeup all APs to enable x2APIC mode
523 //
524 WakeUpAP (CpuMpData, TRUE, 0, ApFuncEnableX2Apic, NULL, TRUE);
525 //
526 // Wait for all known APs finished
527 //
528 while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) {
529 CpuPause ();
530 }
531
532 //
533 // Enable x2APIC on BSP
534 //
535 SetApicMode (LOCAL_APIC_MODE_X2APIC);
536 //
537 // Set BSP/Aps state to IDLE
538 //
539 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
540 SetApState (&CpuMpData->CpuData[Index], CpuStateIdle);
541 }
542 }
543
544 DEBUG ((DEBUG_INFO, "APIC MODE is %d\n", GetApicMode ()));
545 //
546 // Sort BSP/Aps by CPU APIC ID in ascending order
547 //
548 SortApicId (CpuMpData);
549
550 DEBUG ((DEBUG_INFO, "MpInitLib: Find %d processors in system.\n", CpuMpData->CpuCount));
551
552 return CpuMpData->CpuCount;
553 }
554
555 /**
556 Initialize CPU AP Data when AP is wakeup at the first time.
557
558 @param[in, out] CpuMpData Pointer to PEI CPU MP Data
559 @param[in] ProcessorNumber The handle number of processor
560 @param[in] BistData Processor BIST data
561 @param[in] ApTopOfStack Top of AP stack
562
563 **/
564 VOID
565 InitializeApData (
566 IN OUT CPU_MP_DATA *CpuMpData,
567 IN UINTN ProcessorNumber,
568 IN UINT32 BistData,
569 IN UINT64 ApTopOfStack
570 )
571 {
572 CPU_INFO_IN_HOB *CpuInfoInHob;
573 MSR_IA32_PLATFORM_ID_REGISTER PlatformIdMsr;
574
575 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
576 CpuInfoInHob[ProcessorNumber].InitialApicId = GetInitialApicId ();
577 CpuInfoInHob[ProcessorNumber].ApicId = GetApicId ();
578 CpuInfoInHob[ProcessorNumber].Health = BistData;
579 CpuInfoInHob[ProcessorNumber].ApTopOfStack = ApTopOfStack;
580
581 CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE;
582 CpuMpData->CpuData[ProcessorNumber].CpuHealthy = (BistData == 0) ? TRUE : FALSE;
583
584 //
585 // NOTE: PlatformId is not relevant on AMD platforms.
586 //
587 if (!StandardSignatureIsAuthenticAMD ()) {
588 PlatformIdMsr.Uint64 = AsmReadMsr64 (MSR_IA32_PLATFORM_ID);
589 CpuMpData->CpuData[ProcessorNumber].PlatformId = (UINT8)PlatformIdMsr.Bits.PlatformId;
590 }
591
592 AsmCpuid (
593 CPUID_VERSION_INFO,
594 &CpuMpData->CpuData[ProcessorNumber].ProcessorSignature,
595 NULL,
596 NULL,
597 NULL
598 );
599
600 InitializeSpinLock (&CpuMpData->CpuData[ProcessorNumber].ApLock);
601 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle);
602 }
603
604 /**
605 This function will be called from AP reset code if BSP uses WakeUpAP.
606
607 @param[in] ExchangeInfo Pointer to the MP exchange info buffer
608 @param[in] ApIndex Number of current executing AP
609 **/
610 VOID
611 EFIAPI
612 ApWakeupFunction (
613 IN MP_CPU_EXCHANGE_INFO *ExchangeInfo,
614 IN UINTN ApIndex
615 )
616 {
617 CPU_MP_DATA *CpuMpData;
618 UINTN ProcessorNumber;
619 EFI_AP_PROCEDURE Procedure;
620 VOID *Parameter;
621 UINT32 BistData;
622 volatile UINT32 *ApStartupSignalBuffer;
623 CPU_INFO_IN_HOB *CpuInfoInHob;
624 UINT64 ApTopOfStack;
625 UINTN CurrentApicMode;
626
627 //
628 // AP finished assembly code and begin to execute C code
629 //
630 CpuMpData = ExchangeInfo->CpuMpData;
631
632 //
633 // AP's local APIC settings will be lost after received INIT IPI
634 // We need to re-initialize them at here
635 //
636 ProgramVirtualWireMode ();
637 //
638 // Mask the LINT0 and LINT1 so that AP doesn't enter the system timer interrupt handler.
639 //
640 DisableLvtInterrupts ();
641 SyncLocalApicTimerSetting (CpuMpData);
642
643 CurrentApicMode = GetApicMode ();
644 while (TRUE) {
645 if (CpuMpData->InitFlag == ApInitConfig) {
646 ProcessorNumber = ApIndex;
647 //
648 // This is first time AP wakeup, get BIST information from AP stack
649 //
650 ApTopOfStack = CpuMpData->Buffer + (ProcessorNumber + 1) * CpuMpData->CpuApStackSize;
651 BistData = *(UINT32 *)((UINTN)ApTopOfStack - sizeof (UINTN));
652 //
653 // CpuMpData->CpuData[0].VolatileRegisters is initialized based on BSP environment,
654 // to initialize AP in InitConfig path.
655 // NOTE: IDTR.BASE stored in CpuMpData->CpuData[0].VolatileRegisters points to a different IDT shared by all APs.
656 //
657 RestoreVolatileRegisters (&CpuMpData->CpuData[0].VolatileRegisters, FALSE);
658 InitializeApData (CpuMpData, ProcessorNumber, BistData, ApTopOfStack);
659 ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;
660 } else {
661 //
662 // Execute AP function if AP is ready
663 //
664 GetProcessorNumber (CpuMpData, &ProcessorNumber);
665 //
666 // Clear AP start-up signal when AP waken up
667 //
668 ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;
669 InterlockedCompareExchange32 (
670 (UINT32 *)ApStartupSignalBuffer,
671 WAKEUP_AP_SIGNAL,
672 0
673 );
674
675 if (CpuMpData->InitFlag == ApInitReconfig) {
676 //
677 // ApInitReconfig happens when:
678 // 1. AP is re-enabled after it's disabled, in either PEI or DXE phase.
679 // 2. AP is initialized in DXE phase.
680 // In either case, use the volatile registers value derived from BSP.
681 // NOTE: IDTR.BASE stored in CpuMpData->CpuData[0].VolatileRegisters points to a
682 // different IDT shared by all APs.
683 //
684 RestoreVolatileRegisters (&CpuMpData->CpuData[0].VolatileRegisters, FALSE);
685 } else {
686 if (CpuMpData->ApLoopMode == ApInHltLoop) {
687 //
688 // Restore AP's volatile registers saved before AP is halted
689 //
690 RestoreVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters, TRUE);
691 } else {
692 //
693 // The CPU driver might not flush TLB for APs on spot after updating
694 // page attributes. AP in mwait loop mode needs to take care of it when
695 // woken up.
696 //
697 CpuFlushTlb ();
698 }
699 }
700
701 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateReady) {
702 Procedure = (EFI_AP_PROCEDURE)CpuMpData->CpuData[ProcessorNumber].ApFunction;
703 Parameter = (VOID *)CpuMpData->CpuData[ProcessorNumber].ApFunctionArgument;
704 if (Procedure != NULL) {
705 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateBusy);
706 //
707 // Enable source debugging on AP function
708 //
709 EnableDebugAgent ();
710 //
711 // Invoke AP function here
712 //
713 Procedure (Parameter);
714 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
715 if (CpuMpData->SwitchBspFlag) {
716 //
717 // Re-get the processor number due to BSP/AP maybe exchange in AP function
718 //
719 GetProcessorNumber (CpuMpData, &ProcessorNumber);
720 CpuMpData->CpuData[ProcessorNumber].ApFunction = 0;
721 CpuMpData->CpuData[ProcessorNumber].ApFunctionArgument = 0;
722 ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;
723 CpuInfoInHob[ProcessorNumber].ApTopOfStack = CpuInfoInHob[CpuMpData->NewBspNumber].ApTopOfStack;
724 } else {
725 if ((CpuInfoInHob[ProcessorNumber].ApicId != GetApicId ()) ||
726 (CpuInfoInHob[ProcessorNumber].InitialApicId != GetInitialApicId ()))
727 {
728 if (CurrentApicMode != GetApicMode ()) {
729 //
730 // If APIC mode change happened during AP function execution,
731 // we do not support APIC ID value changed.
732 //
733 ASSERT (FALSE);
734 CpuDeadLoop ();
735 } else {
736 //
737 // Re-get the CPU APICID and Initial APICID if they are changed
738 //
739 CpuInfoInHob[ProcessorNumber].ApicId = GetApicId ();
740 CpuInfoInHob[ProcessorNumber].InitialApicId = GetInitialApicId ();
741 }
742 }
743 }
744 }
745
746 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateFinished);
747 }
748 }
749
750 if (CpuMpData->ApLoopMode == ApInHltLoop) {
751 //
752 // Save AP volatile registers
753 //
754 SaveVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters);
755 }
756
757 //
758 // AP finished executing C code
759 //
760 InterlockedIncrement ((UINT32 *)&CpuMpData->FinishedCount);
761
762 if (CpuMpData->InitFlag == ApInitConfig) {
763 //
764 // Delay decrementing the APs executing count when SEV-ES is enabled
765 // to allow the APs to issue an AP_RESET_HOLD before the BSP possibly
766 // performs another INIT-SIPI-SIPI sequence.
767 //
768 if (!CpuMpData->UseSevEsAPMethod) {
769 InterlockedDecrement ((UINT32 *)&CpuMpData->MpCpuExchangeInfo->NumApsExecuting);
770 }
771 }
772
773 //
774 // Place AP is specified loop mode
775 //
776 if (CpuMpData->ApLoopMode == ApInHltLoop) {
777 //
778 // Place AP in HLT-loop
779 //
780 while (TRUE) {
781 DisableInterrupts ();
782 if (CpuMpData->UseSevEsAPMethod) {
783 SevEsPlaceApHlt (CpuMpData);
784 } else {
785 CpuSleep ();
786 }
787
788 CpuPause ();
789 }
790 }
791
792 while (TRUE) {
793 DisableInterrupts ();
794 if (CpuMpData->ApLoopMode == ApInMwaitLoop) {
795 //
796 // Place AP in MWAIT-loop
797 //
798 AsmMonitor ((UINTN)ApStartupSignalBuffer, 0, 0);
799 if (*ApStartupSignalBuffer != WAKEUP_AP_SIGNAL) {
800 //
801 // Check AP start-up signal again.
802 // If AP start-up signal is not set, place AP into
803 // the specified C-state
804 //
805 AsmMwait (CpuMpData->ApTargetCState << 4, 0);
806 }
807 } else if (CpuMpData->ApLoopMode == ApInRunLoop) {
808 //
809 // Place AP in Run-loop
810 //
811 CpuPause ();
812 } else {
813 ASSERT (FALSE);
814 }
815
816 //
817 // If AP start-up signal is written, AP is waken up
818 // otherwise place AP in loop again
819 //
820 if (*ApStartupSignalBuffer == WAKEUP_AP_SIGNAL) {
821 break;
822 }
823 }
824 }
825 }
826
827 /**
828 Wait for AP wakeup and write AP start-up signal till AP is waken up.
829
830 @param[in] ApStartupSignalBuffer Pointer to AP wakeup signal
831 **/
832 VOID
833 WaitApWakeup (
834 IN volatile UINT32 *ApStartupSignalBuffer
835 )
836 {
837 //
838 // If AP is waken up, StartupApSignal should be cleared.
839 // Otherwise, write StartupApSignal again till AP waken up.
840 //
841 while (InterlockedCompareExchange32 (
842 (UINT32 *)ApStartupSignalBuffer,
843 WAKEUP_AP_SIGNAL,
844 WAKEUP_AP_SIGNAL
845 ) != 0)
846 {
847 CpuPause ();
848 }
849 }
850
851 /**
852 Calculate the size of the reset vector.
853
854 @param[in] AddressMap The pointer to Address Map structure.
855 @param[out] SizeBelow1Mb Return the size of below 1MB memory for AP reset area.
856 @param[out] SizeAbove1Mb Return the size of abvoe 1MB memory for AP reset area.
857 **/
858 STATIC
859 VOID
860 GetApResetVectorSize (
861 IN MP_ASSEMBLY_ADDRESS_MAP *AddressMap,
862 OUT UINTN *SizeBelow1Mb OPTIONAL,
863 OUT UINTN *SizeAbove1Mb OPTIONAL
864 )
865 {
866 if (SizeBelow1Mb != NULL) {
867 *SizeBelow1Mb = AddressMap->ModeTransitionOffset + sizeof (MP_CPU_EXCHANGE_INFO);
868 }
869
870 if (SizeAbove1Mb != NULL) {
871 *SizeAbove1Mb = AddressMap->RendezvousFunnelSize - AddressMap->ModeTransitionOffset;
872 }
873 }
874
875 /**
876 This function will fill the exchange info structure.
877
878 @param[in] CpuMpData Pointer to CPU MP Data
879
880 **/
881 VOID
882 FillExchangeInfoData (
883 IN CPU_MP_DATA *CpuMpData
884 )
885 {
886 volatile MP_CPU_EXCHANGE_INFO *ExchangeInfo;
887 UINTN Size;
888 IA32_SEGMENT_DESCRIPTOR *Selector;
889 IA32_CR4 Cr4;
890
891 ExchangeInfo = CpuMpData->MpCpuExchangeInfo;
892 ExchangeInfo->StackStart = CpuMpData->Buffer;
893 ExchangeInfo->StackSize = CpuMpData->CpuApStackSize;
894 ExchangeInfo->BufferStart = CpuMpData->WakeupBuffer;
895 ExchangeInfo->ModeOffset = CpuMpData->AddressMap.ModeEntryOffset;
896
897 ExchangeInfo->CodeSegment = AsmReadCs ();
898 ExchangeInfo->DataSegment = AsmReadDs ();
899
900 ExchangeInfo->Cr3 = AsmReadCr3 ();
901
902 ExchangeInfo->CFunction = (UINTN)ApWakeupFunction;
903 ExchangeInfo->ApIndex = 0;
904 ExchangeInfo->NumApsExecuting = 0;
905 ExchangeInfo->InitFlag = (UINTN)CpuMpData->InitFlag;
906 ExchangeInfo->CpuInfo = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
907 ExchangeInfo->CpuMpData = CpuMpData;
908
909 ExchangeInfo->EnableExecuteDisable = IsBspExecuteDisableEnabled ();
910
911 ExchangeInfo->InitializeFloatingPointUnitsAddress = (UINTN)InitializeFloatingPointUnits;
912
913 //
914 // We can check either CPUID(7).ECX[bit16] or check CR4.LA57[bit12]
915 // to determin whether 5-Level Paging is enabled.
916 // CPUID(7).ECX[bit16] shows CPU's capability, CR4.LA57[bit12] shows
917 // current system setting.
918 // Using latter way is simpler because it also eliminates the needs to
919 // check whether platform wants to enable it.
920 //
921 Cr4.UintN = AsmReadCr4 ();
922 ExchangeInfo->Enable5LevelPaging = (BOOLEAN)(Cr4.Bits.LA57 == 1);
923 DEBUG ((DEBUG_INFO, "%a: 5-Level Paging = %d\n", gEfiCallerBaseName, ExchangeInfo->Enable5LevelPaging));
924
925 ExchangeInfo->SevEsIsEnabled = CpuMpData->SevEsIsEnabled;
926 ExchangeInfo->SevSnpIsEnabled = CpuMpData->SevSnpIsEnabled;
927 ExchangeInfo->GhcbBase = (UINTN)CpuMpData->GhcbBase;
928
929 //
930 // Populate SEV-ES specific exchange data.
931 //
932 if (ExchangeInfo->SevSnpIsEnabled) {
933 FillExchangeInfoDataSevEs (ExchangeInfo);
934 }
935
936 //
937 // Get the BSP's data of GDT and IDT
938 //
939 AsmReadGdtr ((IA32_DESCRIPTOR *)&ExchangeInfo->GdtrProfile);
940 AsmReadIdtr ((IA32_DESCRIPTOR *)&ExchangeInfo->IdtrProfile);
941
942 //
943 // Find a 32-bit code segment
944 //
945 Selector = (IA32_SEGMENT_DESCRIPTOR *)ExchangeInfo->GdtrProfile.Base;
946 Size = ExchangeInfo->GdtrProfile.Limit + 1;
947 while (Size > 0) {
948 if ((Selector->Bits.L == 0) && (Selector->Bits.Type >= 8)) {
949 ExchangeInfo->ModeTransitionSegment =
950 (UINT16)((UINTN)Selector - ExchangeInfo->GdtrProfile.Base);
951 break;
952 }
953
954 Selector += 1;
955 Size -= sizeof (IA32_SEGMENT_DESCRIPTOR);
956 }
957
958 ExchangeInfo->ModeTransitionMemory = (UINT32)CpuMpData->WakeupBufferHigh;
959
960 ExchangeInfo->ModeHighMemory = ExchangeInfo->ModeTransitionMemory +
961 (UINT32)ExchangeInfo->ModeOffset -
962 (UINT32)CpuMpData->AddressMap.ModeTransitionOffset;
963 ExchangeInfo->ModeHighSegment = (UINT16)ExchangeInfo->CodeSegment;
964 }
965
966 /**
967 Helper function that waits until the finished AP count reaches the specified
968 limit, or the specified timeout elapses (whichever comes first).
969
970 @param[in] CpuMpData Pointer to CPU MP Data.
971 @param[in] FinishedApLimit The number of finished APs to wait for.
972 @param[in] TimeLimit The number of microseconds to wait for.
973 **/
974 VOID
975 TimedWaitForApFinish (
976 IN CPU_MP_DATA *CpuMpData,
977 IN UINT32 FinishedApLimit,
978 IN UINT32 TimeLimit
979 );
980
981 /**
982 Get available system memory below 1MB by specified size.
983
984 @param[in] CpuMpData The pointer to CPU MP Data structure.
985 **/
986 VOID
987 BackupAndPrepareWakeupBuffer (
988 IN CPU_MP_DATA *CpuMpData
989 )
990 {
991 CopyMem (
992 (VOID *)CpuMpData->BackupBuffer,
993 (VOID *)CpuMpData->WakeupBuffer,
994 CpuMpData->BackupBufferSize
995 );
996 CopyMem (
997 (VOID *)CpuMpData->WakeupBuffer,
998 (VOID *)CpuMpData->AddressMap.RendezvousFunnelAddress,
999 CpuMpData->BackupBufferSize - sizeof (MP_CPU_EXCHANGE_INFO)
1000 );
1001 }
1002
1003 /**
1004 Restore wakeup buffer data.
1005
1006 @param[in] CpuMpData The pointer to CPU MP Data structure.
1007 **/
1008 VOID
1009 RestoreWakeupBuffer (
1010 IN CPU_MP_DATA *CpuMpData
1011 )
1012 {
1013 CopyMem (
1014 (VOID *)CpuMpData->WakeupBuffer,
1015 (VOID *)CpuMpData->BackupBuffer,
1016 CpuMpData->BackupBufferSize
1017 );
1018 }
1019
1020 /**
1021 Allocate reset vector buffer.
1022
1023 @param[in, out] CpuMpData The pointer to CPU MP Data structure.
1024 **/
1025 VOID
1026 AllocateResetVectorBelow1Mb (
1027 IN OUT CPU_MP_DATA *CpuMpData
1028 )
1029 {
1030 UINTN ApResetStackSize;
1031
1032 if (CpuMpData->WakeupBuffer == (UINTN)-1) {
1033 CpuMpData->WakeupBuffer = GetWakeupBuffer (CpuMpData->BackupBufferSize);
1034 CpuMpData->MpCpuExchangeInfo = (MP_CPU_EXCHANGE_INFO *)(UINTN)
1035 (CpuMpData->WakeupBuffer + CpuMpData->BackupBufferSize - sizeof (MP_CPU_EXCHANGE_INFO));
1036 DEBUG ((
1037 DEBUG_INFO,
1038 "AP Vector: 16-bit = %p/%x, ExchangeInfo = %p/%x\n",
1039 CpuMpData->WakeupBuffer,
1040 CpuMpData->BackupBufferSize - sizeof (MP_CPU_EXCHANGE_INFO),
1041 CpuMpData->MpCpuExchangeInfo,
1042 sizeof (MP_CPU_EXCHANGE_INFO)
1043 ));
1044 //
1045 // The AP reset stack is only used by SEV-ES guests. Do not allocate it
1046 // if SEV-ES is not enabled. An SEV-SNP guest is also considered
1047 // an SEV-ES guest, but uses a different method of AP startup, eliminating
1048 // the need for the allocation.
1049 //
1050 if (ConfidentialComputingGuestHas (CCAttrAmdSevEs) &&
1051 !ConfidentialComputingGuestHas (CCAttrAmdSevSnp))
1052 {
1053 //
1054 // Stack location is based on ProcessorNumber, so use the total number
1055 // of processors for calculating the total stack area.
1056 //
1057 ApResetStackSize = (AP_RESET_STACK_SIZE *
1058 PcdGet32 (PcdCpuMaxLogicalProcessorNumber));
1059
1060 //
1061 // Invoke GetWakeupBuffer a second time to allocate the stack area
1062 // below 1MB. The returned buffer will be page aligned and sized and
1063 // below the previously allocated buffer.
1064 //
1065 CpuMpData->SevEsAPResetStackStart = GetWakeupBuffer (ApResetStackSize);
1066
1067 //
1068 // Check to be sure that the "allocate below" behavior hasn't changed.
1069 // This will also catch a failed allocation, as "-1" is returned on
1070 // failure.
1071 //
1072 if (CpuMpData->SevEsAPResetStackStart >= CpuMpData->WakeupBuffer) {
1073 DEBUG ((
1074 DEBUG_ERROR,
1075 "SEV-ES AP reset stack is not below wakeup buffer\n"
1076 ));
1077
1078 ASSERT (FALSE);
1079 CpuDeadLoop ();
1080 }
1081 }
1082 }
1083
1084 BackupAndPrepareWakeupBuffer (CpuMpData);
1085 }
1086
1087 /**
1088 Free AP reset vector buffer.
1089
1090 @param[in] CpuMpData The pointer to CPU MP Data structure.
1091 **/
1092 VOID
1093 FreeResetVector (
1094 IN CPU_MP_DATA *CpuMpData
1095 )
1096 {
1097 //
1098 // If SEV-ES is enabled, the reset area is needed for AP parking and
1099 // and AP startup in the OS, so the reset area is reserved. Do not
1100 // perform the restore as this will overwrite memory which has data
1101 // needed by SEV-ES.
1102 //
1103 if (!CpuMpData->UseSevEsAPMethod) {
1104 RestoreWakeupBuffer (CpuMpData);
1105 }
1106 }
1107
1108 /**
1109 This function will be called by BSP to wakeup AP.
1110
1111 @param[in] CpuMpData Pointer to CPU MP Data
1112 @param[in] Broadcast TRUE: Send broadcast IPI to all APs
1113 FALSE: Send IPI to AP by ApicId
1114 @param[in] ProcessorNumber The handle number of specified processor
1115 @param[in] Procedure The function to be invoked by AP
1116 @param[in] ProcedureArgument The argument to be passed into AP function
1117 @param[in] WakeUpDisabledAps Whether need to wake up disabled APs in broadcast mode.
1118 **/
1119 VOID
1120 WakeUpAP (
1121 IN CPU_MP_DATA *CpuMpData,
1122 IN BOOLEAN Broadcast,
1123 IN UINTN ProcessorNumber,
1124 IN EFI_AP_PROCEDURE Procedure OPTIONAL,
1125 IN VOID *ProcedureArgument OPTIONAL,
1126 IN BOOLEAN WakeUpDisabledAps
1127 )
1128 {
1129 volatile MP_CPU_EXCHANGE_INFO *ExchangeInfo;
1130 UINTN Index;
1131 CPU_AP_DATA *CpuData;
1132 BOOLEAN ResetVectorRequired;
1133 CPU_INFO_IN_HOB *CpuInfoInHob;
1134
1135 CpuMpData->FinishedCount = 0;
1136 ResetVectorRequired = FALSE;
1137
1138 if (CpuMpData->WakeUpByInitSipiSipi ||
1139 (CpuMpData->InitFlag != ApInitDone))
1140 {
1141 ResetVectorRequired = TRUE;
1142 AllocateResetVectorBelow1Mb (CpuMpData);
1143 AllocateSevEsAPMemory (CpuMpData);
1144 FillExchangeInfoData (CpuMpData);
1145 SaveLocalApicTimerSetting (CpuMpData);
1146 }
1147
1148 if (CpuMpData->ApLoopMode == ApInMwaitLoop) {
1149 //
1150 // Get AP target C-state each time when waking up AP,
1151 // for it maybe updated by platform again
1152 //
1153 CpuMpData->ApTargetCState = PcdGet8 (PcdCpuApTargetCstate);
1154 }
1155
1156 ExchangeInfo = CpuMpData->MpCpuExchangeInfo;
1157
1158 if (Broadcast) {
1159 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1160 if (Index != CpuMpData->BspNumber) {
1161 CpuData = &CpuMpData->CpuData[Index];
1162 //
1163 // All AP(include disabled AP) will be woke up by INIT-SIPI-SIPI, but
1164 // the AP procedure will be skipped for disabled AP because AP state
1165 // is not CpuStateReady.
1166 //
1167 if ((GetApState (CpuData) == CpuStateDisabled) && !WakeUpDisabledAps) {
1168 continue;
1169 }
1170
1171 CpuData->ApFunction = (UINTN)Procedure;
1172 CpuData->ApFunctionArgument = (UINTN)ProcedureArgument;
1173 SetApState (CpuData, CpuStateReady);
1174 if (CpuMpData->InitFlag != ApInitConfig) {
1175 *(UINT32 *)CpuData->StartupApSignal = WAKEUP_AP_SIGNAL;
1176 }
1177 }
1178 }
1179
1180 if (ResetVectorRequired) {
1181 //
1182 // For SEV-ES and SEV-SNP, the initial AP boot address will be defined by
1183 // PcdSevEsWorkAreaBase. The Segment/Rip must be the jump address
1184 // from the original INIT-SIPI-SIPI.
1185 //
1186 if (CpuMpData->SevEsIsEnabled) {
1187 SetSevEsJumpTable (ExchangeInfo->BufferStart);
1188 }
1189
1190 //
1191 // Wakeup all APs
1192 // Must use the INIT-SIPI-SIPI method for initial configuration in
1193 // order to obtain the APIC ID.
1194 //
1195 if (CpuMpData->SevSnpIsEnabled && (CpuMpData->InitFlag != ApInitConfig)) {
1196 SevSnpCreateAP (CpuMpData, -1);
1197 } else {
1198 SendInitSipiSipiAllExcludingSelf ((UINT32)ExchangeInfo->BufferStart);
1199 }
1200 }
1201
1202 if (CpuMpData->InitFlag == ApInitConfig) {
1203 if (PcdGet32 (PcdCpuBootLogicalProcessorNumber) > 0) {
1204 //
1205 // The AP enumeration algorithm below is suitable only when the
1206 // platform can tell us the *exact* boot CPU count in advance.
1207 //
1208 // The wait below finishes only when the detected AP count reaches
1209 // (PcdCpuBootLogicalProcessorNumber - 1), regardless of how long that
1210 // takes. If at least one AP fails to check in (meaning a platform
1211 // hardware bug), the detection hangs forever, by design. If the actual
1212 // boot CPU count in the system is higher than
1213 // PcdCpuBootLogicalProcessorNumber (meaning a platform
1214 // misconfiguration), then some APs may complete initialization after
1215 // the wait finishes, and cause undefined behavior.
1216 //
1217 TimedWaitForApFinish (
1218 CpuMpData,
1219 PcdGet32 (PcdCpuBootLogicalProcessorNumber) - 1,
1220 MAX_UINT32 // approx. 71 minutes
1221 );
1222 } else {
1223 //
1224 // The AP enumeration algorithm below is suitable for two use cases.
1225 //
1226 // (1) The check-in time for an individual AP is bounded, and APs run
1227 // through their initialization routines strongly concurrently. In
1228 // particular, the number of concurrently running APs
1229 // ("NumApsExecuting") is never expected to fall to zero
1230 // *temporarily* -- it is expected to fall to zero only when all
1231 // APs have checked-in.
1232 //
1233 // In this case, the platform is supposed to set
1234 // PcdCpuApInitTimeOutInMicroSeconds to a low-ish value (just long
1235 // enough for one AP to start initialization). The timeout will be
1236 // reached soon, and remaining APs are collected by watching
1237 // NumApsExecuting fall to zero. If NumApsExecuting falls to zero
1238 // mid-process, while some APs have not completed initialization,
1239 // the behavior is undefined.
1240 //
1241 // (2) The check-in time for an individual AP is unbounded, and/or APs
1242 // may complete their initializations widely spread out. In
1243 // particular, some APs may finish initialization before some APs
1244 // even start.
1245 //
1246 // In this case, the platform is supposed to set
1247 // PcdCpuApInitTimeOutInMicroSeconds to a high-ish value. The AP
1248 // enumeration will always take that long (except when the boot CPU
1249 // count happens to be maximal, that is,
1250 // PcdCpuMaxLogicalProcessorNumber). All APs are expected to
1251 // check-in before the timeout, and NumApsExecuting is assumed zero
1252 // at timeout. APs that miss the time-out may cause undefined
1253 // behavior.
1254 //
1255 TimedWaitForApFinish (
1256 CpuMpData,
1257 PcdGet32 (PcdCpuMaxLogicalProcessorNumber) - 1,
1258 PcdGet32 (PcdCpuApInitTimeOutInMicroSeconds)
1259 );
1260
1261 while (CpuMpData->MpCpuExchangeInfo->NumApsExecuting != 0) {
1262 CpuPause ();
1263 }
1264 }
1265 } else {
1266 //
1267 // Wait all APs waken up if this is not the 1st broadcast of SIPI
1268 //
1269 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1270 CpuData = &CpuMpData->CpuData[Index];
1271 if (Index != CpuMpData->BspNumber) {
1272 WaitApWakeup (CpuData->StartupApSignal);
1273 }
1274 }
1275 }
1276 } else {
1277 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1278 CpuData->ApFunction = (UINTN)Procedure;
1279 CpuData->ApFunctionArgument = (UINTN)ProcedureArgument;
1280 SetApState (CpuData, CpuStateReady);
1281 //
1282 // Wakeup specified AP
1283 //
1284 ASSERT (CpuMpData->InitFlag != ApInitConfig);
1285 *(UINT32 *)CpuData->StartupApSignal = WAKEUP_AP_SIGNAL;
1286 if (ResetVectorRequired) {
1287 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
1288
1289 //
1290 // For SEV-ES and SEV-SNP, the initial AP boot address will be defined by
1291 // PcdSevEsWorkAreaBase. The Segment/Rip must be the jump address
1292 // from the original INIT-SIPI-SIPI.
1293 //
1294 if (CpuMpData->SevEsIsEnabled) {
1295 SetSevEsJumpTable (ExchangeInfo->BufferStart);
1296 }
1297
1298 if (CpuMpData->SevSnpIsEnabled && (CpuMpData->InitFlag != ApInitConfig)) {
1299 SevSnpCreateAP (CpuMpData, (INTN)ProcessorNumber);
1300 } else {
1301 SendInitSipiSipi (
1302 CpuInfoInHob[ProcessorNumber].ApicId,
1303 (UINT32)ExchangeInfo->BufferStart
1304 );
1305 }
1306 }
1307
1308 //
1309 // Wait specified AP waken up
1310 //
1311 WaitApWakeup (CpuData->StartupApSignal);
1312 }
1313
1314 if (ResetVectorRequired) {
1315 FreeResetVector (CpuMpData);
1316 }
1317
1318 //
1319 // After one round of Wakeup Ap actions, need to re-sync ApLoopMode with
1320 // WakeUpByInitSipiSipi flag. WakeUpByInitSipiSipi flag maybe changed by
1321 // S3SmmInitDone Ppi.
1322 //
1323 CpuMpData->WakeUpByInitSipiSipi = (CpuMpData->ApLoopMode == ApInHltLoop);
1324 }
1325
1326 /**
1327 Calculate timeout value and return the current performance counter value.
1328
1329 Calculate the number of performance counter ticks required for a timeout.
1330 If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1331 as infinity.
1332
1333 @param[in] TimeoutInMicroseconds Timeout value in microseconds.
1334 @param[out] CurrentTime Returns the current value of the performance counter.
1335
1336 @return Expected time stamp counter for timeout.
1337 If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1338 as infinity.
1339
1340 **/
1341 UINT64
1342 CalculateTimeout (
1343 IN UINTN TimeoutInMicroseconds,
1344 OUT UINT64 *CurrentTime
1345 )
1346 {
1347 UINT64 TimeoutInSeconds;
1348 UINT64 TimestampCounterFreq;
1349
1350 //
1351 // Read the current value of the performance counter
1352 //
1353 *CurrentTime = GetPerformanceCounter ();
1354
1355 //
1356 // If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1357 // as infinity.
1358 //
1359 if (TimeoutInMicroseconds == 0) {
1360 return 0;
1361 }
1362
1363 //
1364 // GetPerformanceCounterProperties () returns the timestamp counter's frequency
1365 // in Hz.
1366 //
1367 TimestampCounterFreq = GetPerformanceCounterProperties (NULL, NULL);
1368
1369 //
1370 // Check the potential overflow before calculate the number of ticks for the timeout value.
1371 //
1372 if (DivU64x64Remainder (MAX_UINT64, TimeoutInMicroseconds, NULL) < TimestampCounterFreq) {
1373 //
1374 // Convert microseconds into seconds if direct multiplication overflows
1375 //
1376 TimeoutInSeconds = DivU64x32 (TimeoutInMicroseconds, 1000000);
1377 //
1378 // Assertion if the final tick count exceeds MAX_UINT64
1379 //
1380 ASSERT (DivU64x64Remainder (MAX_UINT64, TimeoutInSeconds, NULL) >= TimestampCounterFreq);
1381 return MultU64x64 (TimestampCounterFreq, TimeoutInSeconds);
1382 } else {
1383 //
1384 // No overflow case, multiply the return value with TimeoutInMicroseconds and then divide
1385 // it by 1,000,000, to get the number of ticks for the timeout value.
1386 //
1387 return DivU64x32 (
1388 MultU64x64 (
1389 TimestampCounterFreq,
1390 TimeoutInMicroseconds
1391 ),
1392 1000000
1393 );
1394 }
1395 }
1396
1397 /**
1398 Checks whether timeout expires.
1399
1400 Check whether the number of elapsed performance counter ticks required for
1401 a timeout condition has been reached.
1402 If Timeout is zero, which means infinity, return value is always FALSE.
1403
1404 @param[in, out] PreviousTime On input, the value of the performance counter
1405 when it was last read.
1406 On output, the current value of the performance
1407 counter
1408 @param[in] TotalTime The total amount of elapsed time in performance
1409 counter ticks.
1410 @param[in] Timeout The number of performance counter ticks required
1411 to reach a timeout condition.
1412
1413 @retval TRUE A timeout condition has been reached.
1414 @retval FALSE A timeout condition has not been reached.
1415
1416 **/
1417 BOOLEAN
1418 CheckTimeout (
1419 IN OUT UINT64 *PreviousTime,
1420 IN UINT64 *TotalTime,
1421 IN UINT64 Timeout
1422 )
1423 {
1424 UINT64 Start;
1425 UINT64 End;
1426 UINT64 CurrentTime;
1427 INT64 Delta;
1428 INT64 Cycle;
1429
1430 if (Timeout == 0) {
1431 return FALSE;
1432 }
1433
1434 GetPerformanceCounterProperties (&Start, &End);
1435 Cycle = End - Start;
1436 if (Cycle < 0) {
1437 Cycle = -Cycle;
1438 }
1439
1440 Cycle++;
1441 CurrentTime = GetPerformanceCounter ();
1442 Delta = (INT64)(CurrentTime - *PreviousTime);
1443 if (Start > End) {
1444 Delta = -Delta;
1445 }
1446
1447 if (Delta < 0) {
1448 Delta += Cycle;
1449 }
1450
1451 *TotalTime += Delta;
1452 *PreviousTime = CurrentTime;
1453 if (*TotalTime > Timeout) {
1454 return TRUE;
1455 }
1456
1457 return FALSE;
1458 }
1459
1460 /**
1461 Helper function that waits until the finished AP count reaches the specified
1462 limit, or the specified timeout elapses (whichever comes first).
1463
1464 @param[in] CpuMpData Pointer to CPU MP Data.
1465 @param[in] FinishedApLimit The number of finished APs to wait for.
1466 @param[in] TimeLimit The number of microseconds to wait for.
1467 **/
1468 VOID
1469 TimedWaitForApFinish (
1470 IN CPU_MP_DATA *CpuMpData,
1471 IN UINT32 FinishedApLimit,
1472 IN UINT32 TimeLimit
1473 )
1474 {
1475 //
1476 // CalculateTimeout() and CheckTimeout() consider a TimeLimit of 0
1477 // "infinity", so check for (TimeLimit == 0) explicitly.
1478 //
1479 if (TimeLimit == 0) {
1480 return;
1481 }
1482
1483 CpuMpData->TotalTime = 0;
1484 CpuMpData->ExpectedTime = CalculateTimeout (
1485 TimeLimit,
1486 &CpuMpData->CurrentTime
1487 );
1488 while (CpuMpData->FinishedCount < FinishedApLimit &&
1489 !CheckTimeout (
1490 &CpuMpData->CurrentTime,
1491 &CpuMpData->TotalTime,
1492 CpuMpData->ExpectedTime
1493 ))
1494 {
1495 CpuPause ();
1496 }
1497
1498 if (CpuMpData->FinishedCount >= FinishedApLimit) {
1499 DEBUG ((
1500 DEBUG_VERBOSE,
1501 "%a: reached FinishedApLimit=%u in %Lu microseconds\n",
1502 __FUNCTION__,
1503 FinishedApLimit,
1504 DivU64x64Remainder (
1505 MultU64x32 (CpuMpData->TotalTime, 1000000),
1506 GetPerformanceCounterProperties (NULL, NULL),
1507 NULL
1508 )
1509 ));
1510 }
1511 }
1512
1513 /**
1514 Reset an AP to Idle state.
1515
1516 Any task being executed by the AP will be aborted and the AP
1517 will be waiting for a new task in Wait-For-SIPI state.
1518
1519 @param[in] ProcessorNumber The handle number of processor.
1520 **/
1521 VOID
1522 ResetProcessorToIdleState (
1523 IN UINTN ProcessorNumber
1524 )
1525 {
1526 CPU_MP_DATA *CpuMpData;
1527
1528 CpuMpData = GetCpuMpData ();
1529
1530 CpuMpData->InitFlag = ApInitReconfig;
1531 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, NULL, NULL, TRUE);
1532 while (CpuMpData->FinishedCount < 1) {
1533 CpuPause ();
1534 }
1535
1536 CpuMpData->InitFlag = ApInitDone;
1537
1538 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle);
1539 }
1540
1541 /**
1542 Searches for the next waiting AP.
1543
1544 Search for the next AP that is put in waiting state by single-threaded StartupAllAPs().
1545
1546 @param[out] NextProcessorNumber Pointer to the processor number of the next waiting AP.
1547
1548 @retval EFI_SUCCESS The next waiting AP has been found.
1549 @retval EFI_NOT_FOUND No waiting AP exists.
1550
1551 **/
1552 EFI_STATUS
1553 GetNextWaitingProcessorNumber (
1554 OUT UINTN *NextProcessorNumber
1555 )
1556 {
1557 UINTN ProcessorNumber;
1558 CPU_MP_DATA *CpuMpData;
1559
1560 CpuMpData = GetCpuMpData ();
1561
1562 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1563 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
1564 *NextProcessorNumber = ProcessorNumber;
1565 return EFI_SUCCESS;
1566 }
1567 }
1568
1569 return EFI_NOT_FOUND;
1570 }
1571
1572 /** Checks status of specified AP.
1573
1574 This function checks whether the specified AP has finished the task assigned
1575 by StartupThisAP(), and whether timeout expires.
1576
1577 @param[in] ProcessorNumber The handle number of processor.
1578
1579 @retval EFI_SUCCESS Specified AP has finished task assigned by StartupThisAPs().
1580 @retval EFI_TIMEOUT The timeout expires.
1581 @retval EFI_NOT_READY Specified AP has not finished task and timeout has not expired.
1582 **/
1583 EFI_STATUS
1584 CheckThisAP (
1585 IN UINTN ProcessorNumber
1586 )
1587 {
1588 CPU_MP_DATA *CpuMpData;
1589 CPU_AP_DATA *CpuData;
1590
1591 CpuMpData = GetCpuMpData ();
1592 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1593
1594 //
1595 // Check the CPU state of AP. If it is CpuStateIdle, then the AP has finished its task.
1596 // Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
1597 // value of state after setting the it to CpuStateIdle, so BSP can safely make use of its value.
1598 //
1599 //
1600 // If the AP finishes for StartupThisAP(), return EFI_SUCCESS.
1601 //
1602 if (GetApState (CpuData) == CpuStateFinished) {
1603 if (CpuData->Finished != NULL) {
1604 *(CpuData->Finished) = TRUE;
1605 }
1606
1607 SetApState (CpuData, CpuStateIdle);
1608 return EFI_SUCCESS;
1609 } else {
1610 //
1611 // If timeout expires for StartupThisAP(), report timeout.
1612 //
1613 if (CheckTimeout (&CpuData->CurrentTime, &CpuData->TotalTime, CpuData->ExpectedTime)) {
1614 if (CpuData->Finished != NULL) {
1615 *(CpuData->Finished) = FALSE;
1616 }
1617
1618 //
1619 // Reset failed AP to idle state
1620 //
1621 ResetProcessorToIdleState (ProcessorNumber);
1622
1623 return EFI_TIMEOUT;
1624 }
1625 }
1626
1627 return EFI_NOT_READY;
1628 }
1629
1630 /**
1631 Checks status of all APs.
1632
1633 This function checks whether all APs have finished task assigned by StartupAllAPs(),
1634 and whether timeout expires.
1635
1636 @retval EFI_SUCCESS All APs have finished task assigned by StartupAllAPs().
1637 @retval EFI_TIMEOUT The timeout expires.
1638 @retval EFI_NOT_READY APs have not finished task and timeout has not expired.
1639 **/
1640 EFI_STATUS
1641 CheckAllAPs (
1642 VOID
1643 )
1644 {
1645 UINTN ProcessorNumber;
1646 UINTN NextProcessorNumber;
1647 UINTN ListIndex;
1648 EFI_STATUS Status;
1649 CPU_MP_DATA *CpuMpData;
1650 CPU_AP_DATA *CpuData;
1651
1652 CpuMpData = GetCpuMpData ();
1653
1654 NextProcessorNumber = 0;
1655
1656 //
1657 // Go through all APs that are responsible for the StartupAllAPs().
1658 //
1659 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1660 if (!CpuMpData->CpuData[ProcessorNumber].Waiting) {
1661 continue;
1662 }
1663
1664 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1665 //
1666 // Check the CPU state of AP. If it is CpuStateIdle, then the AP has finished its task.
1667 // Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
1668 // value of state after setting the it to CpuStateIdle, so BSP can safely make use of its value.
1669 //
1670 if (GetApState (CpuData) == CpuStateFinished) {
1671 CpuMpData->RunningCount--;
1672 CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE;
1673 SetApState (CpuData, CpuStateIdle);
1674
1675 //
1676 // If in Single Thread mode, then search for the next waiting AP for execution.
1677 //
1678 if (CpuMpData->SingleThread) {
1679 Status = GetNextWaitingProcessorNumber (&NextProcessorNumber);
1680
1681 if (!EFI_ERROR (Status)) {
1682 WakeUpAP (
1683 CpuMpData,
1684 FALSE,
1685 (UINT32)NextProcessorNumber,
1686 CpuMpData->Procedure,
1687 CpuMpData->ProcArguments,
1688 TRUE
1689 );
1690 }
1691 }
1692 }
1693 }
1694
1695 //
1696 // If all APs finish, return EFI_SUCCESS.
1697 //
1698 if (CpuMpData->RunningCount == 0) {
1699 return EFI_SUCCESS;
1700 }
1701
1702 //
1703 // If timeout expires, report timeout.
1704 //
1705 if (CheckTimeout (
1706 &CpuMpData->CurrentTime,
1707 &CpuMpData->TotalTime,
1708 CpuMpData->ExpectedTime
1709 )
1710 )
1711 {
1712 //
1713 // If FailedCpuList is not NULL, record all failed APs in it.
1714 //
1715 if (CpuMpData->FailedCpuList != NULL) {
1716 *CpuMpData->FailedCpuList =
1717 AllocatePool ((CpuMpData->RunningCount + 1) * sizeof (UINTN));
1718 ASSERT (*CpuMpData->FailedCpuList != NULL);
1719 }
1720
1721 ListIndex = 0;
1722
1723 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1724 //
1725 // Check whether this processor is responsible for StartupAllAPs().
1726 //
1727 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
1728 //
1729 // Reset failed APs to idle state
1730 //
1731 ResetProcessorToIdleState (ProcessorNumber);
1732 CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE;
1733 if (CpuMpData->FailedCpuList != NULL) {
1734 (*CpuMpData->FailedCpuList)[ListIndex++] = ProcessorNumber;
1735 }
1736 }
1737 }
1738
1739 if (CpuMpData->FailedCpuList != NULL) {
1740 (*CpuMpData->FailedCpuList)[ListIndex] = END_OF_CPU_LIST;
1741 }
1742
1743 return EFI_TIMEOUT;
1744 }
1745
1746 return EFI_NOT_READY;
1747 }
1748
1749 /**
1750 MP Initialize Library initialization.
1751
1752 This service will allocate AP reset vector and wakeup all APs to do APs
1753 initialization.
1754
1755 This service must be invoked before all other MP Initialize Library
1756 service are invoked.
1757
1758 @retval EFI_SUCCESS MP initialization succeeds.
1759 @retval Others MP initialization fails.
1760
1761 **/
1762 EFI_STATUS
1763 EFIAPI
1764 MpInitLibInitialize (
1765 VOID
1766 )
1767 {
1768 CPU_MP_DATA *OldCpuMpData;
1769 CPU_INFO_IN_HOB *CpuInfoInHob;
1770 UINT32 MaxLogicalProcessorNumber;
1771 UINT32 ApStackSize;
1772 MP_ASSEMBLY_ADDRESS_MAP AddressMap;
1773 CPU_VOLATILE_REGISTERS VolatileRegisters;
1774 UINTN BufferSize;
1775 UINT32 MonitorFilterSize;
1776 VOID *MpBuffer;
1777 UINTN Buffer;
1778 CPU_MP_DATA *CpuMpData;
1779 UINT8 ApLoopMode;
1780 UINT8 *MonitorBuffer;
1781 UINTN Index;
1782 UINTN ApResetVectorSizeBelow1Mb;
1783 UINTN ApResetVectorSizeAbove1Mb;
1784 UINTN BackupBufferAddr;
1785 UINTN ApIdtBase;
1786
1787 OldCpuMpData = GetCpuMpDataFromGuidedHob ();
1788 if (OldCpuMpData == NULL) {
1789 MaxLogicalProcessorNumber = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
1790 } else {
1791 MaxLogicalProcessorNumber = OldCpuMpData->CpuCount;
1792 }
1793
1794 ASSERT (MaxLogicalProcessorNumber != 0);
1795
1796 AsmGetAddressMap (&AddressMap);
1797 GetApResetVectorSize (&AddressMap, &ApResetVectorSizeBelow1Mb, &ApResetVectorSizeAbove1Mb);
1798 ApStackSize = PcdGet32 (PcdCpuApStackSize);
1799 ApLoopMode = GetApLoopMode (&MonitorFilterSize);
1800
1801 //
1802 // Save BSP's Control registers for APs.
1803 //
1804 SaveVolatileRegisters (&VolatileRegisters);
1805
1806 BufferSize = ApStackSize * MaxLogicalProcessorNumber;
1807 BufferSize += MonitorFilterSize * MaxLogicalProcessorNumber;
1808 BufferSize += ApResetVectorSizeBelow1Mb;
1809 BufferSize = ALIGN_VALUE (BufferSize, 8);
1810 BufferSize += VolatileRegisters.Idtr.Limit + 1;
1811 BufferSize += sizeof (CPU_MP_DATA);
1812 BufferSize += (sizeof (CPU_AP_DATA) + sizeof (CPU_INFO_IN_HOB))* MaxLogicalProcessorNumber;
1813 MpBuffer = AllocatePages (EFI_SIZE_TO_PAGES (BufferSize));
1814 ASSERT (MpBuffer != NULL);
1815 ZeroMem (MpBuffer, BufferSize);
1816 Buffer = (UINTN)MpBuffer;
1817
1818 //
1819 // The layout of the Buffer is as below:
1820 //
1821 // +--------------------+ <-- Buffer
1822 // AP Stacks (N)
1823 // +--------------------+ <-- MonitorBuffer
1824 // AP Monitor Filters (N)
1825 // +--------------------+ <-- BackupBufferAddr (CpuMpData->BackupBuffer)
1826 // Backup Buffer
1827 // +--------------------+
1828 // Padding
1829 // +--------------------+ <-- ApIdtBase (8-byte boundary)
1830 // AP IDT All APs share one separate IDT. So AP can get address of CPU_MP_DATA from IDT Base.
1831 // +--------------------+ <-- CpuMpData
1832 // CPU_MP_DATA
1833 // +--------------------+ <-- CpuMpData->CpuData
1834 // CPU_AP_DATA (N)
1835 // +--------------------+ <-- CpuMpData->CpuInfoInHob
1836 // CPU_INFO_IN_HOB (N)
1837 // +--------------------+
1838 //
1839 MonitorBuffer = (UINT8 *)(Buffer + ApStackSize * MaxLogicalProcessorNumber);
1840 BackupBufferAddr = (UINTN)MonitorBuffer + MonitorFilterSize * MaxLogicalProcessorNumber;
1841 ApIdtBase = ALIGN_VALUE (BackupBufferAddr + ApResetVectorSizeBelow1Mb, 8);
1842 CpuMpData = (CPU_MP_DATA *)(ApIdtBase + VolatileRegisters.Idtr.Limit + 1);
1843 CpuMpData->Buffer = Buffer;
1844 CpuMpData->CpuApStackSize = ApStackSize;
1845 CpuMpData->BackupBuffer = BackupBufferAddr;
1846 CpuMpData->BackupBufferSize = ApResetVectorSizeBelow1Mb;
1847 CpuMpData->WakeupBuffer = (UINTN)-1;
1848 CpuMpData->CpuCount = 1;
1849 CpuMpData->BspNumber = 0;
1850 CpuMpData->WaitEvent = NULL;
1851 CpuMpData->SwitchBspFlag = FALSE;
1852 CpuMpData->CpuData = (CPU_AP_DATA *)(CpuMpData + 1);
1853 CpuMpData->CpuInfoInHob = (UINT64)(UINTN)(CpuMpData->CpuData + MaxLogicalProcessorNumber);
1854 InitializeSpinLock (&CpuMpData->MpLock);
1855 CpuMpData->SevEsIsEnabled = ConfidentialComputingGuestHas (CCAttrAmdSevEs);
1856 CpuMpData->SevSnpIsEnabled = ConfidentialComputingGuestHas (CCAttrAmdSevSnp);
1857 CpuMpData->SevEsAPBuffer = (UINTN)-1;
1858 CpuMpData->GhcbBase = PcdGet64 (PcdGhcbBase);
1859 CpuMpData->UseSevEsAPMethod = CpuMpData->SevEsIsEnabled && !CpuMpData->SevSnpIsEnabled;
1860
1861 if (CpuMpData->SevSnpIsEnabled) {
1862 ASSERT ((PcdGet64 (PcdGhcbHypervisorFeatures) & GHCB_HV_FEATURES_SNP_AP_CREATE) == GHCB_HV_FEATURES_SNP_AP_CREATE);
1863 }
1864
1865 //
1866 // Make sure no memory usage outside of the allocated buffer.
1867 //
1868 ASSERT (
1869 (CpuMpData->CpuInfoInHob + sizeof (CPU_INFO_IN_HOB) * MaxLogicalProcessorNumber) ==
1870 Buffer + BufferSize
1871 );
1872
1873 //
1874 // Duplicate BSP's IDT to APs.
1875 // All APs share one separate IDT. So AP can get the address of CpuMpData by using IDTR.BASE + IDTR.LIMIT + 1
1876 //
1877 CopyMem ((VOID *)ApIdtBase, (VOID *)VolatileRegisters.Idtr.Base, VolatileRegisters.Idtr.Limit + 1);
1878 VolatileRegisters.Idtr.Base = ApIdtBase;
1879 //
1880 // Don't pass BSP's TR to APs to avoid AP init failure.
1881 //
1882 VolatileRegisters.Tr = 0;
1883 CopyMem (&CpuMpData->CpuData[0].VolatileRegisters, &VolatileRegisters, sizeof (VolatileRegisters));
1884 //
1885 // Set BSP basic information
1886 //
1887 InitializeApData (CpuMpData, 0, 0, CpuMpData->Buffer + ApStackSize);
1888 //
1889 // Save assembly code information
1890 //
1891 CopyMem (&CpuMpData->AddressMap, &AddressMap, sizeof (MP_ASSEMBLY_ADDRESS_MAP));
1892 //
1893 // Finally set AP loop mode
1894 //
1895 CpuMpData->ApLoopMode = ApLoopMode;
1896 DEBUG ((DEBUG_INFO, "AP Loop Mode is %d\n", CpuMpData->ApLoopMode));
1897
1898 CpuMpData->WakeUpByInitSipiSipi = (CpuMpData->ApLoopMode == ApInHltLoop);
1899
1900 //
1901 // Set up APs wakeup signal buffer
1902 //
1903 for (Index = 0; Index < MaxLogicalProcessorNumber; Index++) {
1904 CpuMpData->CpuData[Index].StartupApSignal =
1905 (UINT32 *)(MonitorBuffer + MonitorFilterSize * Index);
1906 }
1907
1908 //
1909 // Copy all 32-bit code and 64-bit code into memory with type of
1910 // EfiBootServicesCode to avoid page fault if NX memory protection is enabled.
1911 //
1912 CpuMpData->WakeupBufferHigh = AllocateCodeBuffer (ApResetVectorSizeAbove1Mb);
1913 CopyMem (
1914 (VOID *)CpuMpData->WakeupBufferHigh,
1915 CpuMpData->AddressMap.RendezvousFunnelAddress +
1916 CpuMpData->AddressMap.ModeTransitionOffset,
1917 ApResetVectorSizeAbove1Mb
1918 );
1919 DEBUG ((DEBUG_INFO, "AP Vector: non-16-bit = %p/%x\n", CpuMpData->WakeupBufferHigh, ApResetVectorSizeAbove1Mb));
1920
1921 //
1922 // Enable the local APIC for Virtual Wire Mode.
1923 //
1924 ProgramVirtualWireMode ();
1925
1926 if (OldCpuMpData == NULL) {
1927 if (MaxLogicalProcessorNumber > 1) {
1928 //
1929 // Wakeup all APs and calculate the processor count in system
1930 //
1931 CollectProcessorCount (CpuMpData);
1932 }
1933 } else {
1934 //
1935 // APs have been wakeup before, just get the CPU Information
1936 // from HOB
1937 //
1938 OldCpuMpData->NewCpuMpData = CpuMpData;
1939 CpuMpData->CpuCount = OldCpuMpData->CpuCount;
1940 CpuMpData->BspNumber = OldCpuMpData->BspNumber;
1941 CpuMpData->CpuInfoInHob = OldCpuMpData->CpuInfoInHob;
1942 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
1943 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1944 InitializeSpinLock (&CpuMpData->CpuData[Index].ApLock);
1945 CpuMpData->CpuData[Index].CpuHealthy = (CpuInfoInHob[Index].Health == 0) ? TRUE : FALSE;
1946 CpuMpData->CpuData[Index].ApFunction = 0;
1947 }
1948 }
1949
1950 if (!GetMicrocodePatchInfoFromHob (
1951 &CpuMpData->MicrocodePatchAddress,
1952 &CpuMpData->MicrocodePatchRegionSize
1953 ))
1954 {
1955 //
1956 // The microcode patch information cache HOB does not exist, which means
1957 // the microcode patches data has not been loaded into memory yet
1958 //
1959 ShadowMicrocodeUpdatePatch (CpuMpData);
1960 }
1961
1962 //
1963 // Detect and apply Microcode on BSP
1964 //
1965 MicrocodeDetect (CpuMpData, CpuMpData->BspNumber);
1966 //
1967 // Store BSP's MTRR setting
1968 //
1969 MtrrGetAllMtrrs (&CpuMpData->MtrrTable);
1970
1971 //
1972 // Wakeup APs to do some AP initialize sync (Microcode & MTRR)
1973 //
1974 if (CpuMpData->CpuCount > 1) {
1975 if (OldCpuMpData != NULL) {
1976 //
1977 // Only needs to use this flag for DXE phase to update the wake up
1978 // buffer. Wakeup buffer allocated in PEI phase is no longer valid
1979 // in DXE.
1980 //
1981 CpuMpData->InitFlag = ApInitReconfig;
1982 }
1983
1984 WakeUpAP (CpuMpData, TRUE, 0, ApInitializeSync, CpuMpData, TRUE);
1985 //
1986 // Wait for all APs finished initialization
1987 //
1988 while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) {
1989 CpuPause ();
1990 }
1991
1992 if (OldCpuMpData != NULL) {
1993 CpuMpData->InitFlag = ApInitDone;
1994 }
1995
1996 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1997 SetApState (&CpuMpData->CpuData[Index], CpuStateIdle);
1998 }
1999 }
2000
2001 //
2002 // Dump the microcode revision for each core.
2003 //
2004 DEBUG_CODE_BEGIN ();
2005 UINT32 ThreadId;
2006 UINT32 ExpectedMicrocodeRevision;
2007
2008 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
2009 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
2010 GetProcessorLocationByApicId (CpuInfoInHob[Index].InitialApicId, NULL, NULL, &ThreadId);
2011 if (ThreadId == 0) {
2012 //
2013 // MicrocodeDetect() loads microcode in first thread of each core, so,
2014 // CpuMpData->CpuData[Index].MicrocodeEntryAddr is initialized only for first thread of each core.
2015 //
2016 ExpectedMicrocodeRevision = 0;
2017 if (CpuMpData->CpuData[Index].MicrocodeEntryAddr != 0) {
2018 ExpectedMicrocodeRevision = ((CPU_MICROCODE_HEADER *)(UINTN)CpuMpData->CpuData[Index].MicrocodeEntryAddr)->UpdateRevision;
2019 }
2020
2021 DEBUG ((
2022 DEBUG_INFO,
2023 "CPU[%04d]: Microcode revision = %08x, expected = %08x\n",
2024 Index,
2025 CpuMpData->CpuData[Index].MicrocodeRevision,
2026 ExpectedMicrocodeRevision
2027 ));
2028 }
2029 }
2030
2031 DEBUG_CODE_END ();
2032 //
2033 // Initialize global data for MP support
2034 //
2035 InitMpGlobalData (CpuMpData);
2036
2037 return EFI_SUCCESS;
2038 }
2039
2040 /**
2041 Gets detailed MP-related information on the requested processor at the
2042 instant this call is made. This service may only be called from the BSP.
2043
2044 @param[in] ProcessorNumber The handle number of processor.
2045 @param[out] ProcessorInfoBuffer A pointer to the buffer where information for
2046 the requested processor is deposited.
2047 @param[out] HealthData Return processor health data.
2048
2049 @retval EFI_SUCCESS Processor information was returned.
2050 @retval EFI_DEVICE_ERROR The calling processor is an AP.
2051 @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL.
2052 @retval EFI_NOT_FOUND The processor with the handle specified by
2053 ProcessorNumber does not exist in the platform.
2054 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2055
2056 **/
2057 EFI_STATUS
2058 EFIAPI
2059 MpInitLibGetProcessorInfo (
2060 IN UINTN ProcessorNumber,
2061 OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer,
2062 OUT EFI_HEALTH_FLAGS *HealthData OPTIONAL
2063 )
2064 {
2065 CPU_MP_DATA *CpuMpData;
2066 UINTN CallerNumber;
2067 CPU_INFO_IN_HOB *CpuInfoInHob;
2068 UINTN OriginalProcessorNumber;
2069
2070 CpuMpData = GetCpuMpData ();
2071 CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;
2072
2073 //
2074 // Lower 24 bits contains the actual processor number.
2075 //
2076 OriginalProcessorNumber = ProcessorNumber;
2077 ProcessorNumber &= BIT24 - 1;
2078
2079 //
2080 // Check whether caller processor is BSP
2081 //
2082 MpInitLibWhoAmI (&CallerNumber);
2083 if (CallerNumber != CpuMpData->BspNumber) {
2084 return EFI_DEVICE_ERROR;
2085 }
2086
2087 if (ProcessorInfoBuffer == NULL) {
2088 return EFI_INVALID_PARAMETER;
2089 }
2090
2091 if (ProcessorNumber >= CpuMpData->CpuCount) {
2092 return EFI_NOT_FOUND;
2093 }
2094
2095 ProcessorInfoBuffer->ProcessorId = (UINT64)CpuInfoInHob[ProcessorNumber].ApicId;
2096 ProcessorInfoBuffer->StatusFlag = 0;
2097 if (ProcessorNumber == CpuMpData->BspNumber) {
2098 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_AS_BSP_BIT;
2099 }
2100
2101 if (CpuMpData->CpuData[ProcessorNumber].CpuHealthy) {
2102 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_HEALTH_STATUS_BIT;
2103 }
2104
2105 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateDisabled) {
2106 ProcessorInfoBuffer->StatusFlag &= ~PROCESSOR_ENABLED_BIT;
2107 } else {
2108 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_ENABLED_BIT;
2109 }
2110
2111 //
2112 // Get processor location information
2113 //
2114 GetProcessorLocationByApicId (
2115 CpuInfoInHob[ProcessorNumber].ApicId,
2116 &ProcessorInfoBuffer->Location.Package,
2117 &ProcessorInfoBuffer->Location.Core,
2118 &ProcessorInfoBuffer->Location.Thread
2119 );
2120
2121 if ((OriginalProcessorNumber & CPU_V2_EXTENDED_TOPOLOGY) != 0) {
2122 GetProcessorLocation2ByApicId (
2123 CpuInfoInHob[ProcessorNumber].ApicId,
2124 &ProcessorInfoBuffer->ExtendedInformation.Location2.Package,
2125 &ProcessorInfoBuffer->ExtendedInformation.Location2.Die,
2126 &ProcessorInfoBuffer->ExtendedInformation.Location2.Tile,
2127 &ProcessorInfoBuffer->ExtendedInformation.Location2.Module,
2128 &ProcessorInfoBuffer->ExtendedInformation.Location2.Core,
2129 &ProcessorInfoBuffer->ExtendedInformation.Location2.Thread
2130 );
2131 }
2132
2133 if (HealthData != NULL) {
2134 HealthData->Uint32 = CpuInfoInHob[ProcessorNumber].Health;
2135 }
2136
2137 return EFI_SUCCESS;
2138 }
2139
2140 /**
2141 Worker function to switch the requested AP to be the BSP from that point onward.
2142
2143 @param[in] ProcessorNumber The handle number of AP that is to become the new BSP.
2144 @param[in] EnableOldBSP If TRUE, then the old BSP will be listed as an
2145 enabled AP. Otherwise, it will be disabled.
2146
2147 @retval EFI_SUCCESS BSP successfully switched.
2148 @retval others Failed to switch BSP.
2149
2150 **/
2151 EFI_STATUS
2152 SwitchBSPWorker (
2153 IN UINTN ProcessorNumber,
2154 IN BOOLEAN EnableOldBSP
2155 )
2156 {
2157 CPU_MP_DATA *CpuMpData;
2158 UINTN CallerNumber;
2159 CPU_STATE State;
2160 MSR_IA32_APIC_BASE_REGISTER ApicBaseMsr;
2161 BOOLEAN OldInterruptState;
2162 BOOLEAN OldTimerInterruptState;
2163
2164 //
2165 // Save and Disable Local APIC timer interrupt
2166 //
2167 OldTimerInterruptState = GetApicTimerInterruptState ();
2168 DisableApicTimerInterrupt ();
2169 //
2170 // Before send both BSP and AP to a procedure to exchange their roles,
2171 // interrupt must be disabled. This is because during the exchange role
2172 // process, 2 CPU may use 1 stack. If interrupt happens, the stack will
2173 // be corrupted, since interrupt return address will be pushed to stack
2174 // by hardware.
2175 //
2176 OldInterruptState = SaveAndDisableInterrupts ();
2177
2178 //
2179 // Mask LINT0 & LINT1 for the old BSP
2180 //
2181 DisableLvtInterrupts ();
2182
2183 CpuMpData = GetCpuMpData ();
2184
2185 //
2186 // Check whether caller processor is BSP
2187 //
2188 MpInitLibWhoAmI (&CallerNumber);
2189 if (CallerNumber != CpuMpData->BspNumber) {
2190 return EFI_DEVICE_ERROR;
2191 }
2192
2193 if (ProcessorNumber >= CpuMpData->CpuCount) {
2194 return EFI_NOT_FOUND;
2195 }
2196
2197 //
2198 // Check whether specified AP is disabled
2199 //
2200 State = GetApState (&CpuMpData->CpuData[ProcessorNumber]);
2201 if (State == CpuStateDisabled) {
2202 return EFI_INVALID_PARAMETER;
2203 }
2204
2205 //
2206 // Check whether ProcessorNumber specifies the current BSP
2207 //
2208 if (ProcessorNumber == CpuMpData->BspNumber) {
2209 return EFI_INVALID_PARAMETER;
2210 }
2211
2212 //
2213 // Check whether specified AP is busy
2214 //
2215 if (State == CpuStateBusy) {
2216 return EFI_NOT_READY;
2217 }
2218
2219 CpuMpData->BSPInfo.State = CPU_SWITCH_STATE_IDLE;
2220 CpuMpData->APInfo.State = CPU_SWITCH_STATE_IDLE;
2221 CpuMpData->SwitchBspFlag = TRUE;
2222 CpuMpData->NewBspNumber = ProcessorNumber;
2223
2224 //
2225 // Clear the BSP bit of MSR_IA32_APIC_BASE
2226 //
2227 ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
2228 ApicBaseMsr.Bits.BSP = 0;
2229 AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
2230
2231 //
2232 // Need to wakeUp AP (future BSP).
2233 //
2234 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, FutureBSPProc, CpuMpData, TRUE);
2235
2236 AsmExchangeRole (&CpuMpData->BSPInfo, &CpuMpData->APInfo);
2237
2238 //
2239 // Set the BSP bit of MSR_IA32_APIC_BASE on new BSP
2240 //
2241 ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
2242 ApicBaseMsr.Bits.BSP = 1;
2243 AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
2244 ProgramVirtualWireMode ();
2245
2246 //
2247 // Wait for old BSP finished AP task
2248 //
2249 while (GetApState (&CpuMpData->CpuData[CallerNumber]) != CpuStateFinished) {
2250 CpuPause ();
2251 }
2252
2253 CpuMpData->SwitchBspFlag = FALSE;
2254 //
2255 // Set old BSP enable state
2256 //
2257 if (!EnableOldBSP) {
2258 SetApState (&CpuMpData->CpuData[CallerNumber], CpuStateDisabled);
2259 } else {
2260 SetApState (&CpuMpData->CpuData[CallerNumber], CpuStateIdle);
2261 }
2262
2263 //
2264 // Save new BSP number
2265 //
2266 CpuMpData->BspNumber = (UINT32)ProcessorNumber;
2267
2268 //
2269 // Restore interrupt state.
2270 //
2271 SetInterruptState (OldInterruptState);
2272
2273 if (OldTimerInterruptState) {
2274 EnableApicTimerInterrupt ();
2275 }
2276
2277 return EFI_SUCCESS;
2278 }
2279
2280 /**
2281 Worker function to let the caller enable or disable an AP from this point onward.
2282 This service may only be called from the BSP.
2283
2284 @param[in] ProcessorNumber The handle number of AP.
2285 @param[in] EnableAP Specifies the new state for the processor for
2286 enabled, FALSE for disabled.
2287 @param[in] HealthFlag If not NULL, a pointer to a value that specifies
2288 the new health status of the AP.
2289
2290 @retval EFI_SUCCESS The specified AP was enabled or disabled successfully.
2291 @retval others Failed to Enable/Disable AP.
2292
2293 **/
2294 EFI_STATUS
2295 EnableDisableApWorker (
2296 IN UINTN ProcessorNumber,
2297 IN BOOLEAN EnableAP,
2298 IN UINT32 *HealthFlag OPTIONAL
2299 )
2300 {
2301 CPU_MP_DATA *CpuMpData;
2302 UINTN CallerNumber;
2303
2304 CpuMpData = GetCpuMpData ();
2305
2306 //
2307 // Check whether caller processor is BSP
2308 //
2309 MpInitLibWhoAmI (&CallerNumber);
2310 if (CallerNumber != CpuMpData->BspNumber) {
2311 return EFI_DEVICE_ERROR;
2312 }
2313
2314 if (ProcessorNumber == CpuMpData->BspNumber) {
2315 return EFI_INVALID_PARAMETER;
2316 }
2317
2318 if (ProcessorNumber >= CpuMpData->CpuCount) {
2319 return EFI_NOT_FOUND;
2320 }
2321
2322 if (!EnableAP) {
2323 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateDisabled);
2324 } else {
2325 ResetProcessorToIdleState (ProcessorNumber);
2326 }
2327
2328 if (HealthFlag != NULL) {
2329 CpuMpData->CpuData[ProcessorNumber].CpuHealthy =
2330 (BOOLEAN)((*HealthFlag & PROCESSOR_HEALTH_STATUS_BIT) != 0);
2331 }
2332
2333 return EFI_SUCCESS;
2334 }
2335
2336 /**
2337 This return the handle number for the calling processor. This service may be
2338 called from the BSP and APs.
2339
2340 @param[out] ProcessorNumber Pointer to the handle number of AP.
2341 The range is from 0 to the total number of
2342 logical processors minus 1. The total number of
2343 logical processors can be retrieved by
2344 MpInitLibGetNumberOfProcessors().
2345
2346 @retval EFI_SUCCESS The current processor handle number was returned
2347 in ProcessorNumber.
2348 @retval EFI_INVALID_PARAMETER ProcessorNumber is NULL.
2349 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2350
2351 **/
2352 EFI_STATUS
2353 EFIAPI
2354 MpInitLibWhoAmI (
2355 OUT UINTN *ProcessorNumber
2356 )
2357 {
2358 CPU_MP_DATA *CpuMpData;
2359
2360 if (ProcessorNumber == NULL) {
2361 return EFI_INVALID_PARAMETER;
2362 }
2363
2364 CpuMpData = GetCpuMpData ();
2365
2366 return GetProcessorNumber (CpuMpData, ProcessorNumber);
2367 }
2368
2369 /**
2370 Retrieves the number of logical processor in the platform and the number of
2371 those logical processors that are enabled on this boot. This service may only
2372 be called from the BSP.
2373
2374 @param[out] NumberOfProcessors Pointer to the total number of logical
2375 processors in the system, including the BSP
2376 and disabled APs.
2377 @param[out] NumberOfEnabledProcessors Pointer to the number of enabled logical
2378 processors that exist in system, including
2379 the BSP.
2380
2381 @retval EFI_SUCCESS The number of logical processors and enabled
2382 logical processors was retrieved.
2383 @retval EFI_DEVICE_ERROR The calling processor is an AP.
2384 @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL and NumberOfEnabledProcessors
2385 is NULL.
2386 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2387
2388 **/
2389 EFI_STATUS
2390 EFIAPI
2391 MpInitLibGetNumberOfProcessors (
2392 OUT UINTN *NumberOfProcessors OPTIONAL,
2393 OUT UINTN *NumberOfEnabledProcessors OPTIONAL
2394 )
2395 {
2396 CPU_MP_DATA *CpuMpData;
2397 UINTN CallerNumber;
2398 UINTN ProcessorNumber;
2399 UINTN EnabledProcessorNumber;
2400 UINTN Index;
2401
2402 CpuMpData = GetCpuMpData ();
2403
2404 if ((NumberOfProcessors == NULL) && (NumberOfEnabledProcessors == NULL)) {
2405 return EFI_INVALID_PARAMETER;
2406 }
2407
2408 //
2409 // Check whether caller processor is BSP
2410 //
2411 MpInitLibWhoAmI (&CallerNumber);
2412 if (CallerNumber != CpuMpData->BspNumber) {
2413 return EFI_DEVICE_ERROR;
2414 }
2415
2416 ProcessorNumber = CpuMpData->CpuCount;
2417 EnabledProcessorNumber = 0;
2418 for (Index = 0; Index < ProcessorNumber; Index++) {
2419 if (GetApState (&CpuMpData->CpuData[Index]) != CpuStateDisabled) {
2420 EnabledProcessorNumber++;
2421 }
2422 }
2423
2424 if (NumberOfProcessors != NULL) {
2425 *NumberOfProcessors = ProcessorNumber;
2426 }
2427
2428 if (NumberOfEnabledProcessors != NULL) {
2429 *NumberOfEnabledProcessors = EnabledProcessorNumber;
2430 }
2431
2432 return EFI_SUCCESS;
2433 }
2434
2435 /**
2436 Worker function to execute a caller provided function on all enabled APs.
2437
2438 @param[in] Procedure A pointer to the function to be run on
2439 enabled APs of the system.
2440 @param[in] SingleThread If TRUE, then all the enabled APs execute
2441 the function specified by Procedure one by
2442 one, in ascending order of processor handle
2443 number. If FALSE, then all the enabled APs
2444 execute the function specified by Procedure
2445 simultaneously.
2446 @param[in] ExcludeBsp Whether let BSP also trig this task.
2447 @param[in] WaitEvent The event created by the caller with CreateEvent()
2448 service.
2449 @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
2450 APs to return from Procedure, either for
2451 blocking or non-blocking mode.
2452 @param[in] ProcedureArgument The parameter passed into Procedure for
2453 all APs.
2454 @param[out] FailedCpuList If all APs finish successfully, then its
2455 content is set to NULL. If not all APs
2456 finish before timeout expires, then its
2457 content is set to address of the buffer
2458 holding handle numbers of the failed APs.
2459
2460 @retval EFI_SUCCESS In blocking mode, all APs have finished before
2461 the timeout expired.
2462 @retval EFI_SUCCESS In non-blocking mode, function has been dispatched
2463 to all enabled APs.
2464 @retval others Failed to Startup all APs.
2465
2466 **/
2467 EFI_STATUS
2468 StartupAllCPUsWorker (
2469 IN EFI_AP_PROCEDURE Procedure,
2470 IN BOOLEAN SingleThread,
2471 IN BOOLEAN ExcludeBsp,
2472 IN EFI_EVENT WaitEvent OPTIONAL,
2473 IN UINTN TimeoutInMicroseconds,
2474 IN VOID *ProcedureArgument OPTIONAL,
2475 OUT UINTN **FailedCpuList OPTIONAL
2476 )
2477 {
2478 EFI_STATUS Status;
2479 CPU_MP_DATA *CpuMpData;
2480 UINTN ProcessorCount;
2481 UINTN ProcessorNumber;
2482 UINTN CallerNumber;
2483 CPU_AP_DATA *CpuData;
2484 BOOLEAN HasEnabledAp;
2485 CPU_STATE ApState;
2486
2487 CpuMpData = GetCpuMpData ();
2488
2489 if (FailedCpuList != NULL) {
2490 *FailedCpuList = NULL;
2491 }
2492
2493 if ((CpuMpData->CpuCount == 1) && ExcludeBsp) {
2494 return EFI_NOT_STARTED;
2495 }
2496
2497 if (Procedure == NULL) {
2498 return EFI_INVALID_PARAMETER;
2499 }
2500
2501 //
2502 // Check whether caller processor is BSP
2503 //
2504 MpInitLibWhoAmI (&CallerNumber);
2505 if (CallerNumber != CpuMpData->BspNumber) {
2506 return EFI_DEVICE_ERROR;
2507 }
2508
2509 //
2510 // Update AP state
2511 //
2512 CheckAndUpdateApsStatus ();
2513
2514 ProcessorCount = CpuMpData->CpuCount;
2515 HasEnabledAp = FALSE;
2516 //
2517 // Check whether all enabled APs are idle.
2518 // If any enabled AP is not idle, return EFI_NOT_READY.
2519 //
2520 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2521 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2522 if (ProcessorNumber != CpuMpData->BspNumber) {
2523 ApState = GetApState (CpuData);
2524 if (ApState != CpuStateDisabled) {
2525 HasEnabledAp = TRUE;
2526 if (ApState != CpuStateIdle) {
2527 //
2528 // If any enabled APs are busy, return EFI_NOT_READY.
2529 //
2530 return EFI_NOT_READY;
2531 }
2532 }
2533 }
2534 }
2535
2536 if (!HasEnabledAp && ExcludeBsp) {
2537 //
2538 // If no enabled AP exists and not include Bsp to do the procedure, return EFI_NOT_STARTED.
2539 //
2540 return EFI_NOT_STARTED;
2541 }
2542
2543 CpuMpData->RunningCount = 0;
2544 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2545 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2546 CpuData->Waiting = FALSE;
2547 if (ProcessorNumber != CpuMpData->BspNumber) {
2548 if (CpuData->State == CpuStateIdle) {
2549 //
2550 // Mark this processor as responsible for current calling.
2551 //
2552 CpuData->Waiting = TRUE;
2553 CpuMpData->RunningCount++;
2554 }
2555 }
2556 }
2557
2558 CpuMpData->Procedure = Procedure;
2559 CpuMpData->ProcArguments = ProcedureArgument;
2560 CpuMpData->SingleThread = SingleThread;
2561 CpuMpData->FinishedCount = 0;
2562 CpuMpData->FailedCpuList = FailedCpuList;
2563 CpuMpData->ExpectedTime = CalculateTimeout (
2564 TimeoutInMicroseconds,
2565 &CpuMpData->CurrentTime
2566 );
2567 CpuMpData->TotalTime = 0;
2568 CpuMpData->WaitEvent = WaitEvent;
2569
2570 if (!SingleThread) {
2571 WakeUpAP (CpuMpData, TRUE, 0, Procedure, ProcedureArgument, FALSE);
2572 } else {
2573 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2574 if (ProcessorNumber == CallerNumber) {
2575 continue;
2576 }
2577
2578 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
2579 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, Procedure, ProcedureArgument, TRUE);
2580 break;
2581 }
2582 }
2583 }
2584
2585 if (!ExcludeBsp) {
2586 //
2587 // Start BSP.
2588 //
2589 Procedure (ProcedureArgument);
2590 }
2591
2592 Status = EFI_SUCCESS;
2593 if (WaitEvent == NULL) {
2594 do {
2595 Status = CheckAllAPs ();
2596 } while (Status == EFI_NOT_READY);
2597 }
2598
2599 return Status;
2600 }
2601
2602 /**
2603 Worker function to let the caller get one enabled AP to execute a caller-provided
2604 function.
2605
2606 @param[in] Procedure A pointer to the function to be run on
2607 enabled APs of the system.
2608 @param[in] ProcessorNumber The handle number of the AP.
2609 @param[in] WaitEvent The event created by the caller with CreateEvent()
2610 service.
2611 @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
2612 APs to return from Procedure, either for
2613 blocking or non-blocking mode.
2614 @param[in] ProcedureArgument The parameter passed into Procedure for
2615 all APs.
2616 @param[out] Finished If AP returns from Procedure before the
2617 timeout expires, its content is set to TRUE.
2618 Otherwise, the value is set to FALSE.
2619
2620 @retval EFI_SUCCESS In blocking mode, specified AP finished before
2621 the timeout expires.
2622 @retval others Failed to Startup AP.
2623
2624 **/
2625 EFI_STATUS
2626 StartupThisAPWorker (
2627 IN EFI_AP_PROCEDURE Procedure,
2628 IN UINTN ProcessorNumber,
2629 IN EFI_EVENT WaitEvent OPTIONAL,
2630 IN UINTN TimeoutInMicroseconds,
2631 IN VOID *ProcedureArgument OPTIONAL,
2632 OUT BOOLEAN *Finished OPTIONAL
2633 )
2634 {
2635 EFI_STATUS Status;
2636 CPU_MP_DATA *CpuMpData;
2637 CPU_AP_DATA *CpuData;
2638 UINTN CallerNumber;
2639
2640 CpuMpData = GetCpuMpData ();
2641
2642 if (Finished != NULL) {
2643 *Finished = FALSE;
2644 }
2645
2646 //
2647 // Check whether caller processor is BSP
2648 //
2649 MpInitLibWhoAmI (&CallerNumber);
2650 if (CallerNumber != CpuMpData->BspNumber) {
2651 return EFI_DEVICE_ERROR;
2652 }
2653
2654 //
2655 // Check whether processor with the handle specified by ProcessorNumber exists
2656 //
2657 if (ProcessorNumber >= CpuMpData->CpuCount) {
2658 return EFI_NOT_FOUND;
2659 }
2660
2661 //
2662 // Check whether specified processor is BSP
2663 //
2664 if (ProcessorNumber == CpuMpData->BspNumber) {
2665 return EFI_INVALID_PARAMETER;
2666 }
2667
2668 //
2669 // Check parameter Procedure
2670 //
2671 if (Procedure == NULL) {
2672 return EFI_INVALID_PARAMETER;
2673 }
2674
2675 //
2676 // Update AP state
2677 //
2678 CheckAndUpdateApsStatus ();
2679
2680 //
2681 // Check whether specified AP is disabled
2682 //
2683 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateDisabled) {
2684 return EFI_INVALID_PARAMETER;
2685 }
2686
2687 //
2688 // If WaitEvent is not NULL, execute in non-blocking mode.
2689 // BSP saves data for CheckAPsStatus(), and returns EFI_SUCCESS.
2690 // CheckAPsStatus() will check completion and timeout periodically.
2691 //
2692 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2693 CpuData->WaitEvent = WaitEvent;
2694 CpuData->Finished = Finished;
2695 CpuData->ExpectedTime = CalculateTimeout (TimeoutInMicroseconds, &CpuData->CurrentTime);
2696 CpuData->TotalTime = 0;
2697
2698 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, Procedure, ProcedureArgument, TRUE);
2699
2700 //
2701 // If WaitEvent is NULL, execute in blocking mode.
2702 // BSP checks AP's state until it finishes or TimeoutInMicrosecsond expires.
2703 //
2704 Status = EFI_SUCCESS;
2705 if (WaitEvent == NULL) {
2706 do {
2707 Status = CheckThisAP (ProcessorNumber);
2708 } while (Status == EFI_NOT_READY);
2709 }
2710
2711 return Status;
2712 }
2713
2714 /**
2715 Get pointer to CPU MP Data structure from GUIDed HOB.
2716
2717 @return The pointer to CPU MP Data structure.
2718 **/
2719 CPU_MP_DATA *
2720 GetCpuMpDataFromGuidedHob (
2721 VOID
2722 )
2723 {
2724 EFI_HOB_GUID_TYPE *GuidHob;
2725 VOID *DataInHob;
2726 CPU_MP_DATA *CpuMpData;
2727
2728 CpuMpData = NULL;
2729 GuidHob = GetFirstGuidHob (&mCpuInitMpLibHobGuid);
2730 if (GuidHob != NULL) {
2731 DataInHob = GET_GUID_HOB_DATA (GuidHob);
2732 CpuMpData = (CPU_MP_DATA *)(*(UINTN *)DataInHob);
2733 }
2734
2735 return CpuMpData;
2736 }
2737
2738 /**
2739 This service executes a caller provided function on all enabled CPUs.
2740
2741 @param[in] Procedure A pointer to the function to be run on
2742 enabled APs of the system. See type
2743 EFI_AP_PROCEDURE.
2744 @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
2745 APs to return from Procedure, either for
2746 blocking or non-blocking mode. Zero means
2747 infinity. TimeoutInMicroseconds is ignored
2748 for BSP.
2749 @param[in] ProcedureArgument The parameter passed into Procedure for
2750 all APs.
2751
2752 @retval EFI_SUCCESS In blocking mode, all CPUs have finished before
2753 the timeout expired.
2754 @retval EFI_SUCCESS In non-blocking mode, function has been dispatched
2755 to all enabled CPUs.
2756 @retval EFI_DEVICE_ERROR Caller processor is AP.
2757 @retval EFI_NOT_READY Any enabled APs are busy.
2758 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2759 @retval EFI_TIMEOUT In blocking mode, the timeout expired before
2760 all enabled APs have finished.
2761 @retval EFI_INVALID_PARAMETER Procedure is NULL.
2762
2763 **/
2764 EFI_STATUS
2765 EFIAPI
2766 MpInitLibStartupAllCPUs (
2767 IN EFI_AP_PROCEDURE Procedure,
2768 IN UINTN TimeoutInMicroseconds,
2769 IN VOID *ProcedureArgument OPTIONAL
2770 )
2771 {
2772 return StartupAllCPUsWorker (
2773 Procedure,
2774 FALSE,
2775 FALSE,
2776 NULL,
2777 TimeoutInMicroseconds,
2778 ProcedureArgument,
2779 NULL
2780 );
2781 }
2782
2783 /**
2784 The function check if the specified Attr is set.
2785
2786 @param[in] CurrentAttr The current attribute.
2787 @param[in] Attr The attribute to check.
2788
2789 @retval TRUE The specified Attr is set.
2790 @retval FALSE The specified Attr is not set.
2791
2792 **/
2793 STATIC
2794 BOOLEAN
2795 AmdMemEncryptionAttrCheck (
2796 IN UINT64 CurrentAttr,
2797 IN CONFIDENTIAL_COMPUTING_GUEST_ATTR Attr
2798 )
2799 {
2800 switch (Attr) {
2801 case CCAttrAmdSev:
2802 //
2803 // SEV is automatically enabled if SEV-ES or SEV-SNP is active.
2804 //
2805 return CurrentAttr >= CCAttrAmdSev;
2806 case CCAttrAmdSevEs:
2807 //
2808 // SEV-ES is automatically enabled if SEV-SNP is active.
2809 //
2810 return CurrentAttr >= CCAttrAmdSevEs;
2811 case CCAttrAmdSevSnp:
2812 return CurrentAttr == CCAttrAmdSevSnp;
2813 default:
2814 return FALSE;
2815 }
2816 }
2817
2818 /**
2819 Check if the specified confidential computing attribute is active.
2820
2821 @param[in] Attr The attribute to check.
2822
2823 @retval TRUE The specified Attr is active.
2824 @retval FALSE The specified Attr is not active.
2825
2826 **/
2827 BOOLEAN
2828 EFIAPI
2829 ConfidentialComputingGuestHas (
2830 IN CONFIDENTIAL_COMPUTING_GUEST_ATTR Attr
2831 )
2832 {
2833 UINT64 CurrentAttr;
2834
2835 //
2836 // Get the current CC attribute.
2837 //
2838 CurrentAttr = PcdGet64 (PcdConfidentialComputingGuestAttr);
2839
2840 //
2841 // If attr is for the AMD group then call AMD specific checks.
2842 //
2843 if (((RShiftU64 (CurrentAttr, 8)) & 0xff) == 1) {
2844 return AmdMemEncryptionAttrCheck (CurrentAttr, Attr);
2845 }
2846
2847 return (CurrentAttr == Attr);
2848 }