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