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