]> git.proxmox.com Git - mirror_edk2.git/blob - UefiCpuPkg/Library/MpInitLib/MpLib.c
33374888922a85d80fbe4f4735f1f24446b03926
[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 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 } else {
623 //
624 // Execute AP function if AP is ready
625 //
626 GetProcessorNumber (CpuMpData, &ProcessorNumber);
627 //
628 // Clear AP start-up signal when AP waken up
629 //
630 ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;
631 InterlockedCompareExchange32 (
632 (UINT32 *) ApStartupSignalBuffer,
633 WAKEUP_AP_SIGNAL,
634 0
635 );
636 if (CpuMpData->ApLoopMode == ApInHltLoop) {
637 //
638 // Restore AP's volatile registers saved
639 //
640 RestoreVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters, TRUE);
641 } else {
642 //
643 // The CPU driver might not flush TLB for APs on spot after updating
644 // page attributes. AP in mwait loop mode needs to take care of it when
645 // woken up.
646 //
647 CpuFlushTlb ();
648 }
649
650 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateReady) {
651 Procedure = (EFI_AP_PROCEDURE)CpuMpData->CpuData[ProcessorNumber].ApFunction;
652 Parameter = (VOID *) CpuMpData->CpuData[ProcessorNumber].ApFunctionArgument;
653 if (Procedure != NULL) {
654 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateBusy);
655 //
656 // Enable source debugging on AP function
657 //
658 EnableDebugAgent ();
659 //
660 // Invoke AP function here
661 //
662 Procedure (Parameter);
663 CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;
664 if (CpuMpData->SwitchBspFlag) {
665 //
666 // Re-get the processor number due to BSP/AP maybe exchange in AP function
667 //
668 GetProcessorNumber (CpuMpData, &ProcessorNumber);
669 CpuMpData->CpuData[ProcessorNumber].ApFunction = 0;
670 CpuMpData->CpuData[ProcessorNumber].ApFunctionArgument = 0;
671 ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;
672 CpuInfoInHob[ProcessorNumber].ApTopOfStack = CpuInfoInHob[CpuMpData->NewBspNumber].ApTopOfStack;
673 } else {
674 if (CpuInfoInHob[ProcessorNumber].ApicId != GetApicId () ||
675 CpuInfoInHob[ProcessorNumber].InitialApicId != GetInitialApicId ()) {
676 if (CurrentApicMode != GetApicMode ()) {
677 //
678 // If APIC mode change happened during AP function execution,
679 // we do not support APIC ID value changed.
680 //
681 ASSERT (FALSE);
682 CpuDeadLoop ();
683 } else {
684 //
685 // Re-get the CPU APICID and Initial APICID if they are changed
686 //
687 CpuInfoInHob[ProcessorNumber].ApicId = GetApicId ();
688 CpuInfoInHob[ProcessorNumber].InitialApicId = GetInitialApicId ();
689 }
690 }
691 }
692 }
693 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateFinished);
694 }
695 }
696
697 //
698 // AP finished executing C code
699 //
700 InterlockedIncrement ((UINT32 *) &CpuMpData->FinishedCount);
701 InterlockedDecrement ((UINT32 *) &CpuMpData->MpCpuExchangeInfo->NumApsExecuting);
702
703 //
704 // Place AP is specified loop mode
705 //
706 if (CpuMpData->ApLoopMode == ApInHltLoop) {
707 //
708 // Save AP volatile registers
709 //
710 SaveVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters);
711 //
712 // Place AP in HLT-loop
713 //
714 while (TRUE) {
715 DisableInterrupts ();
716 CpuSleep ();
717 CpuPause ();
718 }
719 }
720 while (TRUE) {
721 DisableInterrupts ();
722 if (CpuMpData->ApLoopMode == ApInMwaitLoop) {
723 //
724 // Place AP in MWAIT-loop
725 //
726 AsmMonitor ((UINTN) ApStartupSignalBuffer, 0, 0);
727 if (*ApStartupSignalBuffer != WAKEUP_AP_SIGNAL) {
728 //
729 // Check AP start-up signal again.
730 // If AP start-up signal is not set, place AP into
731 // the specified C-state
732 //
733 AsmMwait (CpuMpData->ApTargetCState << 4, 0);
734 }
735 } else if (CpuMpData->ApLoopMode == ApInRunLoop) {
736 //
737 // Place AP in Run-loop
738 //
739 CpuPause ();
740 } else {
741 ASSERT (FALSE);
742 }
743
744 //
745 // If AP start-up signal is written, AP is waken up
746 // otherwise place AP in loop again
747 //
748 if (*ApStartupSignalBuffer == WAKEUP_AP_SIGNAL) {
749 break;
750 }
751 }
752 }
753 }
754
755 /**
756 Wait for AP wakeup and write AP start-up signal till AP is waken up.
757
758 @param[in] ApStartupSignalBuffer Pointer to AP wakeup signal
759 **/
760 VOID
761 WaitApWakeup (
762 IN volatile UINT32 *ApStartupSignalBuffer
763 )
764 {
765 //
766 // If AP is waken up, StartupApSignal should be cleared.
767 // Otherwise, write StartupApSignal again till AP waken up.
768 //
769 while (InterlockedCompareExchange32 (
770 (UINT32 *) ApStartupSignalBuffer,
771 WAKEUP_AP_SIGNAL,
772 WAKEUP_AP_SIGNAL
773 ) != 0) {
774 CpuPause ();
775 }
776 }
777
778 /**
779 This function will fill the exchange info structure.
780
781 @param[in] CpuMpData Pointer to CPU MP Data
782
783 **/
784 VOID
785 FillExchangeInfoData (
786 IN CPU_MP_DATA *CpuMpData
787 )
788 {
789 volatile MP_CPU_EXCHANGE_INFO *ExchangeInfo;
790 UINTN Size;
791 IA32_SEGMENT_DESCRIPTOR *Selector;
792
793 ExchangeInfo = CpuMpData->MpCpuExchangeInfo;
794 ExchangeInfo->Lock = 0;
795 ExchangeInfo->StackStart = CpuMpData->Buffer;
796 ExchangeInfo->StackSize = CpuMpData->CpuApStackSize;
797 ExchangeInfo->BufferStart = CpuMpData->WakeupBuffer;
798 ExchangeInfo->ModeOffset = CpuMpData->AddressMap.ModeEntryOffset;
799
800 ExchangeInfo->CodeSegment = AsmReadCs ();
801 ExchangeInfo->DataSegment = AsmReadDs ();
802
803 ExchangeInfo->Cr3 = AsmReadCr3 ();
804
805 ExchangeInfo->CFunction = (UINTN) ApWakeupFunction;
806 ExchangeInfo->ApIndex = 0;
807 ExchangeInfo->NumApsExecuting = 0;
808 ExchangeInfo->InitFlag = (UINTN) CpuMpData->InitFlag;
809 ExchangeInfo->CpuInfo = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;
810 ExchangeInfo->CpuMpData = CpuMpData;
811
812 ExchangeInfo->EnableExecuteDisable = IsBspExecuteDisableEnabled ();
813
814 ExchangeInfo->InitializeFloatingPointUnitsAddress = (UINTN)InitializeFloatingPointUnits;
815
816 //
817 // Get the BSP's data of GDT and IDT
818 //
819 AsmReadGdtr ((IA32_DESCRIPTOR *) &ExchangeInfo->GdtrProfile);
820 AsmReadIdtr ((IA32_DESCRIPTOR *) &ExchangeInfo->IdtrProfile);
821
822 //
823 // Find a 32-bit code segment
824 //
825 Selector = (IA32_SEGMENT_DESCRIPTOR *)ExchangeInfo->GdtrProfile.Base;
826 Size = ExchangeInfo->GdtrProfile.Limit + 1;
827 while (Size > 0) {
828 if (Selector->Bits.L == 0 && Selector->Bits.Type >= 8) {
829 ExchangeInfo->ModeTransitionSegment =
830 (UINT16)((UINTN)Selector - ExchangeInfo->GdtrProfile.Base);
831 break;
832 }
833 Selector += 1;
834 Size -= sizeof (IA32_SEGMENT_DESCRIPTOR);
835 }
836
837 //
838 // Copy all 32-bit code and 64-bit code into memory with type of
839 // EfiBootServicesCode to avoid page fault if NX memory protection is enabled.
840 //
841 if (CpuMpData->WakeupBufferHigh != 0) {
842 Size = CpuMpData->AddressMap.RendezvousFunnelSize -
843 CpuMpData->AddressMap.ModeTransitionOffset;
844 CopyMem (
845 (VOID *)CpuMpData->WakeupBufferHigh,
846 CpuMpData->AddressMap.RendezvousFunnelAddress +
847 CpuMpData->AddressMap.ModeTransitionOffset,
848 Size
849 );
850
851 ExchangeInfo->ModeTransitionMemory = (UINT32)CpuMpData->WakeupBufferHigh;
852 } else {
853 ExchangeInfo->ModeTransitionMemory = (UINT32)
854 (ExchangeInfo->BufferStart + CpuMpData->AddressMap.ModeTransitionOffset);
855 }
856
857 ExchangeInfo->ModeHighMemory = ExchangeInfo->ModeTransitionMemory +
858 (UINT32)ExchangeInfo->ModeOffset -
859 (UINT32)CpuMpData->AddressMap.ModeTransitionOffset;
860 ExchangeInfo->ModeHighSegment = (UINT16)ExchangeInfo->CodeSegment;
861 }
862
863 /**
864 Helper function that waits until the finished AP count reaches the specified
865 limit, or the specified timeout elapses (whichever comes first).
866
867 @param[in] CpuMpData Pointer to CPU MP Data.
868 @param[in] FinishedApLimit The number of finished APs to wait for.
869 @param[in] TimeLimit The number of microseconds to wait for.
870 **/
871 VOID
872 TimedWaitForApFinish (
873 IN CPU_MP_DATA *CpuMpData,
874 IN UINT32 FinishedApLimit,
875 IN UINT32 TimeLimit
876 );
877
878 /**
879 Get available system memory below 1MB by specified size.
880
881 @param[in] CpuMpData The pointer to CPU MP Data structure.
882 **/
883 VOID
884 BackupAndPrepareWakeupBuffer(
885 IN CPU_MP_DATA *CpuMpData
886 )
887 {
888 CopyMem (
889 (VOID *) CpuMpData->BackupBuffer,
890 (VOID *) CpuMpData->WakeupBuffer,
891 CpuMpData->BackupBufferSize
892 );
893 CopyMem (
894 (VOID *) CpuMpData->WakeupBuffer,
895 (VOID *) CpuMpData->AddressMap.RendezvousFunnelAddress,
896 CpuMpData->AddressMap.RendezvousFunnelSize
897 );
898 }
899
900 /**
901 Restore wakeup buffer data.
902
903 @param[in] CpuMpData The pointer to CPU MP Data structure.
904 **/
905 VOID
906 RestoreWakeupBuffer(
907 IN CPU_MP_DATA *CpuMpData
908 )
909 {
910 CopyMem (
911 (VOID *) CpuMpData->WakeupBuffer,
912 (VOID *) CpuMpData->BackupBuffer,
913 CpuMpData->BackupBufferSize
914 );
915 }
916
917 /**
918 Allocate reset vector buffer.
919
920 @param[in, out] CpuMpData The pointer to CPU MP Data structure.
921 **/
922 VOID
923 AllocateResetVector (
924 IN OUT CPU_MP_DATA *CpuMpData
925 )
926 {
927 UINTN ApResetVectorSize;
928
929 if (CpuMpData->WakeupBuffer == (UINTN) -1) {
930 ApResetVectorSize = CpuMpData->AddressMap.RendezvousFunnelSize +
931 sizeof (MP_CPU_EXCHANGE_INFO);
932
933 CpuMpData->WakeupBuffer = GetWakeupBuffer (ApResetVectorSize);
934 CpuMpData->MpCpuExchangeInfo = (MP_CPU_EXCHANGE_INFO *) (UINTN)
935 (CpuMpData->WakeupBuffer + CpuMpData->AddressMap.RendezvousFunnelSize);
936 CpuMpData->WakeupBufferHigh = GetModeTransitionBuffer (
937 CpuMpData->AddressMap.RendezvousFunnelSize -
938 CpuMpData->AddressMap.ModeTransitionOffset
939 );
940 }
941 BackupAndPrepareWakeupBuffer (CpuMpData);
942 }
943
944 /**
945 Free AP reset vector buffer.
946
947 @param[in] CpuMpData The pointer to CPU MP Data structure.
948 **/
949 VOID
950 FreeResetVector (
951 IN CPU_MP_DATA *CpuMpData
952 )
953 {
954 RestoreWakeupBuffer (CpuMpData);
955 }
956
957 /**
958 This function will be called by BSP to wakeup AP.
959
960 @param[in] CpuMpData Pointer to CPU MP Data
961 @param[in] Broadcast TRUE: Send broadcast IPI to all APs
962 FALSE: Send IPI to AP by ApicId
963 @param[in] ProcessorNumber The handle number of specified processor
964 @param[in] Procedure The function to be invoked by AP
965 @param[in] ProcedureArgument The argument to be passed into AP function
966 @param[in] WakeUpDisabledAps Whether need to wake up disabled APs in broadcast mode.
967 **/
968 VOID
969 WakeUpAP (
970 IN CPU_MP_DATA *CpuMpData,
971 IN BOOLEAN Broadcast,
972 IN UINTN ProcessorNumber,
973 IN EFI_AP_PROCEDURE Procedure, OPTIONAL
974 IN VOID *ProcedureArgument, OPTIONAL
975 IN BOOLEAN WakeUpDisabledAps
976 )
977 {
978 volatile MP_CPU_EXCHANGE_INFO *ExchangeInfo;
979 UINTN Index;
980 CPU_AP_DATA *CpuData;
981 BOOLEAN ResetVectorRequired;
982 CPU_INFO_IN_HOB *CpuInfoInHob;
983
984 CpuMpData->FinishedCount = 0;
985 ResetVectorRequired = FALSE;
986
987 if (CpuMpData->WakeUpByInitSipiSipi ||
988 CpuMpData->InitFlag != ApInitDone) {
989 ResetVectorRequired = TRUE;
990 AllocateResetVector (CpuMpData);
991 FillExchangeInfoData (CpuMpData);
992 SaveLocalApicTimerSetting (CpuMpData);
993 }
994
995 if (CpuMpData->ApLoopMode == ApInMwaitLoop) {
996 //
997 // Get AP target C-state each time when waking up AP,
998 // for it maybe updated by platform again
999 //
1000 CpuMpData->ApTargetCState = PcdGet8 (PcdCpuApTargetCstate);
1001 }
1002
1003 ExchangeInfo = CpuMpData->MpCpuExchangeInfo;
1004
1005 if (Broadcast) {
1006 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1007 if (Index != CpuMpData->BspNumber) {
1008 CpuData = &CpuMpData->CpuData[Index];
1009 //
1010 // All AP(include disabled AP) will be woke up by INIT-SIPI-SIPI, but
1011 // the AP procedure will be skipped for disabled AP because AP state
1012 // is not CpuStateReady.
1013 //
1014 if (GetApState (CpuData) == CpuStateDisabled && !WakeUpDisabledAps) {
1015 continue;
1016 }
1017
1018 CpuData->ApFunction = (UINTN) Procedure;
1019 CpuData->ApFunctionArgument = (UINTN) ProcedureArgument;
1020 SetApState (CpuData, CpuStateReady);
1021 if (CpuMpData->InitFlag != ApInitConfig) {
1022 *(UINT32 *) CpuData->StartupApSignal = WAKEUP_AP_SIGNAL;
1023 }
1024 }
1025 }
1026 if (ResetVectorRequired) {
1027 //
1028 // Wakeup all APs
1029 //
1030 SendInitSipiSipiAllExcludingSelf ((UINT32) ExchangeInfo->BufferStart);
1031 }
1032 if (CpuMpData->InitFlag == ApInitConfig) {
1033 //
1034 // Here support two methods to collect AP count through adjust
1035 // PcdCpuApInitTimeOutInMicroSeconds values.
1036 //
1037 // one way is set a value to just let the first AP to start the
1038 // initialization, then through the later while loop to wait all Aps
1039 // finsh the initialization.
1040 // The other way is set a value to let all APs finished the initialzation.
1041 // In this case, the later while loop is useless.
1042 //
1043 TimedWaitForApFinish (
1044 CpuMpData,
1045 PcdGet32 (PcdCpuMaxLogicalProcessorNumber) - 1,
1046 PcdGet32 (PcdCpuApInitTimeOutInMicroSeconds)
1047 );
1048
1049 while (CpuMpData->MpCpuExchangeInfo->NumApsExecuting != 0) {
1050 CpuPause();
1051 }
1052 } else {
1053 //
1054 // Wait all APs waken up if this is not the 1st broadcast of SIPI
1055 //
1056 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1057 CpuData = &CpuMpData->CpuData[Index];
1058 if (Index != CpuMpData->BspNumber) {
1059 WaitApWakeup (CpuData->StartupApSignal);
1060 }
1061 }
1062 }
1063 } else {
1064 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1065 CpuData->ApFunction = (UINTN) Procedure;
1066 CpuData->ApFunctionArgument = (UINTN) ProcedureArgument;
1067 SetApState (CpuData, CpuStateReady);
1068 //
1069 // Wakeup specified AP
1070 //
1071 ASSERT (CpuMpData->InitFlag != ApInitConfig);
1072 *(UINT32 *) CpuData->StartupApSignal = WAKEUP_AP_SIGNAL;
1073 if (ResetVectorRequired) {
1074 CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;
1075 SendInitSipiSipi (
1076 CpuInfoInHob[ProcessorNumber].ApicId,
1077 (UINT32) ExchangeInfo->BufferStart
1078 );
1079 }
1080 //
1081 // Wait specified AP waken up
1082 //
1083 WaitApWakeup (CpuData->StartupApSignal);
1084 }
1085
1086 if (ResetVectorRequired) {
1087 FreeResetVector (CpuMpData);
1088 }
1089
1090 //
1091 // After one round of Wakeup Ap actions, need to re-sync ApLoopMode with
1092 // WakeUpByInitSipiSipi flag. WakeUpByInitSipiSipi flag maybe changed by
1093 // S3SmmInitDone Ppi.
1094 //
1095 CpuMpData->WakeUpByInitSipiSipi = (CpuMpData->ApLoopMode == ApInHltLoop);
1096 }
1097
1098 /**
1099 Calculate timeout value and return the current performance counter value.
1100
1101 Calculate the number of performance counter ticks required for a timeout.
1102 If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1103 as infinity.
1104
1105 @param[in] TimeoutInMicroseconds Timeout value in microseconds.
1106 @param[out] CurrentTime Returns the current value of the performance counter.
1107
1108 @return Expected time stamp counter for timeout.
1109 If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1110 as infinity.
1111
1112 **/
1113 UINT64
1114 CalculateTimeout (
1115 IN UINTN TimeoutInMicroseconds,
1116 OUT UINT64 *CurrentTime
1117 )
1118 {
1119 UINT64 TimeoutInSeconds;
1120 UINT64 TimestampCounterFreq;
1121
1122 //
1123 // Read the current value of the performance counter
1124 //
1125 *CurrentTime = GetPerformanceCounter ();
1126
1127 //
1128 // If TimeoutInMicroseconds is 0, return value is also 0, which is recognized
1129 // as infinity.
1130 //
1131 if (TimeoutInMicroseconds == 0) {
1132 return 0;
1133 }
1134
1135 //
1136 // GetPerformanceCounterProperties () returns the timestamp counter's frequency
1137 // in Hz.
1138 //
1139 TimestampCounterFreq = GetPerformanceCounterProperties (NULL, NULL);
1140
1141 //
1142 // Check the potential overflow before calculate the number of ticks for the timeout value.
1143 //
1144 if (DivU64x64Remainder (MAX_UINT64, TimeoutInMicroseconds, NULL) < TimestampCounterFreq) {
1145 //
1146 // Convert microseconds into seconds if direct multiplication overflows
1147 //
1148 TimeoutInSeconds = DivU64x32 (TimeoutInMicroseconds, 1000000);
1149 //
1150 // Assertion if the final tick count exceeds MAX_UINT64
1151 //
1152 ASSERT (DivU64x64Remainder (MAX_UINT64, TimeoutInSeconds, NULL) >= TimestampCounterFreq);
1153 return MultU64x64 (TimestampCounterFreq, TimeoutInSeconds);
1154 } else {
1155 //
1156 // No overflow case, multiply the return value with TimeoutInMicroseconds and then divide
1157 // it by 1,000,000, to get the number of ticks for the timeout value.
1158 //
1159 return DivU64x32 (
1160 MultU64x64 (
1161 TimestampCounterFreq,
1162 TimeoutInMicroseconds
1163 ),
1164 1000000
1165 );
1166 }
1167 }
1168
1169 /**
1170 Checks whether timeout expires.
1171
1172 Check whether the number of elapsed performance counter ticks required for
1173 a timeout condition has been reached.
1174 If Timeout is zero, which means infinity, return value is always FALSE.
1175
1176 @param[in, out] PreviousTime On input, the value of the performance counter
1177 when it was last read.
1178 On output, the current value of the performance
1179 counter
1180 @param[in] TotalTime The total amount of elapsed time in performance
1181 counter ticks.
1182 @param[in] Timeout The number of performance counter ticks required
1183 to reach a timeout condition.
1184
1185 @retval TRUE A timeout condition has been reached.
1186 @retval FALSE A timeout condition has not been reached.
1187
1188 **/
1189 BOOLEAN
1190 CheckTimeout (
1191 IN OUT UINT64 *PreviousTime,
1192 IN UINT64 *TotalTime,
1193 IN UINT64 Timeout
1194 )
1195 {
1196 UINT64 Start;
1197 UINT64 End;
1198 UINT64 CurrentTime;
1199 INT64 Delta;
1200 INT64 Cycle;
1201
1202 if (Timeout == 0) {
1203 return FALSE;
1204 }
1205 GetPerformanceCounterProperties (&Start, &End);
1206 Cycle = End - Start;
1207 if (Cycle < 0) {
1208 Cycle = -Cycle;
1209 }
1210 Cycle++;
1211 CurrentTime = GetPerformanceCounter();
1212 Delta = (INT64) (CurrentTime - *PreviousTime);
1213 if (Start > End) {
1214 Delta = -Delta;
1215 }
1216 if (Delta < 0) {
1217 Delta += Cycle;
1218 }
1219 *TotalTime += Delta;
1220 *PreviousTime = CurrentTime;
1221 if (*TotalTime > Timeout) {
1222 return TRUE;
1223 }
1224 return FALSE;
1225 }
1226
1227 /**
1228 Helper function that waits until the finished AP count reaches the specified
1229 limit, or the specified timeout elapses (whichever comes first).
1230
1231 @param[in] CpuMpData Pointer to CPU MP Data.
1232 @param[in] FinishedApLimit The number of finished APs to wait for.
1233 @param[in] TimeLimit The number of microseconds to wait for.
1234 **/
1235 VOID
1236 TimedWaitForApFinish (
1237 IN CPU_MP_DATA *CpuMpData,
1238 IN UINT32 FinishedApLimit,
1239 IN UINT32 TimeLimit
1240 )
1241 {
1242 //
1243 // CalculateTimeout() and CheckTimeout() consider a TimeLimit of 0
1244 // "infinity", so check for (TimeLimit == 0) explicitly.
1245 //
1246 if (TimeLimit == 0) {
1247 return;
1248 }
1249
1250 CpuMpData->TotalTime = 0;
1251 CpuMpData->ExpectedTime = CalculateTimeout (
1252 TimeLimit,
1253 &CpuMpData->CurrentTime
1254 );
1255 while (CpuMpData->FinishedCount < FinishedApLimit &&
1256 !CheckTimeout (
1257 &CpuMpData->CurrentTime,
1258 &CpuMpData->TotalTime,
1259 CpuMpData->ExpectedTime
1260 )) {
1261 CpuPause ();
1262 }
1263
1264 if (CpuMpData->FinishedCount >= FinishedApLimit) {
1265 DEBUG ((
1266 DEBUG_VERBOSE,
1267 "%a: reached FinishedApLimit=%u in %Lu microseconds\n",
1268 __FUNCTION__,
1269 FinishedApLimit,
1270 DivU64x64Remainder (
1271 MultU64x32 (CpuMpData->TotalTime, 1000000),
1272 GetPerformanceCounterProperties (NULL, NULL),
1273 NULL
1274 )
1275 ));
1276 }
1277 }
1278
1279 /**
1280 Reset an AP to Idle state.
1281
1282 Any task being executed by the AP will be aborted and the AP
1283 will be waiting for a new task in Wait-For-SIPI state.
1284
1285 @param[in] ProcessorNumber The handle number of processor.
1286 **/
1287 VOID
1288 ResetProcessorToIdleState (
1289 IN UINTN ProcessorNumber
1290 )
1291 {
1292 CPU_MP_DATA *CpuMpData;
1293
1294 CpuMpData = GetCpuMpData ();
1295
1296 CpuMpData->InitFlag = ApInitReconfig;
1297 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, NULL, NULL, TRUE);
1298 while (CpuMpData->FinishedCount < 1) {
1299 CpuPause ();
1300 }
1301 CpuMpData->InitFlag = ApInitDone;
1302
1303 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle);
1304 }
1305
1306 /**
1307 Searches for the next waiting AP.
1308
1309 Search for the next AP that is put in waiting state by single-threaded StartupAllAPs().
1310
1311 @param[out] NextProcessorNumber Pointer to the processor number of the next waiting AP.
1312
1313 @retval EFI_SUCCESS The next waiting AP has been found.
1314 @retval EFI_NOT_FOUND No waiting AP exists.
1315
1316 **/
1317 EFI_STATUS
1318 GetNextWaitingProcessorNumber (
1319 OUT UINTN *NextProcessorNumber
1320 )
1321 {
1322 UINTN ProcessorNumber;
1323 CPU_MP_DATA *CpuMpData;
1324
1325 CpuMpData = GetCpuMpData ();
1326
1327 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1328 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
1329 *NextProcessorNumber = ProcessorNumber;
1330 return EFI_SUCCESS;
1331 }
1332 }
1333
1334 return EFI_NOT_FOUND;
1335 }
1336
1337 /** Checks status of specified AP.
1338
1339 This function checks whether the specified AP has finished the task assigned
1340 by StartupThisAP(), and whether timeout expires.
1341
1342 @param[in] ProcessorNumber The handle number of processor.
1343
1344 @retval EFI_SUCCESS Specified AP has finished task assigned by StartupThisAPs().
1345 @retval EFI_TIMEOUT The timeout expires.
1346 @retval EFI_NOT_READY Specified AP has not finished task and timeout has not expired.
1347 **/
1348 EFI_STATUS
1349 CheckThisAP (
1350 IN UINTN ProcessorNumber
1351 )
1352 {
1353 CPU_MP_DATA *CpuMpData;
1354 CPU_AP_DATA *CpuData;
1355
1356 CpuMpData = GetCpuMpData ();
1357 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1358
1359 //
1360 // Check the CPU state of AP. If it is CpuStateIdle, then the AP has finished its task.
1361 // Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
1362 // value of state after setting the it to CpuStateIdle, so BSP can safely make use of its value.
1363 //
1364 //
1365 // If the AP finishes for StartupThisAP(), return EFI_SUCCESS.
1366 //
1367 if (GetApState(CpuData) == CpuStateFinished) {
1368 if (CpuData->Finished != NULL) {
1369 *(CpuData->Finished) = TRUE;
1370 }
1371 SetApState (CpuData, CpuStateIdle);
1372 return EFI_SUCCESS;
1373 } else {
1374 //
1375 // If timeout expires for StartupThisAP(), report timeout.
1376 //
1377 if (CheckTimeout (&CpuData->CurrentTime, &CpuData->TotalTime, CpuData->ExpectedTime)) {
1378 if (CpuData->Finished != NULL) {
1379 *(CpuData->Finished) = FALSE;
1380 }
1381 //
1382 // Reset failed AP to idle state
1383 //
1384 ResetProcessorToIdleState (ProcessorNumber);
1385
1386 return EFI_TIMEOUT;
1387 }
1388 }
1389 return EFI_NOT_READY;
1390 }
1391
1392 /**
1393 Checks status of all APs.
1394
1395 This function checks whether all APs have finished task assigned by StartupAllAPs(),
1396 and whether timeout expires.
1397
1398 @retval EFI_SUCCESS All APs have finished task assigned by StartupAllAPs().
1399 @retval EFI_TIMEOUT The timeout expires.
1400 @retval EFI_NOT_READY APs have not finished task and timeout has not expired.
1401 **/
1402 EFI_STATUS
1403 CheckAllAPs (
1404 VOID
1405 )
1406 {
1407 UINTN ProcessorNumber;
1408 UINTN NextProcessorNumber;
1409 UINTN ListIndex;
1410 EFI_STATUS Status;
1411 CPU_MP_DATA *CpuMpData;
1412 CPU_AP_DATA *CpuData;
1413
1414 CpuMpData = GetCpuMpData ();
1415
1416 NextProcessorNumber = 0;
1417
1418 //
1419 // Go through all APs that are responsible for the StartupAllAPs().
1420 //
1421 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1422 if (!CpuMpData->CpuData[ProcessorNumber].Waiting) {
1423 continue;
1424 }
1425
1426 CpuData = &CpuMpData->CpuData[ProcessorNumber];
1427 //
1428 // Check the CPU state of AP. If it is CpuStateIdle, then the AP has finished its task.
1429 // Only BSP and corresponding AP access this unit of CPU Data. This means the AP will not modify the
1430 // value of state after setting the it to CpuStateIdle, so BSP can safely make use of its value.
1431 //
1432 if (GetApState(CpuData) == CpuStateFinished) {
1433 CpuMpData->RunningCount --;
1434 CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE;
1435 SetApState(CpuData, CpuStateIdle);
1436
1437 //
1438 // If in Single Thread mode, then search for the next waiting AP for execution.
1439 //
1440 if (CpuMpData->SingleThread) {
1441 Status = GetNextWaitingProcessorNumber (&NextProcessorNumber);
1442
1443 if (!EFI_ERROR (Status)) {
1444 WakeUpAP (
1445 CpuMpData,
1446 FALSE,
1447 (UINT32) NextProcessorNumber,
1448 CpuMpData->Procedure,
1449 CpuMpData->ProcArguments,
1450 TRUE
1451 );
1452 }
1453 }
1454 }
1455 }
1456
1457 //
1458 // If all APs finish, return EFI_SUCCESS.
1459 //
1460 if (CpuMpData->RunningCount == 0) {
1461 return EFI_SUCCESS;
1462 }
1463
1464 //
1465 // If timeout expires, report timeout.
1466 //
1467 if (CheckTimeout (
1468 &CpuMpData->CurrentTime,
1469 &CpuMpData->TotalTime,
1470 CpuMpData->ExpectedTime)
1471 ) {
1472 //
1473 // If FailedCpuList is not NULL, record all failed APs in it.
1474 //
1475 if (CpuMpData->FailedCpuList != NULL) {
1476 *CpuMpData->FailedCpuList =
1477 AllocatePool ((CpuMpData->RunningCount + 1) * sizeof (UINTN));
1478 ASSERT (*CpuMpData->FailedCpuList != NULL);
1479 }
1480 ListIndex = 0;
1481
1482 for (ProcessorNumber = 0; ProcessorNumber < CpuMpData->CpuCount; ProcessorNumber++) {
1483 //
1484 // Check whether this processor is responsible for StartupAllAPs().
1485 //
1486 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
1487 //
1488 // Reset failed APs to idle state
1489 //
1490 ResetProcessorToIdleState (ProcessorNumber);
1491 CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE;
1492 if (CpuMpData->FailedCpuList != NULL) {
1493 (*CpuMpData->FailedCpuList)[ListIndex++] = ProcessorNumber;
1494 }
1495 }
1496 }
1497 if (CpuMpData->FailedCpuList != NULL) {
1498 (*CpuMpData->FailedCpuList)[ListIndex] = END_OF_CPU_LIST;
1499 }
1500 return EFI_TIMEOUT;
1501 }
1502 return EFI_NOT_READY;
1503 }
1504
1505 /**
1506 MP Initialize Library initialization.
1507
1508 This service will allocate AP reset vector and wakeup all APs to do APs
1509 initialization.
1510
1511 This service must be invoked before all other MP Initialize Library
1512 service are invoked.
1513
1514 @retval EFI_SUCCESS MP initialization succeeds.
1515 @retval Others MP initialization fails.
1516
1517 **/
1518 EFI_STATUS
1519 EFIAPI
1520 MpInitLibInitialize (
1521 VOID
1522 )
1523 {
1524 CPU_MP_DATA *OldCpuMpData;
1525 CPU_INFO_IN_HOB *CpuInfoInHob;
1526 UINT32 MaxLogicalProcessorNumber;
1527 UINT32 ApStackSize;
1528 MP_ASSEMBLY_ADDRESS_MAP AddressMap;
1529 CPU_VOLATILE_REGISTERS VolatileRegisters;
1530 UINTN BufferSize;
1531 UINT32 MonitorFilterSize;
1532 VOID *MpBuffer;
1533 UINTN Buffer;
1534 CPU_MP_DATA *CpuMpData;
1535 UINT8 ApLoopMode;
1536 UINT8 *MonitorBuffer;
1537 UINTN Index;
1538 UINTN ApResetVectorSize;
1539 UINTN BackupBufferAddr;
1540 UINTN ApIdtBase;
1541 VOID *MicrocodePatchInRam;
1542
1543 OldCpuMpData = GetCpuMpDataFromGuidedHob ();
1544 if (OldCpuMpData == NULL) {
1545 MaxLogicalProcessorNumber = PcdGet32(PcdCpuMaxLogicalProcessorNumber);
1546 } else {
1547 MaxLogicalProcessorNumber = OldCpuMpData->CpuCount;
1548 }
1549 ASSERT (MaxLogicalProcessorNumber != 0);
1550
1551 AsmGetAddressMap (&AddressMap);
1552 ApResetVectorSize = AddressMap.RendezvousFunnelSize + sizeof (MP_CPU_EXCHANGE_INFO);
1553 ApStackSize = PcdGet32(PcdCpuApStackSize);
1554 ApLoopMode = GetApLoopMode (&MonitorFilterSize);
1555
1556 //
1557 // Save BSP's Control registers for APs.
1558 //
1559 SaveVolatileRegisters (&VolatileRegisters);
1560
1561 BufferSize = ApStackSize * MaxLogicalProcessorNumber;
1562 BufferSize += MonitorFilterSize * MaxLogicalProcessorNumber;
1563 BufferSize += ApResetVectorSize;
1564 BufferSize = ALIGN_VALUE (BufferSize, 8);
1565 BufferSize += VolatileRegisters.Idtr.Limit + 1;
1566 BufferSize += sizeof (CPU_MP_DATA);
1567 BufferSize += (sizeof (CPU_AP_DATA) + sizeof (CPU_INFO_IN_HOB))* MaxLogicalProcessorNumber;
1568 MpBuffer = AllocatePages (EFI_SIZE_TO_PAGES (BufferSize));
1569 ASSERT (MpBuffer != NULL);
1570 ZeroMem (MpBuffer, BufferSize);
1571 Buffer = (UINTN) MpBuffer;
1572
1573 //
1574 // The layout of the Buffer is as below:
1575 //
1576 // +--------------------+ <-- Buffer
1577 // AP Stacks (N)
1578 // +--------------------+ <-- MonitorBuffer
1579 // AP Monitor Filters (N)
1580 // +--------------------+ <-- BackupBufferAddr (CpuMpData->BackupBuffer)
1581 // Backup Buffer
1582 // +--------------------+
1583 // Padding
1584 // +--------------------+ <-- ApIdtBase (8-byte boundary)
1585 // AP IDT All APs share one separate IDT. So AP can get address of CPU_MP_DATA from IDT Base.
1586 // +--------------------+ <-- CpuMpData
1587 // CPU_MP_DATA
1588 // +--------------------+ <-- CpuMpData->CpuData
1589 // CPU_AP_DATA (N)
1590 // +--------------------+ <-- CpuMpData->CpuInfoInHob
1591 // CPU_INFO_IN_HOB (N)
1592 // +--------------------+
1593 //
1594 MonitorBuffer = (UINT8 *) (Buffer + ApStackSize * MaxLogicalProcessorNumber);
1595 BackupBufferAddr = (UINTN) MonitorBuffer + MonitorFilterSize * MaxLogicalProcessorNumber;
1596 ApIdtBase = ALIGN_VALUE (BackupBufferAddr + ApResetVectorSize, 8);
1597 CpuMpData = (CPU_MP_DATA *) (ApIdtBase + VolatileRegisters.Idtr.Limit + 1);
1598 CpuMpData->Buffer = Buffer;
1599 CpuMpData->CpuApStackSize = ApStackSize;
1600 CpuMpData->BackupBuffer = BackupBufferAddr;
1601 CpuMpData->BackupBufferSize = ApResetVectorSize;
1602 CpuMpData->WakeupBuffer = (UINTN) -1;
1603 CpuMpData->CpuCount = 1;
1604 CpuMpData->BspNumber = 0;
1605 CpuMpData->WaitEvent = NULL;
1606 CpuMpData->SwitchBspFlag = FALSE;
1607 CpuMpData->CpuData = (CPU_AP_DATA *) (CpuMpData + 1);
1608 CpuMpData->CpuInfoInHob = (UINT64) (UINTN) (CpuMpData->CpuData + MaxLogicalProcessorNumber);
1609 CpuMpData->MicrocodePatchRegionSize = PcdGet64 (PcdCpuMicrocodePatchRegionSize);
1610 //
1611 // If platform has more than one CPU, relocate microcode to memory to reduce
1612 // loading microcode time.
1613 //
1614 MicrocodePatchInRam = NULL;
1615 if (MaxLogicalProcessorNumber > 1) {
1616 MicrocodePatchInRam = AllocatePages (
1617 EFI_SIZE_TO_PAGES (
1618 (UINTN)CpuMpData->MicrocodePatchRegionSize
1619 )
1620 );
1621 }
1622 if (MicrocodePatchInRam == NULL) {
1623 //
1624 // there is only one processor, or no microcode patch is available, or
1625 // memory allocation failed
1626 //
1627 CpuMpData->MicrocodePatchAddress = PcdGet64 (PcdCpuMicrocodePatchAddress);
1628 } else {
1629 //
1630 // there are multiple processors, and a microcode patch is available, and
1631 // memory allocation succeeded
1632 //
1633 CopyMem (
1634 MicrocodePatchInRam,
1635 (VOID *)(UINTN)PcdGet64 (PcdCpuMicrocodePatchAddress),
1636 (UINTN)CpuMpData->MicrocodePatchRegionSize
1637 );
1638 CpuMpData->MicrocodePatchAddress = (UINTN)MicrocodePatchInRam;
1639 }
1640
1641 InitializeSpinLock(&CpuMpData->MpLock);
1642
1643 //
1644 // Make sure no memory usage outside of the allocated buffer.
1645 //
1646 ASSERT ((CpuMpData->CpuInfoInHob + sizeof (CPU_INFO_IN_HOB) * MaxLogicalProcessorNumber) ==
1647 Buffer + BufferSize);
1648
1649 //
1650 // Duplicate BSP's IDT to APs.
1651 // All APs share one separate IDT. So AP can get the address of CpuMpData by using IDTR.BASE + IDTR.LIMIT + 1
1652 //
1653 CopyMem ((VOID *)ApIdtBase, (VOID *)VolatileRegisters.Idtr.Base, VolatileRegisters.Idtr.Limit + 1);
1654 VolatileRegisters.Idtr.Base = ApIdtBase;
1655 //
1656 // Don't pass BSP's TR to APs to avoid AP init failure.
1657 //
1658 VolatileRegisters.Tr = 0;
1659 CopyMem (&CpuMpData->CpuData[0].VolatileRegisters, &VolatileRegisters, sizeof (VolatileRegisters));
1660 //
1661 // Set BSP basic information
1662 //
1663 InitializeApData (CpuMpData, 0, 0, CpuMpData->Buffer + ApStackSize);
1664 //
1665 // Save assembly code information
1666 //
1667 CopyMem (&CpuMpData->AddressMap, &AddressMap, sizeof (MP_ASSEMBLY_ADDRESS_MAP));
1668 //
1669 // Finally set AP loop mode
1670 //
1671 CpuMpData->ApLoopMode = ApLoopMode;
1672 DEBUG ((DEBUG_INFO, "AP Loop Mode is %d\n", CpuMpData->ApLoopMode));
1673
1674 CpuMpData->WakeUpByInitSipiSipi = (CpuMpData->ApLoopMode == ApInHltLoop);
1675
1676 //
1677 // Set up APs wakeup signal buffer
1678 //
1679 for (Index = 0; Index < MaxLogicalProcessorNumber; Index++) {
1680 CpuMpData->CpuData[Index].StartupApSignal =
1681 (UINT32 *)(MonitorBuffer + MonitorFilterSize * Index);
1682 }
1683 //
1684 // Load Microcode on BSP
1685 //
1686 MicrocodeDetect (CpuMpData, TRUE);
1687 //
1688 // Store BSP's MTRR setting
1689 //
1690 MtrrGetAllMtrrs (&CpuMpData->MtrrTable);
1691 //
1692 // Enable the local APIC for Virtual Wire Mode.
1693 //
1694 ProgramVirtualWireMode ();
1695
1696 if (OldCpuMpData == NULL) {
1697 if (MaxLogicalProcessorNumber > 1) {
1698 //
1699 // Wakeup all APs and calculate the processor count in system
1700 //
1701 CollectProcessorCount (CpuMpData);
1702 }
1703 } else {
1704 //
1705 // APs have been wakeup before, just get the CPU Information
1706 // from HOB
1707 //
1708 CpuMpData->CpuCount = OldCpuMpData->CpuCount;
1709 CpuMpData->BspNumber = OldCpuMpData->BspNumber;
1710 CpuMpData->InitFlag = ApInitReconfig;
1711 CpuMpData->CpuInfoInHob = OldCpuMpData->CpuInfoInHob;
1712 CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;
1713 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1714 InitializeSpinLock(&CpuMpData->CpuData[Index].ApLock);
1715 if (CpuInfoInHob[Index].InitialApicId >= 255 || Index > 254) {
1716 CpuMpData->X2ApicEnable = TRUE;
1717 }
1718 CpuMpData->CpuData[Index].CpuHealthy = (CpuInfoInHob[Index].Health == 0)? TRUE:FALSE;
1719 CpuMpData->CpuData[Index].ApFunction = 0;
1720 CopyMem (&CpuMpData->CpuData[Index].VolatileRegisters, &VolatileRegisters, sizeof (CPU_VOLATILE_REGISTERS));
1721 }
1722 if (MaxLogicalProcessorNumber > 1) {
1723 //
1724 // Wakeup APs to do some AP initialize sync
1725 //
1726 WakeUpAP (CpuMpData, TRUE, 0, ApInitializeSync, CpuMpData, TRUE);
1727 //
1728 // Wait for all APs finished initialization
1729 //
1730 while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) {
1731 CpuPause ();
1732 }
1733 CpuMpData->InitFlag = ApInitDone;
1734 for (Index = 0; Index < CpuMpData->CpuCount; Index++) {
1735 SetApState (&CpuMpData->CpuData[Index], CpuStateIdle);
1736 }
1737 }
1738 }
1739
1740 //
1741 // Initialize global data for MP support
1742 //
1743 InitMpGlobalData (CpuMpData);
1744
1745 return EFI_SUCCESS;
1746 }
1747
1748 /**
1749 Gets detailed MP-related information on the requested processor at the
1750 instant this call is made. This service may only be called from the BSP.
1751
1752 @param[in] ProcessorNumber The handle number of processor.
1753 @param[out] ProcessorInfoBuffer A pointer to the buffer where information for
1754 the requested processor is deposited.
1755 @param[out] HealthData Return processor health data.
1756
1757 @retval EFI_SUCCESS Processor information was returned.
1758 @retval EFI_DEVICE_ERROR The calling processor is an AP.
1759 @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL.
1760 @retval EFI_NOT_FOUND The processor with the handle specified by
1761 ProcessorNumber does not exist in the platform.
1762 @retval EFI_NOT_READY MP Initialize Library is not initialized.
1763
1764 **/
1765 EFI_STATUS
1766 EFIAPI
1767 MpInitLibGetProcessorInfo (
1768 IN UINTN ProcessorNumber,
1769 OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer,
1770 OUT EFI_HEALTH_FLAGS *HealthData OPTIONAL
1771 )
1772 {
1773 CPU_MP_DATA *CpuMpData;
1774 UINTN CallerNumber;
1775 CPU_INFO_IN_HOB *CpuInfoInHob;
1776
1777 CpuMpData = GetCpuMpData ();
1778 CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;
1779
1780 //
1781 // Check whether caller processor is BSP
1782 //
1783 MpInitLibWhoAmI (&CallerNumber);
1784 if (CallerNumber != CpuMpData->BspNumber) {
1785 return EFI_DEVICE_ERROR;
1786 }
1787
1788 if (ProcessorInfoBuffer == NULL) {
1789 return EFI_INVALID_PARAMETER;
1790 }
1791
1792 if (ProcessorNumber >= CpuMpData->CpuCount) {
1793 return EFI_NOT_FOUND;
1794 }
1795
1796 ProcessorInfoBuffer->ProcessorId = (UINT64) CpuInfoInHob[ProcessorNumber].ApicId;
1797 ProcessorInfoBuffer->StatusFlag = 0;
1798 if (ProcessorNumber == CpuMpData->BspNumber) {
1799 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_AS_BSP_BIT;
1800 }
1801 if (CpuMpData->CpuData[ProcessorNumber].CpuHealthy) {
1802 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_HEALTH_STATUS_BIT;
1803 }
1804 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateDisabled) {
1805 ProcessorInfoBuffer->StatusFlag &= ~PROCESSOR_ENABLED_BIT;
1806 } else {
1807 ProcessorInfoBuffer->StatusFlag |= PROCESSOR_ENABLED_BIT;
1808 }
1809
1810 //
1811 // Get processor location information
1812 //
1813 GetProcessorLocationByApicId (
1814 CpuInfoInHob[ProcessorNumber].ApicId,
1815 &ProcessorInfoBuffer->Location.Package,
1816 &ProcessorInfoBuffer->Location.Core,
1817 &ProcessorInfoBuffer->Location.Thread
1818 );
1819
1820 if (HealthData != NULL) {
1821 HealthData->Uint32 = CpuInfoInHob[ProcessorNumber].Health;
1822 }
1823
1824 return EFI_SUCCESS;
1825 }
1826
1827 /**
1828 Worker function to switch the requested AP to be the BSP from that point onward.
1829
1830 @param[in] ProcessorNumber The handle number of AP that is to become the new BSP.
1831 @param[in] EnableOldBSP If TRUE, then the old BSP will be listed as an
1832 enabled AP. Otherwise, it will be disabled.
1833
1834 @retval EFI_SUCCESS BSP successfully switched.
1835 @retval others Failed to switch BSP.
1836
1837 **/
1838 EFI_STATUS
1839 SwitchBSPWorker (
1840 IN UINTN ProcessorNumber,
1841 IN BOOLEAN EnableOldBSP
1842 )
1843 {
1844 CPU_MP_DATA *CpuMpData;
1845 UINTN CallerNumber;
1846 CPU_STATE State;
1847 MSR_IA32_APIC_BASE_REGISTER ApicBaseMsr;
1848 BOOLEAN OldInterruptState;
1849 BOOLEAN OldTimerInterruptState;
1850
1851 //
1852 // Save and Disable Local APIC timer interrupt
1853 //
1854 OldTimerInterruptState = GetApicTimerInterruptState ();
1855 DisableApicTimerInterrupt ();
1856 //
1857 // Before send both BSP and AP to a procedure to exchange their roles,
1858 // interrupt must be disabled. This is because during the exchange role
1859 // process, 2 CPU may use 1 stack. If interrupt happens, the stack will
1860 // be corrupted, since interrupt return address will be pushed to stack
1861 // by hardware.
1862 //
1863 OldInterruptState = SaveAndDisableInterrupts ();
1864
1865 //
1866 // Mask LINT0 & LINT1 for the old BSP
1867 //
1868 DisableLvtInterrupts ();
1869
1870 CpuMpData = GetCpuMpData ();
1871
1872 //
1873 // Check whether caller processor is BSP
1874 //
1875 MpInitLibWhoAmI (&CallerNumber);
1876 if (CallerNumber != CpuMpData->BspNumber) {
1877 return EFI_DEVICE_ERROR;
1878 }
1879
1880 if (ProcessorNumber >= CpuMpData->CpuCount) {
1881 return EFI_NOT_FOUND;
1882 }
1883
1884 //
1885 // Check whether specified AP is disabled
1886 //
1887 State = GetApState (&CpuMpData->CpuData[ProcessorNumber]);
1888 if (State == CpuStateDisabled) {
1889 return EFI_INVALID_PARAMETER;
1890 }
1891
1892 //
1893 // Check whether ProcessorNumber specifies the current BSP
1894 //
1895 if (ProcessorNumber == CpuMpData->BspNumber) {
1896 return EFI_INVALID_PARAMETER;
1897 }
1898
1899 //
1900 // Check whether specified AP is busy
1901 //
1902 if (State == CpuStateBusy) {
1903 return EFI_NOT_READY;
1904 }
1905
1906 CpuMpData->BSPInfo.State = CPU_SWITCH_STATE_IDLE;
1907 CpuMpData->APInfo.State = CPU_SWITCH_STATE_IDLE;
1908 CpuMpData->SwitchBspFlag = TRUE;
1909 CpuMpData->NewBspNumber = ProcessorNumber;
1910
1911 //
1912 // Clear the BSP bit of MSR_IA32_APIC_BASE
1913 //
1914 ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
1915 ApicBaseMsr.Bits.BSP = 0;
1916 AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
1917
1918 //
1919 // Need to wakeUp AP (future BSP).
1920 //
1921 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, FutureBSPProc, CpuMpData, TRUE);
1922
1923 AsmExchangeRole (&CpuMpData->BSPInfo, &CpuMpData->APInfo);
1924
1925 //
1926 // Set the BSP bit of MSR_IA32_APIC_BASE on new BSP
1927 //
1928 ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
1929 ApicBaseMsr.Bits.BSP = 1;
1930 AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
1931 ProgramVirtualWireMode ();
1932
1933 //
1934 // Wait for old BSP finished AP task
1935 //
1936 while (GetApState (&CpuMpData->CpuData[CallerNumber]) != CpuStateFinished) {
1937 CpuPause ();
1938 }
1939
1940 CpuMpData->SwitchBspFlag = FALSE;
1941 //
1942 // Set old BSP enable state
1943 //
1944 if (!EnableOldBSP) {
1945 SetApState (&CpuMpData->CpuData[CallerNumber], CpuStateDisabled);
1946 } else {
1947 SetApState (&CpuMpData->CpuData[CallerNumber], CpuStateIdle);
1948 }
1949 //
1950 // Save new BSP number
1951 //
1952 CpuMpData->BspNumber = (UINT32) ProcessorNumber;
1953
1954 //
1955 // Restore interrupt state.
1956 //
1957 SetInterruptState (OldInterruptState);
1958
1959 if (OldTimerInterruptState) {
1960 EnableApicTimerInterrupt ();
1961 }
1962
1963 return EFI_SUCCESS;
1964 }
1965
1966 /**
1967 Worker function to let the caller enable or disable an AP from this point onward.
1968 This service may only be called from the BSP.
1969
1970 @param[in] ProcessorNumber The handle number of AP.
1971 @param[in] EnableAP Specifies the new state for the processor for
1972 enabled, FALSE for disabled.
1973 @param[in] HealthFlag If not NULL, a pointer to a value that specifies
1974 the new health status of the AP.
1975
1976 @retval EFI_SUCCESS The specified AP was enabled or disabled successfully.
1977 @retval others Failed to Enable/Disable AP.
1978
1979 **/
1980 EFI_STATUS
1981 EnableDisableApWorker (
1982 IN UINTN ProcessorNumber,
1983 IN BOOLEAN EnableAP,
1984 IN UINT32 *HealthFlag OPTIONAL
1985 )
1986 {
1987 CPU_MP_DATA *CpuMpData;
1988 UINTN CallerNumber;
1989
1990 CpuMpData = GetCpuMpData ();
1991
1992 //
1993 // Check whether caller processor is BSP
1994 //
1995 MpInitLibWhoAmI (&CallerNumber);
1996 if (CallerNumber != CpuMpData->BspNumber) {
1997 return EFI_DEVICE_ERROR;
1998 }
1999
2000 if (ProcessorNumber == CpuMpData->BspNumber) {
2001 return EFI_INVALID_PARAMETER;
2002 }
2003
2004 if (ProcessorNumber >= CpuMpData->CpuCount) {
2005 return EFI_NOT_FOUND;
2006 }
2007
2008 if (!EnableAP) {
2009 SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateDisabled);
2010 } else {
2011 ResetProcessorToIdleState (ProcessorNumber);
2012 }
2013
2014 if (HealthFlag != NULL) {
2015 CpuMpData->CpuData[ProcessorNumber].CpuHealthy =
2016 (BOOLEAN) ((*HealthFlag & PROCESSOR_HEALTH_STATUS_BIT) != 0);
2017 }
2018
2019 return EFI_SUCCESS;
2020 }
2021
2022 /**
2023 This return the handle number for the calling processor. This service may be
2024 called from the BSP and APs.
2025
2026 @param[out] ProcessorNumber Pointer to the handle number of AP.
2027 The range is from 0 to the total number of
2028 logical processors minus 1. The total number of
2029 logical processors can be retrieved by
2030 MpInitLibGetNumberOfProcessors().
2031
2032 @retval EFI_SUCCESS The current processor handle number was returned
2033 in ProcessorNumber.
2034 @retval EFI_INVALID_PARAMETER ProcessorNumber is NULL.
2035 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2036
2037 **/
2038 EFI_STATUS
2039 EFIAPI
2040 MpInitLibWhoAmI (
2041 OUT UINTN *ProcessorNumber
2042 )
2043 {
2044 CPU_MP_DATA *CpuMpData;
2045
2046 if (ProcessorNumber == NULL) {
2047 return EFI_INVALID_PARAMETER;
2048 }
2049
2050 CpuMpData = GetCpuMpData ();
2051
2052 return GetProcessorNumber (CpuMpData, ProcessorNumber);
2053 }
2054
2055 /**
2056 Retrieves the number of logical processor in the platform and the number of
2057 those logical processors that are enabled on this boot. This service may only
2058 be called from the BSP.
2059
2060 @param[out] NumberOfProcessors Pointer to the total number of logical
2061 processors in the system, including the BSP
2062 and disabled APs.
2063 @param[out] NumberOfEnabledProcessors Pointer to the number of enabled logical
2064 processors that exist in system, including
2065 the BSP.
2066
2067 @retval EFI_SUCCESS The number of logical processors and enabled
2068 logical processors was retrieved.
2069 @retval EFI_DEVICE_ERROR The calling processor is an AP.
2070 @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL and NumberOfEnabledProcessors
2071 is NULL.
2072 @retval EFI_NOT_READY MP Initialize Library is not initialized.
2073
2074 **/
2075 EFI_STATUS
2076 EFIAPI
2077 MpInitLibGetNumberOfProcessors (
2078 OUT UINTN *NumberOfProcessors, OPTIONAL
2079 OUT UINTN *NumberOfEnabledProcessors OPTIONAL
2080 )
2081 {
2082 CPU_MP_DATA *CpuMpData;
2083 UINTN CallerNumber;
2084 UINTN ProcessorNumber;
2085 UINTN EnabledProcessorNumber;
2086 UINTN Index;
2087
2088 CpuMpData = GetCpuMpData ();
2089
2090 if ((NumberOfProcessors == NULL) && (NumberOfEnabledProcessors == NULL)) {
2091 return EFI_INVALID_PARAMETER;
2092 }
2093
2094 //
2095 // Check whether caller processor is BSP
2096 //
2097 MpInitLibWhoAmI (&CallerNumber);
2098 if (CallerNumber != CpuMpData->BspNumber) {
2099 return EFI_DEVICE_ERROR;
2100 }
2101
2102 ProcessorNumber = CpuMpData->CpuCount;
2103 EnabledProcessorNumber = 0;
2104 for (Index = 0; Index < ProcessorNumber; Index++) {
2105 if (GetApState (&CpuMpData->CpuData[Index]) != CpuStateDisabled) {
2106 EnabledProcessorNumber ++;
2107 }
2108 }
2109
2110 if (NumberOfProcessors != NULL) {
2111 *NumberOfProcessors = ProcessorNumber;
2112 }
2113 if (NumberOfEnabledProcessors != NULL) {
2114 *NumberOfEnabledProcessors = EnabledProcessorNumber;
2115 }
2116
2117 return EFI_SUCCESS;
2118 }
2119
2120
2121 /**
2122 Worker function to execute a caller provided function on all enabled APs.
2123
2124 @param[in] Procedure A pointer to the function to be run on
2125 enabled APs of the system.
2126 @param[in] SingleThread If TRUE, then all the enabled APs execute
2127 the function specified by Procedure one by
2128 one, in ascending order of processor handle
2129 number. If FALSE, then all the enabled APs
2130 execute the function specified by Procedure
2131 simultaneously.
2132 @param[in] WaitEvent The event created by the caller with CreateEvent()
2133 service.
2134 @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
2135 APs to return from Procedure, either for
2136 blocking or non-blocking mode.
2137 @param[in] ProcedureArgument The parameter passed into Procedure for
2138 all APs.
2139 @param[out] FailedCpuList If all APs finish successfully, then its
2140 content is set to NULL. If not all APs
2141 finish before timeout expires, then its
2142 content is set to address of the buffer
2143 holding handle numbers of the failed APs.
2144
2145 @retval EFI_SUCCESS In blocking mode, all APs have finished before
2146 the timeout expired.
2147 @retval EFI_SUCCESS In non-blocking mode, function has been dispatched
2148 to all enabled APs.
2149 @retval others Failed to Startup all APs.
2150
2151 **/
2152 EFI_STATUS
2153 StartupAllAPsWorker (
2154 IN EFI_AP_PROCEDURE Procedure,
2155 IN BOOLEAN SingleThread,
2156 IN EFI_EVENT WaitEvent OPTIONAL,
2157 IN UINTN TimeoutInMicroseconds,
2158 IN VOID *ProcedureArgument OPTIONAL,
2159 OUT UINTN **FailedCpuList OPTIONAL
2160 )
2161 {
2162 EFI_STATUS Status;
2163 CPU_MP_DATA *CpuMpData;
2164 UINTN ProcessorCount;
2165 UINTN ProcessorNumber;
2166 UINTN CallerNumber;
2167 CPU_AP_DATA *CpuData;
2168 BOOLEAN HasEnabledAp;
2169 CPU_STATE ApState;
2170
2171 CpuMpData = GetCpuMpData ();
2172
2173 if (FailedCpuList != NULL) {
2174 *FailedCpuList = NULL;
2175 }
2176
2177 if (CpuMpData->CpuCount == 1) {
2178 return EFI_NOT_STARTED;
2179 }
2180
2181 if (Procedure == NULL) {
2182 return EFI_INVALID_PARAMETER;
2183 }
2184
2185 //
2186 // Check whether caller processor is BSP
2187 //
2188 MpInitLibWhoAmI (&CallerNumber);
2189 if (CallerNumber != CpuMpData->BspNumber) {
2190 return EFI_DEVICE_ERROR;
2191 }
2192
2193 //
2194 // Update AP state
2195 //
2196 CheckAndUpdateApsStatus ();
2197
2198 ProcessorCount = CpuMpData->CpuCount;
2199 HasEnabledAp = FALSE;
2200 //
2201 // Check whether all enabled APs are idle.
2202 // If any enabled AP is not idle, return EFI_NOT_READY.
2203 //
2204 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2205 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2206 if (ProcessorNumber != CpuMpData->BspNumber) {
2207 ApState = GetApState (CpuData);
2208 if (ApState != CpuStateDisabled) {
2209 HasEnabledAp = TRUE;
2210 if (ApState != CpuStateIdle) {
2211 //
2212 // If any enabled APs are busy, return EFI_NOT_READY.
2213 //
2214 return EFI_NOT_READY;
2215 }
2216 }
2217 }
2218 }
2219
2220 if (!HasEnabledAp) {
2221 //
2222 // If no enabled AP exists, return EFI_NOT_STARTED.
2223 //
2224 return EFI_NOT_STARTED;
2225 }
2226
2227 CpuMpData->RunningCount = 0;
2228 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2229 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2230 CpuData->Waiting = FALSE;
2231 if (ProcessorNumber != CpuMpData->BspNumber) {
2232 if (CpuData->State == CpuStateIdle) {
2233 //
2234 // Mark this processor as responsible for current calling.
2235 //
2236 CpuData->Waiting = TRUE;
2237 CpuMpData->RunningCount++;
2238 }
2239 }
2240 }
2241
2242 CpuMpData->Procedure = Procedure;
2243 CpuMpData->ProcArguments = ProcedureArgument;
2244 CpuMpData->SingleThread = SingleThread;
2245 CpuMpData->FinishedCount = 0;
2246 CpuMpData->FailedCpuList = FailedCpuList;
2247 CpuMpData->ExpectedTime = CalculateTimeout (
2248 TimeoutInMicroseconds,
2249 &CpuMpData->CurrentTime
2250 );
2251 CpuMpData->TotalTime = 0;
2252 CpuMpData->WaitEvent = WaitEvent;
2253
2254 if (!SingleThread) {
2255 WakeUpAP (CpuMpData, TRUE, 0, Procedure, ProcedureArgument, FALSE);
2256 } else {
2257 for (ProcessorNumber = 0; ProcessorNumber < ProcessorCount; ProcessorNumber++) {
2258 if (ProcessorNumber == CallerNumber) {
2259 continue;
2260 }
2261 if (CpuMpData->CpuData[ProcessorNumber].Waiting) {
2262 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, Procedure, ProcedureArgument, TRUE);
2263 break;
2264 }
2265 }
2266 }
2267
2268 Status = EFI_SUCCESS;
2269 if (WaitEvent == NULL) {
2270 do {
2271 Status = CheckAllAPs ();
2272 } while (Status == EFI_NOT_READY);
2273 }
2274
2275 return Status;
2276 }
2277
2278 /**
2279 Worker function to let the caller get one enabled AP to execute a caller-provided
2280 function.
2281
2282 @param[in] Procedure A pointer to the function to be run on
2283 enabled APs of the system.
2284 @param[in] ProcessorNumber The handle number of the AP.
2285 @param[in] WaitEvent The event created by the caller with CreateEvent()
2286 service.
2287 @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for
2288 APs to return from Procedure, either for
2289 blocking or non-blocking mode.
2290 @param[in] ProcedureArgument The parameter passed into Procedure for
2291 all APs.
2292 @param[out] Finished If AP returns from Procedure before the
2293 timeout expires, its content is set to TRUE.
2294 Otherwise, the value is set to FALSE.
2295
2296 @retval EFI_SUCCESS In blocking mode, specified AP finished before
2297 the timeout expires.
2298 @retval others Failed to Startup AP.
2299
2300 **/
2301 EFI_STATUS
2302 StartupThisAPWorker (
2303 IN EFI_AP_PROCEDURE Procedure,
2304 IN UINTN ProcessorNumber,
2305 IN EFI_EVENT WaitEvent OPTIONAL,
2306 IN UINTN TimeoutInMicroseconds,
2307 IN VOID *ProcedureArgument OPTIONAL,
2308 OUT BOOLEAN *Finished OPTIONAL
2309 )
2310 {
2311 EFI_STATUS Status;
2312 CPU_MP_DATA *CpuMpData;
2313 CPU_AP_DATA *CpuData;
2314 UINTN CallerNumber;
2315
2316 CpuMpData = GetCpuMpData ();
2317
2318 if (Finished != NULL) {
2319 *Finished = FALSE;
2320 }
2321
2322 //
2323 // Check whether caller processor is BSP
2324 //
2325 MpInitLibWhoAmI (&CallerNumber);
2326 if (CallerNumber != CpuMpData->BspNumber) {
2327 return EFI_DEVICE_ERROR;
2328 }
2329
2330 //
2331 // Check whether processor with the handle specified by ProcessorNumber exists
2332 //
2333 if (ProcessorNumber >= CpuMpData->CpuCount) {
2334 return EFI_NOT_FOUND;
2335 }
2336
2337 //
2338 // Check whether specified processor is BSP
2339 //
2340 if (ProcessorNumber == CpuMpData->BspNumber) {
2341 return EFI_INVALID_PARAMETER;
2342 }
2343
2344 //
2345 // Check parameter Procedure
2346 //
2347 if (Procedure == NULL) {
2348 return EFI_INVALID_PARAMETER;
2349 }
2350
2351 //
2352 // Update AP state
2353 //
2354 CheckAndUpdateApsStatus ();
2355
2356 //
2357 // Check whether specified AP is disabled
2358 //
2359 if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateDisabled) {
2360 return EFI_INVALID_PARAMETER;
2361 }
2362
2363 //
2364 // If WaitEvent is not NULL, execute in non-blocking mode.
2365 // BSP saves data for CheckAPsStatus(), and returns EFI_SUCCESS.
2366 // CheckAPsStatus() will check completion and timeout periodically.
2367 //
2368 CpuData = &CpuMpData->CpuData[ProcessorNumber];
2369 CpuData->WaitEvent = WaitEvent;
2370 CpuData->Finished = Finished;
2371 CpuData->ExpectedTime = CalculateTimeout (TimeoutInMicroseconds, &CpuData->CurrentTime);
2372 CpuData->TotalTime = 0;
2373
2374 WakeUpAP (CpuMpData, FALSE, ProcessorNumber, Procedure, ProcedureArgument, TRUE);
2375
2376 //
2377 // If WaitEvent is NULL, execute in blocking mode.
2378 // BSP checks AP's state until it finishes or TimeoutInMicrosecsond expires.
2379 //
2380 Status = EFI_SUCCESS;
2381 if (WaitEvent == NULL) {
2382 do {
2383 Status = CheckThisAP (ProcessorNumber);
2384 } while (Status == EFI_NOT_READY);
2385 }
2386
2387 return Status;
2388 }
2389
2390 /**
2391 Get pointer to CPU MP Data structure from GUIDed HOB.
2392
2393 @return The pointer to CPU MP Data structure.
2394 **/
2395 CPU_MP_DATA *
2396 GetCpuMpDataFromGuidedHob (
2397 VOID
2398 )
2399 {
2400 EFI_HOB_GUID_TYPE *GuidHob;
2401 VOID *DataInHob;
2402 CPU_MP_DATA *CpuMpData;
2403
2404 CpuMpData = NULL;
2405 GuidHob = GetFirstGuidHob (&mCpuInitMpLibHobGuid);
2406 if (GuidHob != NULL) {
2407 DataInHob = GET_GUID_HOB_DATA (GuidHob);
2408 CpuMpData = (CPU_MP_DATA *) (*(UINTN *) DataInHob);
2409 }
2410 return CpuMpData;
2411 }
2412