]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/CpuHotplugSmm/CpuHotplug.c
NetworkPkg: Apply uncrustify changes
[mirror_edk2.git] / OvmfPkg / CpuHotplugSmm / CpuHotplug.c
1 /** @file
2 Root SMI handler for VCPU hotplug SMIs.
3
4 Copyright (c) 2020, Red Hat, Inc.
5
6 SPDX-License-Identifier: BSD-2-Clause-Patent
7 **/
8
9 #include <CpuHotPlugData.h> // CPU_HOT_PLUG_DATA
10 #include <IndustryStandard/Q35MchIch9.h> // ICH9_APM_CNT
11 #include <IndustryStandard/QemuCpuHotplug.h> // QEMU_CPUHP_CMD_GET_PENDING
12 #include <Library/BaseLib.h> // CpuDeadLoop()
13 #include <Library/CpuLib.h> // CpuSleep()
14 #include <Library/DebugLib.h> // ASSERT()
15 #include <Library/MmServicesTableLib.h> // gMmst
16 #include <Library/PcdLib.h> // PcdGetBool()
17 #include <Library/SafeIntLib.h> // SafeUintnSub()
18 #include <Pcd/CpuHotEjectData.h> // CPU_HOT_EJECT_DATA
19 #include <Protocol/MmCpuIo.h> // EFI_MM_CPU_IO_PROTOCOL
20 #include <Protocol/SmmCpuService.h> // EFI_SMM_CPU_SERVICE_PROTOCOL
21 #include <Register/Intel/ArchitecturalMsr.h> // MSR_IA32_APIC_BASE_REGISTER
22 #include <Uefi/UefiBaseType.h> // EFI_STATUS
23
24 #include "ApicId.h" // APIC_ID
25 #include "QemuCpuhp.h" // QemuCpuhpWriteCpuSelector()
26 #include "Smbase.h" // SmbaseAllocatePostSmmPen()
27
28 //
29 // We use this protocol for accessing IO Ports.
30 //
31 STATIC EFI_MM_CPU_IO_PROTOCOL *mMmCpuIo;
32 //
33 // The following protocol is used to report the addition or removal of a CPU to
34 // the SMM CPU driver (PiSmmCpuDxeSmm).
35 //
36 STATIC EFI_SMM_CPU_SERVICE_PROTOCOL *mMmCpuService;
37 //
38 // These structures serve as communication side-channels between the
39 // EFI_SMM_CPU_SERVICE_PROTOCOL consumer (i.e., this driver) and provider
40 // (i.e., PiSmmCpuDxeSmm).
41 //
42 STATIC CPU_HOT_PLUG_DATA *mCpuHotPlugData;
43 STATIC CPU_HOT_EJECT_DATA *mCpuHotEjectData;
44 //
45 // SMRAM arrays for fetching the APIC IDs of processors with pending events (of
46 // known event types), for the time of just one MMI.
47 //
48 // The lifetimes of these arrays match that of this driver only because we
49 // don't want to allocate SMRAM at OS runtime, and potentially fail (or
50 // fragment the SMRAM map).
51 //
52 // The first array stores APIC IDs for hot-plug events, the second and the
53 // third store APIC IDs and QEMU CPU Selectors (both indexed similarly) for
54 // hot-unplug events. All of these provide room for "possible CPU count" minus
55 // one elements as we don't expect every possible CPU to appear, or disappear,
56 // in a single MMI. The numbers of used (populated) elements in the arrays are
57 // determined on every MMI separately.
58 //
59 STATIC APIC_ID *mPluggedApicIds;
60 STATIC APIC_ID *mToUnplugApicIds;
61 STATIC UINT32 *mToUnplugSelectors;
62 //
63 // Address of the non-SMRAM reserved memory page that contains the Post-SMM Pen
64 // for hot-added CPUs.
65 //
66 STATIC UINT32 mPostSmmPenAddress;
67 //
68 // Represents the registration of the CPU Hotplug MMI handler.
69 //
70 STATIC EFI_HANDLE mDispatchHandle;
71
72 /**
73 Process CPUs that have been hot-added, per QemuCpuhpCollectApicIds().
74
75 For each such CPU, relocate the SMBASE, and report the CPU to PiSmmCpuDxeSmm
76 via EFI_SMM_CPU_SERVICE_PROTOCOL. If the supposedly hot-added CPU is already
77 known, skip it silently.
78
79 @param[in] PluggedApicIds The APIC IDs of the CPUs that have been
80 hot-plugged.
81
82 @param[in] PluggedCount The number of filled-in APIC IDs in
83 PluggedApicIds.
84
85 @retval EFI_SUCCESS CPUs corresponding to all the APIC IDs are
86 populated.
87
88 @retval EFI_OUT_OF_RESOURCES Out of APIC ID space in "mCpuHotPlugData".
89
90 @return Error codes propagated from SmbaseRelocate()
91 and mMmCpuService->AddProcessor().
92 **/
93 STATIC
94 EFI_STATUS
95 ProcessHotAddedCpus (
96 IN APIC_ID *PluggedApicIds,
97 IN UINT32 PluggedCount
98 )
99 {
100 EFI_STATUS Status;
101 UINT32 PluggedIdx;
102 UINT32 NewSlot;
103
104 //
105 // The Post-SMM Pen need not be reinstalled multiple times within a single
106 // root MMI handling. Even reinstalling once per root MMI is only prudence;
107 // in theory installing the pen in the driver's entry point function should
108 // suffice.
109 //
110 SmbaseReinstallPostSmmPen (mPostSmmPenAddress);
111
112 PluggedIdx = 0;
113 NewSlot = 0;
114 while (PluggedIdx < PluggedCount) {
115 APIC_ID NewApicId;
116 UINT32 CheckSlot;
117 UINTN NewProcessorNumberByProtocol;
118
119 NewApicId = PluggedApicIds[PluggedIdx];
120
121 //
122 // Check if the supposedly hot-added CPU is already known to us.
123 //
124 for (CheckSlot = 0;
125 CheckSlot < mCpuHotPlugData->ArrayLength;
126 CheckSlot++) {
127 if (mCpuHotPlugData->ApicId[CheckSlot] == NewApicId) {
128 break;
129 }
130 }
131 if (CheckSlot < mCpuHotPlugData->ArrayLength) {
132 DEBUG ((DEBUG_VERBOSE, "%a: APIC ID " FMT_APIC_ID " was hot-plugged "
133 "before; ignoring it\n", __FUNCTION__, NewApicId));
134 PluggedIdx++;
135 continue;
136 }
137
138 //
139 // Find the first empty slot in CPU_HOT_PLUG_DATA.
140 //
141 while (NewSlot < mCpuHotPlugData->ArrayLength &&
142 mCpuHotPlugData->ApicId[NewSlot] != MAX_UINT64) {
143 NewSlot++;
144 }
145 if (NewSlot == mCpuHotPlugData->ArrayLength) {
146 DEBUG ((DEBUG_ERROR, "%a: no room for APIC ID " FMT_APIC_ID "\n",
147 __FUNCTION__, NewApicId));
148 return EFI_OUT_OF_RESOURCES;
149 }
150
151 //
152 // Store the APIC ID of the new processor to the slot.
153 //
154 mCpuHotPlugData->ApicId[NewSlot] = NewApicId;
155
156 //
157 // Relocate the SMBASE of the new CPU.
158 //
159 Status = SmbaseRelocate (NewApicId, mCpuHotPlugData->SmBase[NewSlot],
160 mPostSmmPenAddress);
161 if (EFI_ERROR (Status)) {
162 goto RevokeNewSlot;
163 }
164
165 //
166 // Add the new CPU with EFI_SMM_CPU_SERVICE_PROTOCOL.
167 //
168 Status = mMmCpuService->AddProcessor (mMmCpuService, NewApicId,
169 &NewProcessorNumberByProtocol);
170 if (EFI_ERROR (Status)) {
171 DEBUG ((DEBUG_ERROR, "%a: AddProcessor(" FMT_APIC_ID "): %r\n",
172 __FUNCTION__, NewApicId, Status));
173 goto RevokeNewSlot;
174 }
175
176 DEBUG ((DEBUG_INFO, "%a: hot-added APIC ID " FMT_APIC_ID ", SMBASE 0x%Lx, "
177 "EFI_SMM_CPU_SERVICE_PROTOCOL assigned number %Lu\n", __FUNCTION__,
178 NewApicId, (UINT64)mCpuHotPlugData->SmBase[NewSlot],
179 (UINT64)NewProcessorNumberByProtocol));
180
181 NewSlot++;
182 PluggedIdx++;
183 }
184
185 //
186 // We've processed this batch of hot-added CPUs.
187 //
188 return EFI_SUCCESS;
189
190 RevokeNewSlot:
191 mCpuHotPlugData->ApicId[NewSlot] = MAX_UINT64;
192
193 return Status;
194 }
195
196 /**
197 EjectCpu needs to know the BSP at SMI exit at a point when
198 some of the EFI_SMM_CPU_SERVICE_PROTOCOL state has been torn
199 down.
200 Reuse the logic from OvmfPkg::PlatformSmmBspElection() to
201 do that.
202
203 @retval TRUE If the CPU executing this function is the BSP.
204
205 @retval FALSE If the CPU executing this function is an AP.
206 **/
207 STATIC
208 BOOLEAN
209 CheckIfBsp (
210 VOID
211 )
212 {
213 MSR_IA32_APIC_BASE_REGISTER ApicBaseMsr;
214 BOOLEAN IsBsp;
215
216 ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
217 IsBsp = (BOOLEAN)(ApicBaseMsr.Bits.BSP == 1);
218 return IsBsp;
219 }
220
221 /**
222 CPU Hot-eject handler, called from SmmCpuFeaturesRendezvousExit()
223 on each CPU at exit from SMM.
224
225 If, the executing CPU is neither the BSP, nor being ejected, nothing
226 to be done.
227 If, the executing CPU is being ejected, wait in a halted loop
228 until ejected.
229 If, the executing CPU is the BSP, set QEMU CPU status to eject
230 for CPUs being ejected.
231
232 @param[in] ProcessorNum ProcessorNum denotes the CPU exiting SMM,
233 and will be used as an index into
234 CPU_HOT_EJECT_DATA->QemuSelectorMap. It is
235 identical to the processor handle number in
236 EFI_SMM_CPU_SERVICE_PROTOCOL.
237 **/
238 VOID
239 EFIAPI
240 EjectCpu (
241 IN UINTN ProcessorNum
242 )
243 {
244 UINT64 QemuSelector;
245
246 if (CheckIfBsp ()) {
247 UINT32 Idx;
248
249 for (Idx = 0; Idx < mCpuHotEjectData->ArrayLength; Idx++) {
250 QemuSelector = mCpuHotEjectData->QemuSelectorMap[Idx];
251
252 if (QemuSelector != CPU_EJECT_QEMU_SELECTOR_INVALID) {
253 //
254 // This to-be-ejected-CPU has already received the BSP's SMI exit
255 // signal and will execute SmmCpuFeaturesRendezvousExit()
256 // followed by this callback or is already penned in the
257 // CpuSleep() loop below.
258 //
259 // Tell QEMU to context-switch it out.
260 //
261 QemuCpuhpWriteCpuSelector (mMmCpuIo, (UINT32) QemuSelector);
262 QemuCpuhpWriteCpuStatus (mMmCpuIo, QEMU_CPUHP_STAT_EJECT);
263
264 //
265 // Now that we've ejected the CPU corresponding to QemuSelectorMap[Idx],
266 // clear its eject status to ensure that an invalid future SMI does
267 // not end up trying a spurious eject or a newly hotplugged CPU does
268 // not get penned in the CpuSleep() loop.
269 //
270 // Note that the QemuCpuhpWriteCpuStatus() command above is a write to
271 // a different address space and uses the EFI_MM_CPU_IO_PROTOCOL.
272 //
273 // This means that we are guaranteed that the following assignment
274 // will not be reordered before the eject. And, so we can safely
275 // do this write here.
276 //
277 mCpuHotEjectData->QemuSelectorMap[Idx] =
278 CPU_EJECT_QEMU_SELECTOR_INVALID;
279
280 DEBUG ((DEBUG_INFO, "%a: Unplugged ProcessorNum %u, "
281 "QemuSelector %Lu\n", __FUNCTION__, Idx, QemuSelector));
282 }
283 }
284
285 //
286 // We are done until the next hot-unplug; clear the handler.
287 //
288 // mCpuHotEjectData->Handler is a NOP for any CPU not under ejection.
289 // So, once we are done with all the ejections, we can safely reset it
290 // here since any CPU dereferencing it would only see either the old
291 // or the new value (since it is aligned at a natural boundary.)
292 //
293 mCpuHotEjectData->Handler = NULL;
294 return;
295 }
296
297 //
298 // Reached only on APs
299 //
300
301 //
302 // mCpuHotEjectData->QemuSelectorMap[ProcessorNum] is updated
303 // on the BSP in the ongoing SMI at two places:
304 //
305 // - UnplugCpus() where the BSP determines if a CPU is under ejection
306 // or not. As a comment in UnplugCpus() at set-up, and in
307 // SmmCpuFeaturesRendezvousExit() where it is dereferenced describe,
308 // any such updates are guaranteed to be ordered-before the
309 // dereference below.
310 //
311 // - EjectCpu() on the BSP (above) updates QemuSelectorMap[ProcessorNum]
312 // for a CPU once it's ejected.
313 //
314 // The CPU under ejection: might be executing anywhere between the
315 // AllCpusInSync loop in SmiRendezvous(), to about to dereference
316 // QemuSelectorMap[ProcessorNum].
317 // As described in the comment above where we do the reset, this
318 // is not a problem since the ejected CPU never sees the after value.
319 // CPUs not-under ejection: never see any changes so they are fine.
320 //
321 QemuSelector = mCpuHotEjectData->QemuSelectorMap[ProcessorNum];
322 if (QemuSelector == CPU_EJECT_QEMU_SELECTOR_INVALID) {
323 return;
324 }
325
326 //
327 // APs being unplugged get here from SmmCpuFeaturesRendezvousExit()
328 // after having been cleared to exit the SMI and so have no SMM
329 // processing remaining.
330 //
331 // Keep them penned here until the BSP tells QEMU to eject them.
332 //
333 for (;;) {
334 DisableInterrupts ();
335 CpuSleep ();
336 }
337 }
338
339 /**
340 Process to be hot-unplugged CPUs, per QemuCpuhpCollectApicIds().
341
342 For each such CPU, report the CPU to PiSmmCpuDxeSmm via
343 EFI_SMM_CPU_SERVICE_PROTOCOL and stash the QEMU Cpu Selectors for later
344 ejection. If the to be hot-unplugged CPU is unknown, skip it silently.
345
346 Additonally, if we do stash any Cpu Selectors, also install a CPU eject
347 handler which would handle the ejection.
348
349 @param[in] ToUnplugApicIds The APIC IDs of the CPUs that are about to be
350 hot-unplugged.
351
352 @param[in] ToUnplugSelectors The QEMU Selectors of the CPUs that are about to
353 be hot-unplugged.
354
355 @param[in] ToUnplugCount The number of filled-in APIC IDs in
356 ToUnplugApicIds.
357
358 @retval EFI_ALREADY_STARTED For the ProcessorNum that
359 EFI_SMM_CPU_SERVICE_PROTOCOL had assigned to
360 one of the APIC IDs in ToUnplugApicIds,
361 mCpuHotEjectData->QemuSelectorMap already has
362 the QemuSelector value stashed. (This should
363 never happen.)
364
365 @retval EFI_SUCCESS Known APIC IDs have been removed from SMM data
366 structures.
367
368 @return Error codes propagated from
369 mMmCpuService->RemoveProcessor().
370 **/
371 STATIC
372 EFI_STATUS
373 UnplugCpus (
374 IN APIC_ID *ToUnplugApicIds,
375 IN UINT32 *ToUnplugSelectors,
376 IN UINT32 ToUnplugCount
377 )
378 {
379 EFI_STATUS Status;
380 UINT32 ToUnplugIdx;
381 UINT32 EjectCount;
382 UINTN ProcessorNum;
383
384 ToUnplugIdx = 0;
385 EjectCount = 0;
386 while (ToUnplugIdx < ToUnplugCount) {
387 APIC_ID RemoveApicId;
388 UINT32 QemuSelector;
389
390 RemoveApicId = ToUnplugApicIds[ToUnplugIdx];
391 QemuSelector = ToUnplugSelectors[ToUnplugIdx];
392
393 //
394 // mCpuHotPlugData->ApicId maps ProcessorNum -> ApicId. Use RemoveApicId
395 // to find the corresponding ProcessorNum for the CPU to be removed.
396 //
397 // With this we can establish a 3 way mapping:
398 // APIC_ID -- ProcessorNum -- QemuSelector
399 //
400 // We stash the ProcessorNum -> QemuSelector mapping so it can later be
401 // used for CPU hot-eject in SmmCpuFeaturesRendezvousExit() context (where
402 // we only have ProcessorNum available.)
403 //
404
405 for (ProcessorNum = 0;
406 ProcessorNum < mCpuHotPlugData->ArrayLength;
407 ProcessorNum++) {
408 if (mCpuHotPlugData->ApicId[ProcessorNum] == RemoveApicId) {
409 break;
410 }
411 }
412
413 //
414 // Ignore the unplug if APIC ID not found
415 //
416 if (ProcessorNum == mCpuHotPlugData->ArrayLength) {
417 DEBUG ((DEBUG_VERBOSE, "%a: did not find APIC ID " FMT_APIC_ID
418 " to unplug\n", __FUNCTION__, RemoveApicId));
419 ToUnplugIdx++;
420 continue;
421 }
422
423 //
424 // Mark ProcessorNum for removal from SMM data structures
425 //
426 Status = mMmCpuService->RemoveProcessor (mMmCpuService, ProcessorNum);
427 if (EFI_ERROR (Status)) {
428 DEBUG ((DEBUG_ERROR, "%a: RemoveProcessor(" FMT_APIC_ID "): %r\n",
429 __FUNCTION__, RemoveApicId, Status));
430 return Status;
431 }
432
433 if (mCpuHotEjectData->QemuSelectorMap[ProcessorNum] !=
434 CPU_EJECT_QEMU_SELECTOR_INVALID) {
435 //
436 // mCpuHotEjectData->QemuSelectorMap[ProcessorNum] is set to
437 // CPU_EJECT_QEMU_SELECTOR_INVALID when mCpuHotEjectData->QemuSelectorMap
438 // is allocated, and once the subject processsor is ejected.
439 //
440 // Additionally, mMmCpuService->RemoveProcessor(ProcessorNum) invalidates
441 // mCpuHotPlugData->ApicId[ProcessorNum], so a given ProcessorNum can
442 // never match more than one APIC ID -- nor, by transitivity, designate
443 // more than one QemuSelector -- in a single invocation of UnplugCpus().
444 //
445 DEBUG ((DEBUG_ERROR, "%a: ProcessorNum %Lu maps to QemuSelector %Lu, "
446 "cannot also map to %u\n", __FUNCTION__, (UINT64)ProcessorNum,
447 mCpuHotEjectData->QemuSelectorMap[ProcessorNum], QemuSelector));
448
449 return EFI_ALREADY_STARTED;
450 }
451
452 //
453 // Stash the QemuSelector so we can do the actual ejection later.
454 //
455 mCpuHotEjectData->QemuSelectorMap[ProcessorNum] = (UINT64)QemuSelector;
456
457 DEBUG ((DEBUG_INFO, "%a: Started hot-unplug on ProcessorNum %Lu, APIC ID "
458 FMT_APIC_ID ", QemuSelector %u\n", __FUNCTION__, (UINT64)ProcessorNum,
459 RemoveApicId, QemuSelector));
460
461 EjectCount++;
462 ToUnplugIdx++;
463 }
464
465 if (EjectCount != 0) {
466 //
467 // We have processors to be ejected; install the handler.
468 //
469 mCpuHotEjectData->Handler = EjectCpu;
470
471 //
472 // The BSP and APs load mCpuHotEjectData->Handler, and
473 // mCpuHotEjectData->QemuSelectorMap[] in SmmCpuFeaturesRendezvousExit()
474 // and EjectCpu().
475 //
476 // The comment in SmmCpuFeaturesRendezvousExit() details how we use
477 // the AllCpusInSync control-dependency to ensure that any loads are
478 // ordered-after the stores above.
479 //
480 // Ensure that the stores above are ordered-before the AllCpusInSync store
481 // by using a MemoryFence() with release semantics.
482 //
483 MemoryFence ();
484 }
485
486 //
487 // We've removed this set of APIC IDs from SMM data structures and
488 // have installed an ejection handler if needed.
489 //
490 return EFI_SUCCESS;
491 }
492
493 /**
494 CPU Hotplug MMI handler function.
495
496 This is a root MMI handler.
497
498 @param[in] DispatchHandle The unique handle assigned to this handler by
499 EFI_MM_SYSTEM_TABLE.MmiHandlerRegister().
500
501 @param[in] Context Context passed in by
502 EFI_MM_SYSTEM_TABLE.MmiManage(). Due to
503 CpuHotplugMmi() being a root MMI handler,
504 Context is ASSERT()ed to be NULL.
505
506 @param[in,out] CommBuffer Ignored, due to CpuHotplugMmi() being a root
507 MMI handler.
508
509 @param[in,out] CommBufferSize Ignored, due to CpuHotplugMmi() being a root
510 MMI handler.
511
512 @retval EFI_SUCCESS The MMI was handled and the MMI
513 source was quiesced. When returned
514 by a non-root MMI handler,
515 EFI_SUCCESS terminates the
516 processing of MMI handlers in
517 EFI_MM_SYSTEM_TABLE.MmiManage().
518 For a root MMI handler (i.e., for
519 the present function too),
520 EFI_SUCCESS behaves identically to
521 EFI_WARN_INTERRUPT_SOURCE_QUIESCED,
522 as further root MMI handlers are
523 going to be called by
524 EFI_MM_SYSTEM_TABLE.MmiManage()
525 anyway.
526
527 @retval EFI_WARN_INTERRUPT_SOURCE_QUIESCED The MMI source has been quiesced,
528 but other handlers should still
529 be called.
530
531 @retval EFI_WARN_INTERRUPT_SOURCE_PENDING The MMI source is still pending,
532 and other handlers should still
533 be called.
534
535 @retval EFI_INTERRUPT_PENDING The MMI source could not be
536 quiesced.
537 **/
538 STATIC
539 EFI_STATUS
540 EFIAPI
541 CpuHotplugMmi (
542 IN EFI_HANDLE DispatchHandle,
543 IN CONST VOID *Context OPTIONAL,
544 IN OUT VOID *CommBuffer OPTIONAL,
545 IN OUT UINTN *CommBufferSize OPTIONAL
546 )
547 {
548 EFI_STATUS Status;
549 UINT8 ApmControl;
550 UINT32 PluggedCount;
551 UINT32 ToUnplugCount;
552
553 //
554 // Assert that we are entering this function due to our root MMI handler
555 // registration.
556 //
557 ASSERT (DispatchHandle == mDispatchHandle);
558 //
559 // When MmiManage() is invoked to process root MMI handlers, the caller (the
560 // MM Core) is expected to pass in a NULL Context. MmiManage() then passes
561 // the same NULL Context to individual handlers.
562 //
563 ASSERT (Context == NULL);
564 //
565 // Read the MMI command value from the APM Control Port, to see if this is an
566 // MMI we should care about.
567 //
568 Status = mMmCpuIo->Io.Read (mMmCpuIo, MM_IO_UINT8, ICH9_APM_CNT, 1,
569 &ApmControl);
570 if (EFI_ERROR (Status)) {
571 DEBUG ((DEBUG_ERROR, "%a: failed to read ICH9_APM_CNT: %r\n", __FUNCTION__,
572 Status));
573 //
574 // We couldn't even determine if the MMI was for us or not.
575 //
576 goto Fatal;
577 }
578
579 if (ApmControl != ICH9_APM_CNT_CPU_HOTPLUG) {
580 //
581 // The MMI is not for us.
582 //
583 return EFI_WARN_INTERRUPT_SOURCE_QUIESCED;
584 }
585
586 //
587 // Collect the CPUs with pending events.
588 //
589 Status = QemuCpuhpCollectApicIds (
590 mMmCpuIo,
591 mCpuHotPlugData->ArrayLength, // PossibleCpuCount
592 mCpuHotPlugData->ArrayLength - 1, // ApicIdCount
593 mPluggedApicIds,
594 &PluggedCount,
595 mToUnplugApicIds,
596 mToUnplugSelectors,
597 &ToUnplugCount
598 );
599 if (EFI_ERROR (Status)) {
600 goto Fatal;
601 }
602
603 if (PluggedCount > 0) {
604 Status = ProcessHotAddedCpus (mPluggedApicIds, PluggedCount);
605 if (EFI_ERROR (Status)) {
606 goto Fatal;
607 }
608 }
609
610 if (ToUnplugCount > 0) {
611 Status = UnplugCpus (mToUnplugApicIds, mToUnplugSelectors, ToUnplugCount);
612 if (EFI_ERROR (Status)) {
613 goto Fatal;
614 }
615 }
616
617 //
618 // We've handled this MMI.
619 //
620 return EFI_SUCCESS;
621
622 Fatal:
623 ASSERT (FALSE);
624 CpuDeadLoop ();
625 //
626 // We couldn't handle this MMI.
627 //
628 return EFI_INTERRUPT_PENDING;
629 }
630
631
632 //
633 // Entry point function of this driver.
634 //
635 EFI_STATUS
636 EFIAPI
637 CpuHotplugEntry (
638 IN EFI_HANDLE ImageHandle,
639 IN EFI_SYSTEM_TABLE *SystemTable
640 )
641 {
642 EFI_STATUS Status;
643 UINTN Len;
644 UINTN Size;
645 UINTN SizeSel;
646
647 //
648 // This module should only be included when SMM support is required.
649 //
650 ASSERT (FeaturePcdGet (PcdSmmSmramRequire));
651 //
652 // This driver depends on the dynamically detected "SMRAM at default SMBASE"
653 // feature.
654 //
655 if (!PcdGetBool (PcdQ35SmramAtDefaultSmbase)) {
656 return EFI_UNSUPPORTED;
657 }
658
659 //
660 // Errors from here on are fatal; we cannot allow the boot to proceed if we
661 // can't set up this driver to handle CPU hotplug.
662 //
663 // First, collect the protocols needed later. All of these protocols are
664 // listed in our module DEPEX.
665 //
666 Status = gMmst->MmLocateProtocol (&gEfiMmCpuIoProtocolGuid,
667 NULL /* Registration */, (VOID **)&mMmCpuIo);
668 if (EFI_ERROR (Status)) {
669 DEBUG ((DEBUG_ERROR, "%a: locate MmCpuIo: %r\n", __FUNCTION__, Status));
670 goto Fatal;
671 }
672 Status = gMmst->MmLocateProtocol (&gEfiSmmCpuServiceProtocolGuid,
673 NULL /* Registration */, (VOID **)&mMmCpuService);
674 if (EFI_ERROR (Status)) {
675 DEBUG ((DEBUG_ERROR, "%a: locate MmCpuService: %r\n", __FUNCTION__,
676 Status));
677 goto Fatal;
678 }
679
680 //
681 // Our DEPEX on EFI_SMM_CPU_SERVICE_PROTOCOL guarantees that PiSmmCpuDxeSmm
682 // has pointed:
683 // - PcdCpuHotPlugDataAddress to CPU_HOT_PLUG_DATA in SMRAM,
684 // - PcdCpuHotEjectDataAddress to CPU_HOT_EJECT_DATA in SMRAM, if the
685 // possible CPU count is greater than 1.
686 //
687 mCpuHotPlugData = (VOID *)(UINTN)PcdGet64 (PcdCpuHotPlugDataAddress);
688 mCpuHotEjectData = (VOID *)(UINTN)PcdGet64 (PcdCpuHotEjectDataAddress);
689
690 if (mCpuHotPlugData == NULL) {
691 Status = EFI_NOT_FOUND;
692 DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_PLUG_DATA: %r\n", __FUNCTION__, Status));
693 goto Fatal;
694 }
695 //
696 // If the possible CPU count is 1, there's nothing for this driver to do.
697 //
698 if (mCpuHotPlugData->ArrayLength == 1) {
699 return EFI_UNSUPPORTED;
700 }
701
702 if (mCpuHotEjectData == NULL) {
703 Status = EFI_NOT_FOUND;
704 } else if (mCpuHotPlugData->ArrayLength != mCpuHotEjectData->ArrayLength) {
705 Status = EFI_INVALID_PARAMETER;
706 } else {
707 Status = EFI_SUCCESS;
708 }
709 if (EFI_ERROR (Status)) {
710 DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_EJECT_DATA: %r\n", __FUNCTION__, Status));
711 goto Fatal;
712 }
713
714 //
715 // Allocate the data structures that depend on the possible CPU count.
716 //
717 if (RETURN_ERROR (SafeUintnSub (mCpuHotPlugData->ArrayLength, 1, &Len)) ||
718 RETURN_ERROR (SafeUintnMult (sizeof (APIC_ID), Len, &Size)) ||
719 RETURN_ERROR (SafeUintnMult (sizeof (UINT32), Len, &SizeSel))) {
720 Status = EFI_ABORTED;
721 DEBUG ((DEBUG_ERROR, "%a: invalid CPU_HOT_PLUG_DATA\n", __FUNCTION__));
722 goto Fatal;
723 }
724 Status = gMmst->MmAllocatePool (EfiRuntimeServicesData, Size,
725 (VOID **)&mPluggedApicIds);
726 if (EFI_ERROR (Status)) {
727 DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status));
728 goto Fatal;
729 }
730 Status = gMmst->MmAllocatePool (EfiRuntimeServicesData, Size,
731 (VOID **)&mToUnplugApicIds);
732 if (EFI_ERROR (Status)) {
733 DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status));
734 goto ReleasePluggedApicIds;
735 }
736 Status = gMmst->MmAllocatePool (EfiRuntimeServicesData, SizeSel,
737 (VOID **)&mToUnplugSelectors);
738 if (EFI_ERROR (Status)) {
739 DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status));
740 goto ReleaseToUnplugApicIds;
741 }
742
743 //
744 // Allocate the Post-SMM Pen for hot-added CPUs.
745 //
746 Status = SmbaseAllocatePostSmmPen (&mPostSmmPenAddress,
747 SystemTable->BootServices);
748 if (EFI_ERROR (Status)) {
749 goto ReleaseToUnplugSelectors;
750 }
751
752 //
753 // Sanity-check the CPU hotplug interface.
754 //
755 // Both of the following features are part of QEMU 5.0, introduced primarily
756 // in commit range 3e08b2b9cb64..3a61c8db9d25:
757 //
758 // (a) the QEMU_CPUHP_CMD_GET_ARCH_ID command of the modern CPU hotplug
759 // interface,
760 //
761 // (b) the "SMRAM at default SMBASE" feature.
762 //
763 // From these, (b) is restricted to 5.0+ machine type versions, while (a)
764 // does not depend on machine type version. Because we ensured the stricter
765 // condition (b) through PcdQ35SmramAtDefaultSmbase above, the (a)
766 // QEMU_CPUHP_CMD_GET_ARCH_ID command must now be available too. While we
767 // can't verify the presence of precisely that command, we can still verify
768 // (sanity-check) that the modern interface is active, at least.
769 //
770 // Consult the "Typical usecases | Detecting and enabling modern CPU hotplug
771 // interface" section in QEMU's "docs/specs/acpi_cpu_hotplug.txt", on the
772 // following.
773 //
774 QemuCpuhpWriteCpuSelector (mMmCpuIo, 0);
775 QemuCpuhpWriteCpuSelector (mMmCpuIo, 0);
776 QemuCpuhpWriteCommand (mMmCpuIo, QEMU_CPUHP_CMD_GET_PENDING);
777 if (QemuCpuhpReadCommandData2 (mMmCpuIo) != 0) {
778 Status = EFI_NOT_FOUND;
779 DEBUG ((DEBUG_ERROR, "%a: modern CPU hotplug interface: %r\n",
780 __FUNCTION__, Status));
781 goto ReleasePostSmmPen;
782 }
783
784 //
785 // Register the handler for the CPU Hotplug MMI.
786 //
787 Status = gMmst->MmiHandlerRegister (
788 CpuHotplugMmi,
789 NULL, // HandlerType: root MMI handler
790 &mDispatchHandle
791 );
792 if (EFI_ERROR (Status)) {
793 DEBUG ((DEBUG_ERROR, "%a: MmiHandlerRegister(): %r\n", __FUNCTION__,
794 Status));
795 goto ReleasePostSmmPen;
796 }
797
798 //
799 // Install the handler for the hot-added CPUs' first SMI.
800 //
801 SmbaseInstallFirstSmiHandler ();
802
803 return EFI_SUCCESS;
804
805 ReleasePostSmmPen:
806 SmbaseReleasePostSmmPen (mPostSmmPenAddress, SystemTable->BootServices);
807 mPostSmmPenAddress = 0;
808
809 ReleaseToUnplugSelectors:
810 gMmst->MmFreePool (mToUnplugSelectors);
811 mToUnplugSelectors = NULL;
812
813 ReleaseToUnplugApicIds:
814 gMmst->MmFreePool (mToUnplugApicIds);
815 mToUnplugApicIds = NULL;
816
817 ReleasePluggedApicIds:
818 gMmst->MmFreePool (mPluggedApicIds);
819 mPluggedApicIds = NULL;
820
821 Fatal:
822 ASSERT (FALSE);
823 CpuDeadLoop ();
824 return Status;
825 }