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