VirtualBox

source: vbox/trunk/src/VBox/Devices/PC/DevAPIC.cpp@ 57426

Last change on this file since 57426 was 57358, checked in by vboxsync, 9 years ago

*: scm cleanup run.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 90.6 KB
Line 
1/* $Id: DevAPIC.cpp 57358 2015-08-14 15:16:38Z vboxsync $ */
2/** @file
3 * Advanced Programmable Interrupt Controller (APIC) Device.
4 *
5 * @remarks This code does not use pThis, it uses pDev and pApic due to the
6 * non-standard arrangements of the APICs wrt PDM.
7 */
8
9/*
10 * Copyright (C) 2006-2015 Oracle Corporation
11 *
12 * This file is part of VirtualBox Open Source Edition (OSE), as
13 * available from http://www.virtualbox.org. This file is free software;
14 * you can redistribute it and/or modify it under the terms of the GNU
15 * General Public License (GPL) as published by the Free Software
16 * Foundation, in version 2 as it comes in the "COPYING" file of the
17 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19 * --------------------------------------------------------------------
20 *
21 * This code is based on:
22 *
23 * apic.c revision 1.5 @@OSETODO
24 *
25 * APIC support
26 *
27 * Copyright (c) 2004-2005 Fabrice Bellard
28 *
29 * This library is free software; you can redistribute it and/or
30 * modify it under the terms of the GNU Lesser General Public
31 * License as published by the Free Software Foundation; either
32 * version 2 of the License, or (at your option) any later version.
33 *
34 * This library is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
37 * Lesser General Public License for more details.
38 *
39 * You should have received a copy of the GNU Lesser General Public
40 * License along with this library; if not, write to the Free Software
41 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
42 */
43
44
45/*********************************************************************************************************************************
46* Header Files *
47*********************************************************************************************************************************/
48#define LOG_GROUP LOG_GROUP_DEV_APIC
49#include <VBox/vmm/pdmdev.h>
50
51#include <VBox/log.h>
52#include <VBox/vmm/stam.h>
53#include <VBox/vmm/vmcpuset.h>
54#include <iprt/asm.h>
55#include <iprt/assert.h>
56
57#include <VBox/msi.h>
58
59#include "VBoxDD2.h"
60#include "DevApic.h"
61
62
63/*********************************************************************************************************************************
64* Defined Constants And Macros *
65*********************************************************************************************************************************/
66#define MSR_IA32_APICBASE_ENABLE (1<<11)
67#define MSR_IA32_APICBASE_X2ENABLE (1<<10)
68#define MSR_IA32_APICBASE_BASE (0xfffff<<12) /** @todo r=bird: This is not correct according to current specs! */
69
70#ifdef _MSC_VER
71# pragma warning(disable:4244)
72#endif
73
74/** The current saved state version.*/
75#define APIC_SAVED_STATE_VERSION 3
76/** The saved state version used by VirtualBox v3 and earlier.
77 * This does not include the config. */
78#define APIC_SAVED_STATE_VERSION_VBOX_30 2
79/** Some ancient version... */
80#define APIC_SAVED_STATE_VERSION_ANCIENT 1
81
82/* version 0x14: Pentium 4, Xeon; LVT count depends on that */
83#define APIC_HW_VERSION 0x14
84
85/** @def APIC_LOCK
86 * Acquires the PDM lock. */
87#define APIC_LOCK(a_pDev, rcBusy) \
88 do { \
89 int rc2 = PDMCritSectEnter((a_pDev)->CTX_SUFF(pCritSect), (rcBusy)); \
90 if (rc2 != VINF_SUCCESS) \
91 return rc2; \
92 } while (0)
93
94/** @def APIC_LOCK_VOID
95 * Acquires the PDM lock and does not expect failure (i.e. ring-3 only!). */
96#define APIC_LOCK_VOID(a_pDev, rcBusy) \
97 do { \
98 int rc2 = PDMCritSectEnter((a_pDev)->CTX_SUFF(pCritSect), (rcBusy)); \
99 AssertLogRelRCReturnVoid(rc2); \
100 } while (0)
101
102/** @def APIC_UNLOCK
103 * Releases the PDM lock. */
104#define APIC_UNLOCK(a_pDev) \
105 PDMCritSectLeave((a_pDev)->CTX_SUFF(pCritSect))
106
107/** @def APIC_AND_TM_LOCK
108 * Acquires the virtual sync clock lock as well as the PDM lock. */
109#define APIC_AND_TM_LOCK(a_pDev, a_pApic, rcBusy) \
110 do { \
111 int rc2 = TMTimerLock((a_pApic)->CTX_SUFF(pTimer), (rcBusy)); \
112 if (rc2 != VINF_SUCCESS) \
113 return rc2; \
114 rc2 = PDMCritSectEnter((a_pDev)->CTX_SUFF(pCritSect), (rcBusy)); \
115 if (rc2 != VINF_SUCCESS) \
116 { \
117 TMTimerUnlock((a_pApic)->CTX_SUFF(pTimer)); \
118 return rc2; \
119 } \
120 } while (0)
121
122/** @def APIC_AND_TM_UNLOCK
123 * Releases the PDM lock as well as the TM virtual sync clock lock. */
124#define APIC_AND_TM_UNLOCK(a_pDev, a_pApic) \
125 do { \
126 TMTimerUnlock((a_pApic)->CTX_SUFF(pTimer)); \
127 PDMCritSectLeave((a_pDev)->CTX_SUFF(pCritSect)); \
128 } while (0)
129
130/**
131 * Begins an APIC enumeration block.
132 *
133 * Code placed between this and the APIC_FOREACH_END macro will be executed for
134 * each APIC instance present in the system.
135 *
136 * @param a_pDev The APIC device.
137 */
138#define APIC_FOREACH_BEGIN(a_pDev) \
139 do { \
140 VMCPUID const cApics = (a_pDev)->cCpus; \
141 APICState *pCurApic = (a_pDev)->CTX_SUFF(paLapics); \
142 for (VMCPUID iCurApic = 0; iCurApic < cApics; iCurApic++, pCurApic++) \
143 { \
144 do { } while (0)
145
146/**
147 * Begins an APIC enumeration block, given a destination set.
148 *
149 * Code placed between this and the APIC_FOREACH_END macro will be executed for
150 * each APIC instance present in @a a_pDstSet.
151 *
152 * @param a_pDev The APIC device.
153 * @param a_pDstSet The destination set.
154 */
155#define APIC_FOREACH_IN_SET_BEGIN(a_pDev, a_pDstSet) \
156 APIC_FOREACH_BEGIN(a_pDev); \
157 if (!VMCPUSET_IS_PRESENT((a_pDstSet), iCurApic)) \
158 continue; \
159 do { } while (0)
160
161
162/** Counterpart to APIC_FOREACH_IN_SET_BEGIN and APIC_FOREACH_BEGIN. */
163#define APIC_FOREACH_END() \
164 } \
165 } while (0)
166
167#define DEBUG_APIC
168
169#define ESR_ILLEGAL_ADDRESS (1 << 7)
170
171#define APIC_SV_ENABLE (1 << 8)
172
173#define APIC_MAX_PATCH_ATTEMPTS 100
174
175
176/*********************************************************************************************************************************
177* Structures and Typedefs *
178*********************************************************************************************************************************/
179typedef uint32_t PhysApicId;
180typedef uint32_t LogApicId;
181
182typedef struct APIC256BITREG
183{
184 /** The bitmap data. */
185 uint32_t au32Bitmap[8 /*256/32*/];
186} APIC256BITREG;
187typedef APIC256BITREG *PAPIC256BITREG;
188typedef APIC256BITREG const *PCAPIC256BITREG;
189
190/**
191 * Tests if a bit in the 256-bit APIC register is set.
192 *
193 * @returns true if set, false if clear.
194 *
195 * @param pReg The register.
196 * @param iBit The bit to test for.
197 */
198DECLINLINE(bool) Apic256BitReg_IsBitSet(PCAPIC256BITREG pReg, unsigned iBit)
199{
200 Assert(iBit < 256);
201 return ASMBitTest(&pReg->au32Bitmap[0], iBit);
202}
203
204
205/**
206 * Sets a bit in the 256-bit APIC register is set.
207 *
208 * @param pReg The register.
209 * @param iBit The bit to set.
210 */
211DECLINLINE(void) Apic256BitReg_SetBit(PAPIC256BITREG pReg, unsigned iBit)
212{
213 Assert(iBit < 256);
214 return ASMBitSet(&pReg->au32Bitmap[0], iBit);
215}
216
217
218/**
219 * Clears a bit in the 256-bit APIC register is set.
220 *
221 * @param pReg The register.
222 * @param iBit The bit to clear.
223 */
224DECLINLINE(void) Apic256BitReg_ClearBit(PAPIC256BITREG pReg, unsigned iBit)
225{
226 Assert(iBit < 256);
227 return ASMBitClear(&pReg->au32Bitmap[0], iBit);
228}
229
230/**
231 * Clears all bits in the 256-bit APIC register set.
232 *
233 * @param pReg The register.
234 */
235DECLINLINE(void) Apic256BitReg_Empty(PAPIC256BITREG pReg)
236{
237 memset(&pReg->au32Bitmap[0], 0, sizeof(pReg->au32Bitmap));
238}
239
240/**
241 * Finds the last bit set in the register, i.e. the highest priority interrupt.
242 *
243 * @returns The index of the found bit, @a iRetAllClear if none was found.
244 *
245 * @param pReg The register.
246 * @param iRetAllClear What to return if all bits are clear.
247 */
248static int Apic256BitReg_FindLastSetBit(PCAPIC256BITREG pReg, int iRetAllClear)
249{
250 uint32_t i = RT_ELEMENTS(pReg->au32Bitmap);
251 while (i-- > 0)
252 {
253 uint32_t u = pReg->au32Bitmap[i];
254 if (u)
255 {
256 u = ASMBitLastSetU32(u);
257 u--;
258 u |= i << 5;
259 return (int)u;
260 }
261 }
262 return iRetAllClear;
263}
264
265
266/**
267 * The state of one APIC.
268 *
269 * @remarks This is generally pointed to by a parameter or variable named pApic.
270 */
271typedef struct APICState
272{
273 /** In service register (ISR). */
274 APIC256BITREG isr;
275 /** Trigger mode register (TMR). */
276 APIC256BITREG tmr;
277 /** Interrupt request register (IIR). */
278 APIC256BITREG irr;
279 uint32_t lvt[APIC_LVT_NB];
280 uint32_t apicbase;
281 /* Task priority register (interrupt level) */
282 uint32_t tpr;
283 /* Logical APIC id - user programmable */
284 LogApicId id;
285 /* Physical APIC id - not visible to user, constant */
286 PhysApicId phys_id;
287 /** @todo is it logical or physical? Not really used anyway now. */
288 PhysApicId arb_id;
289 uint32_t spurious_vec;
290 uint8_t log_dest;
291 uint8_t dest_mode;
292 uint32_t esr; /* error register */
293 uint32_t icr[2];
294 uint32_t divide_conf;
295 int count_shift;
296 uint32_t initial_count;
297 uint32_t Alignment0;
298
299 /** The time stamp of the initial_count load, i.e. when it was started. */
300 uint64_t initial_count_load_time;
301 /** The time stamp of the next timer callback. */
302 uint64_t next_time;
303 /** The APIC timer - R3 Ptr. */
304 PTMTIMERR3 pTimerR3;
305 /** The APIC timer - R0 Ptr. */
306 PTMTIMERR0 pTimerR0;
307 /** The APIC timer - RC Ptr. */
308 PTMTIMERRC pTimerRC;
309 /** Whether the timer is armed or not */
310 bool fTimerArmed;
311 /** Alignment */
312 bool afAlignment[3];
313 /** The initial_count value used for the current frequency hint. */
314 uint32_t uHintedInitialCount;
315 /** The count_shift value used for the current frequency hint. */
316 uint32_t uHintedCountShift;
317 /** Timer description timer. */
318 R3PTRTYPE(char *) pszDesc;
319
320 /** The IRQ tags and source IDs for each (tracing purposes). */
321 uint32_t auTags[256];
322
323# ifdef VBOX_WITH_STATISTICS
324# if HC_ARCH_BITS == 32
325 uint32_t u32Alignment0;
326# endif
327 STAMCOUNTER StatTimerSetInitialCount;
328 STAMCOUNTER StatTimerSetInitialCountArm;
329 STAMCOUNTER StatTimerSetInitialCountDisarm;
330 STAMCOUNTER StatTimerSetLvt;
331 STAMCOUNTER StatTimerSetLvtClearPeriodic;
332 STAMCOUNTER StatTimerSetLvtPostponed;
333 STAMCOUNTER StatTimerSetLvtArmed;
334 STAMCOUNTER StatTimerSetLvtArm;
335 STAMCOUNTER StatTimerSetLvtArmRetries;
336 STAMCOUNTER StatTimerSetLvtNoRelevantChange;
337# endif
338
339} APICState;
340
341AssertCompileMemberAlignment(APICState, initial_count_load_time, 8);
342# ifdef VBOX_WITH_STATISTICS
343AssertCompileMemberAlignment(APICState, StatTimerSetInitialCount, 8);
344# endif
345
346/**
347 * The wrapper device for the all the APICs.
348 *
349 * @remarks This is generally pointed to by a parameter or variable named pDev.
350 */
351typedef struct
352{
353 /** The device instance - R3 Ptr. */
354 PPDMDEVINSR3 pDevInsR3;
355 /** The APIC helpers - R3 Ptr. */
356 PCPDMAPICHLPR3 pApicHlpR3;
357 /** LAPICs states - R3 Ptr */
358 R3PTRTYPE(APICState *) paLapicsR3;
359 /** The critical section - R3 Ptr. */
360 R3PTRTYPE(PPDMCRITSECT) pCritSectR3;
361
362 /** The device instance - R0 Ptr. */
363 PPDMDEVINSR0 pDevInsR0;
364 /** The APIC helpers - R0 Ptr. */
365 PCPDMAPICHLPR0 pApicHlpR0;
366 /** LAPICs states - R0 Ptr */
367 R0PTRTYPE(APICState *) paLapicsR0;
368 /** The critical section - R3 Ptr. */
369 R0PTRTYPE(PPDMCRITSECT) pCritSectR0;
370
371 /** The device instance - RC Ptr. */
372 PPDMDEVINSRC pDevInsRC;
373 /** The APIC helpers - RC Ptr. */
374 PCPDMAPICHLPRC pApicHlpRC;
375 /** LAPICs states - RC Ptr */
376 RCPTRTYPE(APICState *) paLapicsRC;
377 /** The critical section - R3 Ptr. */
378 RCPTRTYPE(PPDMCRITSECT) pCritSectRC;
379
380 /** APIC specification version in this virtual hardware configuration. */
381 PDMAPICVERSION enmVersion;
382
383 /** Number of attempts made to optimize TPR accesses. */
384 uint32_t cTPRPatchAttempts;
385
386 /** Number of CPUs on the system (same as LAPIC count). */
387 uint32_t cCpus;
388 /** Whether we've got an IO APIC or not. */
389 bool fIoApic;
390 /** Alignment padding. */
391 bool afPadding[3];
392
393# ifdef VBOX_WITH_STATISTICS
394 STAMCOUNTER StatMMIOReadGC;
395 STAMCOUNTER StatMMIOReadHC;
396 STAMCOUNTER StatMMIOWriteGC;
397 STAMCOUNTER StatMMIOWriteHC;
398 STAMCOUNTER StatClearedActiveIrq;
399# endif
400} APICDeviceInfo;
401# ifdef VBOX_WITH_STATISTICS
402AssertCompileMemberAlignment(APICDeviceInfo, StatMMIOReadGC, 8);
403# endif
404
405#ifndef VBOX_DEVICE_STRUCT_TESTCASE
406
407
408/*********************************************************************************************************************************
409* Internal Functions *
410*********************************************************************************************************************************/
411static void apic_update_tpr(APICDeviceInfo *pDev, APICState *pApic, uint32_t val);
412
413static void apic_eoi(APICDeviceInfo *pDev, APICState *pApic); /* */
414static PVMCPUSET apic_get_delivery_bitmask(APICDeviceInfo *pDev, uint8_t dest, uint8_t dest_mode, PVMCPUSET pDstSet);
415static int apic_deliver(APICDeviceInfo *pDev, APICState *pApic,
416 uint8_t dest, uint8_t dest_mode,
417 uint8_t delivery_mode, uint8_t vector_num,
418 uint8_t polarity, uint8_t trigger_mode);
419static int apic_get_arb_pri(APICState const *pApic);
420static int apic_get_ppr(APICState const *pApic);
421static uint32_t apic_get_current_count(APICDeviceInfo const *pDev, APICState const *pApic);
422static void apicTimerSetInitialCount(APICDeviceInfo *pDev, APICState *pApic, uint32_t initial_count);
423static void apicTimerSetLvt(APICDeviceInfo *pDev, APICState *pApic, uint32_t fNew);
424static void apicSendInitIpi(APICDeviceInfo *pDev, APICState *pApic);
425
426static void apicR3InitIpi(APICDeviceInfo *pDev, APICState *pApic);
427static void apic_set_irq(APICDeviceInfo *pDev, APICState *pApic, int vector_num, int trigger_mode, uint32_t uTagSrc);
428static bool apic_update_irq(APICDeviceInfo *pDev, APICState *pApic);
429
430
431DECLINLINE(APICState *) apicGetStateById(APICDeviceInfo *pDev, VMCPUID id)
432{
433 AssertFatalMsg(id < pDev->cCpus, ("CPU id %d out of range\n", id));
434 return &pDev->CTX_SUFF(paLapics)[id];
435}
436
437/**
438 * Get the APIC state for the calling EMT.
439 */
440DECLINLINE(APICState *) apicGetStateByCurEmt(APICDeviceInfo *pDev)
441{
442 /* LAPIC's array is indexed by CPU id */
443 VMCPUID id = pDev->CTX_SUFF(pApicHlp)->pfnGetCpuId(pDev->CTX_SUFF(pDevIns));
444 return apicGetStateById(pDev, id);
445}
446
447DECLINLINE(VMCPUID) getCpuFromLapic(APICDeviceInfo *pDev, APICState *pApic)
448{
449 /* for now we assume LAPIC physical id == CPU id */
450 return (VMCPUID)pApic->phys_id;
451}
452
453DECLINLINE(void) apicCpuSetInterrupt(APICDeviceInfo *pDev, APICState *pApic, PDMAPICIRQ enmType = PDMAPICIRQ_HARDWARE)
454{
455 LogFlow(("apic: setting interrupt flag for cpu %d\n", getCpuFromLapic(pDev, pApic)));
456 pDev->CTX_SUFF(pApicHlp)->pfnSetInterruptFF(pDev->CTX_SUFF(pDevIns), enmType,
457 getCpuFromLapic(pDev, pApic));
458}
459
460DECLINLINE(void) apicCpuClearInterrupt(APICDeviceInfo *pDev, APICState *pApic, PDMAPICIRQ enmType = PDMAPICIRQ_HARDWARE)
461{
462 LogFlow(("apic: clear interrupt flag\n"));
463 pDev->CTX_SUFF(pApicHlp)->pfnClearInterruptFF(pDev->CTX_SUFF(pDevIns), enmType,
464 getCpuFromLapic(pDev, pApic));
465}
466
467# ifdef IN_RING3
468
469DECLINLINE(void) apicR3CpuSendSipi(APICDeviceInfo *pDev, APICState *pApic, int vector)
470{
471 Log2(("apic: send SIPI vector=%d\n", vector));
472
473 pDev->pApicHlpR3->pfnSendSipi(pDev->pDevInsR3,
474 getCpuFromLapic(pDev, pApic),
475 vector);
476}
477
478DECLINLINE(void) apicR3CpuSendInitIpi(APICDeviceInfo *pDev, APICState *pApic)
479{
480 Log2(("apic: send init IPI\n"));
481
482 pDev->pApicHlpR3->pfnSendInitIpi(pDev->pDevInsR3,
483 getCpuFromLapic(pDev, pApic));
484}
485
486# endif /* IN_RING3 */
487
488DECLINLINE(uint32_t) getApicEnableBits(APICDeviceInfo *pDev)
489{
490 switch (pDev->enmVersion)
491 {
492 case PDMAPICVERSION_NONE:
493 return 0;
494 case PDMAPICVERSION_APIC:
495 return MSR_IA32_APICBASE_ENABLE;
496 case PDMAPICVERSION_X2APIC:
497 return MSR_IA32_APICBASE_ENABLE | MSR_IA32_APICBASE_X2ENABLE;
498 default:
499 AssertMsgFailed(("Unsupported APIC version %d\n", pDev->enmVersion));
500 return 0;
501 }
502}
503
504DECLINLINE(PDMAPICVERSION) getApicMode(APICState *apic)
505{
506 switch (((apic->apicbase) >> 10) & 0x3)
507 {
508 case 0:
509 return PDMAPICVERSION_NONE;
510 case 1:
511 default:
512 /* Invalid */
513 return PDMAPICVERSION_NONE;
514 case 2:
515 return PDMAPICVERSION_APIC;
516 case 3:
517 return PDMAPICVERSION_X2APIC;
518 }
519}
520
521static int apic_bus_deliver(APICDeviceInfo *pDev,
522 PCVMCPUSET pDstSet, uint8_t delivery_mode,
523 uint8_t vector_num, uint8_t polarity,
524 uint8_t trigger_mode, uint32_t uTagSrc)
525{
526 LogFlow(("apic_bus_deliver mask=%R[vmcpuset] mode=%x vector=%x polarity=%x trigger_mode=%x uTagSrc=%#x\n",
527 pDstSet, delivery_mode, vector_num, polarity, trigger_mode, uTagSrc));
528
529 switch (delivery_mode)
530 {
531 case APIC_DM_LOWPRI:
532 {
533 VMCPUID idDstCpu = VMCPUSET_FIND_FIRST_PRESENT(pDstSet);
534 if (idDstCpu != NIL_VMCPUID)
535 {
536 APICState *pApic = apicGetStateById(pDev, idDstCpu);
537 apic_set_irq(pDev, pApic, vector_num, trigger_mode, uTagSrc);
538 }
539 return VINF_SUCCESS;
540 }
541
542 case APIC_DM_FIXED:
543 /** @todo XXX: arbitration */
544 break;
545
546 case APIC_DM_SMI:
547 APIC_FOREACH_IN_SET_BEGIN(pDev, pDstSet);
548 apicCpuSetInterrupt(pDev, pCurApic, PDMAPICIRQ_SMI);
549 APIC_FOREACH_END();
550 return VINF_SUCCESS;
551
552 case APIC_DM_NMI:
553 APIC_FOREACH_IN_SET_BEGIN(pDev, pDstSet);
554 apicCpuSetInterrupt(pDev, pCurApic, PDMAPICIRQ_NMI);
555 APIC_FOREACH_END();
556 return VINF_SUCCESS;
557
558 case APIC_DM_INIT:
559 /* normal INIT IPI sent to processors */
560#ifdef IN_RING3
561 APIC_FOREACH_IN_SET_BEGIN(pDev, pDstSet);
562 apicSendInitIpi(pDev, pCurApic);
563 APIC_FOREACH_END();
564 return VINF_SUCCESS;
565#else
566 /* We shall send init IPI only in R3. */
567 return VINF_IOM_R3_MMIO_READ_WRITE;
568#endif /* IN_RING3 */
569
570 case APIC_DM_EXTINT:
571 /* handled in I/O APIC code */
572 break;
573
574 default:
575 return VINF_SUCCESS;
576 }
577
578 APIC_FOREACH_IN_SET_BEGIN(pDev, pDstSet);
579 apic_set_irq(pDev, pCurApic, vector_num, trigger_mode, uTagSrc);
580 APIC_FOREACH_END();
581 return VINF_SUCCESS;
582}
583
584
585PDMBOTHCBDECL(void) apicSetBase(PPDMDEVINS pDevIns, VMCPUID idCpu, uint64_t val)
586{
587 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
588 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
589 APICState *pApic = apicGetStateById(pDev, idCpu);
590 Log(("apicSetBase: %016RX64\n", val));
591
592 /** @todo do we need to lock here ? */
593 /* APIC_LOCK_VOID(pDev, VERR_INTERNAL_ERROR); */
594 /** @todo If this change is valid immediately, then we should change the MMIO registration! */
595 /* We cannot change if this CPU is BSP or not by writing to MSR - it's hardwired */
596 PDMAPICVERSION oldMode = getApicMode(pApic);
597 pApic->apicbase = (val & 0xfffff000) /* base */
598 | (val & getApicEnableBits(pDev)) /* mode */
599 | (pApic->apicbase & MSR_IA32_APICBASE_BSP) /* keep BSP bit */;
600 PDMAPICVERSION newMode = getApicMode(pApic);
601
602 if (oldMode != newMode)
603 {
604 switch (newMode)
605 {
606 case PDMAPICVERSION_NONE:
607 {
608 pApic->spurious_vec &= ~APIC_SV_ENABLE;
609 /* Clear any pending APIC interrupt action flag. */
610 apicCpuClearInterrupt(pDev, pApic);
611 /* See @bugref{7097}. Intel IA-32/64 Spec 10.4.3:
612 * "When IA32_APIC_BASE[11] is 0, the processor is functionally equivalent to
613 * an IA-32 processor without an on-chip APIC. The CPUID feature flag for the
614 * APIC (see Section 10.4.2, 'Presence of the Local APIC') is also set to 0."
615 */
616 pDev->CTX_SUFF(pApicHlp)->pfnChangeFeature(pDevIns, PDMAPICVERSION_NONE);
617 break;
618 }
619 case PDMAPICVERSION_APIC:
620 /** @todo map MMIO ranges, if needed */
621 break;
622 case PDMAPICVERSION_X2APIC:
623 /** @todo unmap MMIO ranges of this APIC, according to the spec. This is how
624 * real hw works! (Remember the problem disabling NMI watchdog timers in
625 * the world switchers when host used x2apic?)! */
626 break;
627 default:
628 break;
629 }
630 }
631 /* APIC_UNLOCK(pDev); */
632}
633
634PDMBOTHCBDECL(uint64_t) apicGetBase(PPDMDEVINS pDevIns, VMCPUID idCpu)
635{
636 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
637 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
638 APICState *pApic = apicGetStateById(pDev, idCpu);
639 LogFlow(("apicGetBase: %016llx\n", (uint64_t)pApic->apicbase));
640 return pApic->apicbase;
641}
642
643PDMBOTHCBDECL(void) apicSetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t val)
644{
645 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
646 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
647 APICState *pApic = apicGetStateById(pDev, idCpu);
648 LogFlow(("apicSetTPR: val=%#x (trp %#x -> %#x)\n", val, pApic->tpr, val));
649 apic_update_tpr(pDev, pApic, val);
650}
651
652PDMBOTHCBDECL(uint8_t) apicGetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu)
653{
654 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
655 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
656 APICState *pApic = apicGetStateById(pDev, idCpu);
657 Log2(("apicGetTPR: returns %#x\n", pApic->tpr));
658 return pApic->tpr;
659}
660
661
662PDMBOTHCBDECL(uint64_t) apicGetTimerFreq(PPDMDEVINS pDevIns)
663{
664 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
665 APICState *pApic = apicGetStateById(pDev, 0);
666 uint64_t uTimer = TMTimerGetFreq(pApic->CTX_SUFF(pTimer));
667 Log2(("apicGetTimerFreq: returns %#RX64\n", uTimer));
668 return uTimer;
669}
670
671
672/**
673 * apicWriteRegister helper for dealing with invalid register access.
674 *
675 * @returns Strict VBox status code.
676 * @param pDev The PDM device instance.
677 * @param pApic The APIC being written to.
678 * @param iReg The APIC register index.
679 * @param u64Value The value being written.
680 * @param rcBusy The busy return code to employ. See
681 * PDMCritSectEnter for a description.
682 * @param fMsr Set if called via MSR, clear if MMIO.
683 */
684static int apicWriteRegisterInvalid(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t u64Value,
685 int rcBusy, bool fMsr)
686{
687 Log(("apicWriteRegisterInvalid/%u: iReg=%#x fMsr=%RTbool u64Value=%#llx\n", pApic->phys_id, iReg, fMsr, u64Value));
688 int rc = PDMDevHlpDBGFStop(pDev->CTX_SUFF(pDevIns), RT_SRC_POS,
689 "iReg=%#x fMsr=%RTbool u64Value=%#llx id=%u\n", iReg, fMsr, u64Value, pApic->phys_id);
690 APIC_LOCK(pDev, rcBusy);
691 pApic->esr |= ESR_ILLEGAL_ADDRESS;
692 APIC_UNLOCK(pDev);
693 return rc;
694}
695
696
697
698/**
699 * Writes to an APIC register via MMIO or MSR.
700 *
701 * @returns Strict VBox status code.
702 * @param pDev The PDM device instance.
703 * @param pApic The APIC being written to.
704 * @param iReg The APIC register index.
705 * @param u64Value The value being written.
706 * @param rcBusy The busy return code to employ. See
707 * PDMCritSectEnter for a description.
708 * @param fMsr Set if called via MSR, clear if MMIO.
709 */
710static int apicWriteRegister(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t u64Value,
711 int rcBusy, bool fMsr)
712{
713 Assert(!PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
714
715 int rc = VINF_SUCCESS;
716 switch (iReg)
717 {
718 case 0x02:
719 APIC_LOCK(pDev, rcBusy);
720 pApic->id = (u64Value >> 24); /** @todo r=bird: Is the range supposed to be 40 bits??? */
721 APIC_UNLOCK(pDev);
722 break;
723
724 case 0x03:
725 /* read only, ignore write. */
726 break;
727
728 case 0x08:
729 APIC_LOCK(pDev, rcBusy);
730 apic_update_tpr(pDev, pApic, u64Value);
731 APIC_UNLOCK(pDev);
732 break;
733
734 case 0x09: case 0x0a:
735 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
736 break;
737
738 case 0x0b: /* EOI */
739 APIC_LOCK(pDev, rcBusy);
740 apic_eoi(pDev, pApic);
741 APIC_UNLOCK(pDev);
742 break;
743
744 case 0x0d:
745 APIC_LOCK(pDev, rcBusy);
746 pApic->log_dest = (u64Value >> 24) & 0xff;
747 APIC_UNLOCK(pDev);
748 break;
749
750 case 0x0e:
751 APIC_LOCK(pDev, rcBusy);
752 pApic->dest_mode = u64Value >> 28; /** @todo r=bird: range? This used to be 32-bit before morphed into an MSR handler. */
753 APIC_UNLOCK(pDev);
754 break;
755
756 case 0x0f:
757 APIC_LOCK(pDev, rcBusy);
758 pApic->spurious_vec = u64Value & 0x1ff;
759 apic_update_irq(pDev, pApic);
760 APIC_UNLOCK(pDev);
761 break;
762
763 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
764 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
765 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
766 case 0x28:
767 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
768 break;
769
770 case 0x30:
771 APIC_LOCK(pDev, rcBusy);
772 pApic->icr[0] = (uint32_t)u64Value;
773 if (fMsr) /* Here one of the differences with regular APIC: ICR is single 64-bit register */
774 pApic->icr[1] = (uint32_t)(u64Value >> 32);
775 rc = apic_deliver(pDev, pApic, (pApic->icr[1] >> 24) & 0xff, (pApic->icr[0] >> 11) & 1,
776 (pApic->icr[0] >> 8) & 7, (pApic->icr[0] & 0xff),
777 (pApic->icr[0] >> 14) & 1, (pApic->icr[0] >> 15) & 1);
778 APIC_UNLOCK(pDev);
779 break;
780
781 case 0x31:
782 if (!fMsr)
783 {
784 APIC_LOCK(pDev, rcBusy);
785 pApic->icr[1] = (uint64_t)u64Value;
786 APIC_UNLOCK(pDev);
787 }
788 else
789 rc = apicWriteRegisterInvalid(pDev, pApic, iReg, u64Value, rcBusy, fMsr);
790 break;
791
792 case 0x32 + APIC_LVT_TIMER:
793 AssertCompile(APIC_LVT_TIMER == 0);
794 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
795 apicTimerSetLvt(pDev, pApic, u64Value);
796 APIC_AND_TM_UNLOCK(pDev, pApic);
797 break;
798
799 case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
800 APIC_LOCK(pDev, rcBusy);
801 pApic->lvt[iReg - 0x32] = u64Value;
802 APIC_UNLOCK(pDev);
803 break;
804
805 case 0x38:
806 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
807 apicTimerSetInitialCount(pDev, pApic, u64Value);
808 APIC_AND_TM_UNLOCK(pDev, pApic);
809 break;
810
811 case 0x39:
812 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
813 break;
814
815 case 0x3e:
816 {
817 APIC_LOCK(pDev, rcBusy);
818 pApic->divide_conf = u64Value & 0xb;
819 int v = (pApic->divide_conf & 3) | ((pApic->divide_conf >> 1) & 4);
820 pApic->count_shift = (v + 1) & 7;
821 APIC_UNLOCK(pDev);
822 break;
823 }
824
825 case 0x3f:
826 if (fMsr)
827 {
828 /* Self IPI, see x2APIC book 2.4.5 */
829 APIC_LOCK(pDev, rcBusy);
830 int vector = u64Value & 0xff;
831 VMCPUSET SelfSet;
832 VMCPUSET_EMPTY(&SelfSet);
833 VMCPUSET_ADD(&SelfSet, pApic->id);
834 rc = apic_bus_deliver(pDev,
835 &SelfSet,
836 0 /* Delivery mode - fixed */,
837 vector,
838 0 /* Polarity - conform to the bus */,
839 0 /* Trigger mode - edge */,
840 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDev->CTX_SUFF(pDevIns), PDM_IRQ_LEVEL_HIGH));
841 APIC_UNLOCK(pDev);
842 break;
843 }
844 /* else: fall thru */
845
846 default:
847 rc = apicWriteRegisterInvalid(pDev, pApic, iReg, u64Value, rcBusy, fMsr);
848 break;
849 }
850
851 return rc;
852}
853
854
855/**
856 * apicReadRegister helper for dealing with invalid register access.
857 *
858 * @returns Strict VBox status code.
859 * @param pDev The PDM device instance.
860 * @param pApic The APIC being read to.
861 * @param iReg The APIC register index.
862 * @param pu64Value Where to store the value we've read.
863 * @param rcBusy The busy return code to employ. See
864 * PDMCritSectEnter for a description.
865 * @param fMsr Set if called via MSR, clear if MMIO.
866 */
867static int apicReadRegisterInvalid(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t *pu64Value,
868 int rcBusy, bool fMsr)
869{
870 Log(("apicReadRegisterInvalid/%u: iReg=%#x fMsr=%RTbool\n", pApic->phys_id, iReg, fMsr));
871 int rc = PDMDevHlpDBGFStop(pDev->CTX_SUFF(pDevIns), RT_SRC_POS,
872 "iReg=%#x fMsr=%RTbool id=%u\n", iReg, fMsr, pApic->phys_id);
873 APIC_LOCK(pDev, rcBusy);
874 pApic->esr |= ESR_ILLEGAL_ADDRESS;
875 APIC_UNLOCK(pDev);
876 *pu64Value = 0;
877 return rc;
878}
879
880
881/**
882 * Read from an APIC register via MMIO or MSR.
883 *
884 * @returns Strict VBox status code.
885 * @param pDev The PDM device instance.
886 * @param pApic The APIC being read to.
887 * @param iReg The APIC register index.
888 * @param pu64Value Where to store the value we've read.
889 * @param rcBusy The busy return code to employ. See
890 * PDMCritSectEnter for a description.
891 * @param fMsr Set if called via MSR, clear if MMIO.
892 */
893static int apicReadRegister(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t *pu64Value,
894 int rcBusy, bool fMsr)
895{
896 Assert(!PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
897
898 int rc = VINF_SUCCESS;
899 switch (iReg)
900 {
901 case 0x02: /* id */
902 APIC_LOCK(pDev, rcBusy);
903 *pu64Value = pApic->id << 24;
904 APIC_UNLOCK(pDev);
905 break;
906
907 case 0x03: /* version */
908 APIC_LOCK(pDev, rcBusy);
909 *pu64Value = APIC_HW_VERSION
910 | ((APIC_LVT_NB - 1) << 16) /* Max LVT index */
911#if 0
912 | (0 << 24) /* Support for EOI broadcast suppression */
913#endif
914 ;
915 APIC_UNLOCK(pDev);
916 break;
917
918 case 0x08:
919 APIC_LOCK(pDev, rcBusy);
920 *pu64Value = pApic->tpr;
921 APIC_UNLOCK(pDev);
922 break;
923
924 case 0x09:
925 *pu64Value = apic_get_arb_pri(pApic);
926 break;
927
928 case 0x0a:
929 /* ppr */
930 APIC_LOCK(pDev, rcBusy);
931 *pu64Value = apic_get_ppr(pApic);
932 APIC_UNLOCK(pDev);
933 break;
934
935 case 0x0b:
936 Log(("apicReadRegister: %x -> write only returning 0\n", iReg));
937 *pu64Value = 0;
938 break;
939
940 case 0x0d:
941 APIC_LOCK(pDev, rcBusy);
942 *pu64Value = (uint64_t)pApic->log_dest << 24;
943 APIC_UNLOCK(pDev);
944 break;
945
946 case 0x0e:
947 /* Bottom 28 bits are always 1 */
948 APIC_LOCK(pDev, rcBusy);
949 *pu64Value = ((uint64_t)pApic->dest_mode << 28) | UINT32_C(0xfffffff);
950 APIC_UNLOCK(pDev);
951 break;
952
953 case 0x0f:
954 APIC_LOCK(pDev, rcBusy);
955 *pu64Value = pApic->spurious_vec;
956 APIC_UNLOCK(pDev);
957 break;
958
959 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
960 APIC_LOCK(pDev, rcBusy);
961 *pu64Value = pApic->isr.au32Bitmap[iReg & 7];
962 APIC_UNLOCK(pDev);
963 break;
964
965 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
966 APIC_LOCK(pDev, rcBusy);
967 *pu64Value = pApic->tmr.au32Bitmap[iReg & 7];
968 APIC_UNLOCK(pDev);
969 break;
970
971 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
972 APIC_LOCK(pDev, rcBusy);
973 *pu64Value = pApic->irr.au32Bitmap[iReg & 7];
974 APIC_UNLOCK(pDev);
975 break;
976
977 case 0x28:
978 APIC_LOCK(pDev, rcBusy);
979 *pu64Value = pApic->esr;
980 APIC_UNLOCK(pDev);
981 break;
982
983 case 0x30:
984 /* Here one of the differences with regular APIC: ICR is single 64-bit register */
985 APIC_LOCK(pDev, rcBusy);
986 if (fMsr)
987 *pu64Value = RT_MAKE_U64(pApic->icr[0], pApic->icr[1]);
988 else
989 *pu64Value = pApic->icr[0];
990 APIC_UNLOCK(pDev);
991 break;
992
993 case 0x31:
994 if (fMsr)
995 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
996 else
997 {
998 APIC_LOCK(pDev, rcBusy);
999 *pu64Value = pApic->icr[1];
1000 APIC_UNLOCK(pDev);
1001 }
1002 break;
1003
1004 case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
1005 APIC_LOCK(pDev, rcBusy);
1006 *pu64Value = pApic->lvt[iReg - 0x32];
1007 APIC_UNLOCK(pDev);
1008 break;
1009
1010 case 0x38:
1011 APIC_LOCK(pDev, rcBusy);
1012 *pu64Value = pApic->initial_count;
1013 APIC_UNLOCK(pDev);
1014 break;
1015
1016 case 0x39:
1017 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
1018 *pu64Value = apic_get_current_count(pDev, pApic);
1019 APIC_AND_TM_UNLOCK(pDev, pApic);
1020 break;
1021
1022 case 0x3e:
1023 APIC_LOCK(pDev, rcBusy);
1024 *pu64Value = pApic->divide_conf;
1025 APIC_UNLOCK(pDev);
1026 break;
1027
1028 case 0x3f:
1029 if (fMsr)
1030 {
1031 /* Self IPI register is write only */
1032 Log(("apicReadMSR: read from write-only register %d ignored\n", iReg));
1033 *pu64Value = 0;
1034 }
1035 else
1036 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
1037 break;
1038 case 0x2f: /** @todo Correctable machine check exception vector, implement me! */
1039 default:
1040 /**
1041 * @todo: according to spec when APIC writes to ESR it msut raise error interrupt,
1042 * i.e. LVT[5]
1043 */
1044 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
1045 break;
1046 }
1047 return rc;
1048}
1049
1050/**
1051 * @interface_method_impl{PDMAPICREG,pfnWriteMSRR3}
1052 */
1053PDMBOTHCBDECL(int) apicWriteMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t u64Value)
1054{
1055 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1056 if (pDev->enmVersion < PDMAPICVERSION_X2APIC)
1057 return VERR_EM_INTERPRETER; /** @todo tell the caller to raise hell (\#GP(0)). */
1058
1059 APICState *pApic = apicGetStateById(pDev, idCpu);
1060 uint32_t iReg = (u32Reg - MSR_IA32_X2APIC_START) & 0xff;
1061 return apicWriteRegister(pDev, pApic, iReg, u64Value, VINF_SUCCESS /*rcBusy*/, true /*fMsr*/);
1062}
1063
1064
1065/**
1066 * @interface_method_impl{PDMAPICREG,pfnReadMSRR3}
1067 */
1068PDMBOTHCBDECL(int) apicReadMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t *pu64Value)
1069{
1070 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1071
1072 if (pDev->enmVersion < PDMAPICVERSION_X2APIC)
1073 return VERR_EM_INTERPRETER;
1074
1075 APICState *pApic = apicGetStateById(pDev, idCpu);
1076 uint32_t iReg = (u32Reg - MSR_IA32_X2APIC_START) & 0xff;
1077 return apicReadRegister(pDev, pApic, iReg, pu64Value, VINF_SUCCESS /*rcBusy*/, true /*fMsr*/);
1078}
1079
1080/**
1081 * More or less private interface between IOAPIC, only PDM is responsible
1082 * for connecting the two devices.
1083 */
1084PDMBOTHCBDECL(int) apicBusDeliverCallback(PPDMDEVINS pDevIns, uint8_t u8Dest, uint8_t u8DestMode,
1085 uint8_t u8DeliveryMode, uint8_t iVector, uint8_t u8Polarity,
1086 uint8_t u8TriggerMode, uint32_t uTagSrc)
1087{
1088 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1089 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1090 LogFlow(("apicBusDeliverCallback: pDevIns=%p u8Dest=%#x u8DestMode=%#x u8DeliveryMode=%#x iVector=%#x u8Polarity=%#x u8TriggerMode=%#x uTagSrc=%#x\n",
1091 pDevIns, u8Dest, u8DestMode, u8DeliveryMode, iVector, u8Polarity, u8TriggerMode, uTagSrc));
1092 VMCPUSET DstSet;
1093 return apic_bus_deliver(pDev, apic_get_delivery_bitmask(pDev, u8Dest, u8DestMode, &DstSet),
1094 u8DeliveryMode, iVector, u8Polarity, u8TriggerMode, uTagSrc);
1095}
1096
1097/**
1098 * Local interrupt delivery, for devices attached to the CPU's LINT0/LINT1 pin.
1099 * Normally used for 8259A PIC and NMI.
1100 */
1101PDMBOTHCBDECL(int) apicLocalInterrupt(PPDMDEVINS pDevIns, uint8_t u8Pin, uint8_t u8Level)
1102{
1103 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1104 APICState *pApic = apicGetStateById(pDev, 0);
1105
1106 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1107 LogFlow(("apicLocalInterrupt: pDevIns=%p u8Pin=%x u8Level=%x\n", pDevIns, u8Pin, u8Level));
1108
1109 /* If LAPIC is disabled, go straight to the CPU. */
1110 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1111 {
1112 LogFlow(("apicLocalInterrupt: LAPIC disabled, delivering directly to CPU core.\n"));
1113 if (u8Level)
1114 apicCpuSetInterrupt(pDev, pApic, PDMAPICIRQ_EXTINT);
1115 else
1116 apicCpuClearInterrupt(pDev, pApic, PDMAPICIRQ_EXTINT);
1117
1118 return VINF_SUCCESS;
1119 }
1120
1121 /* If LAPIC is enabled, interrupts are subject to LVT programming. */
1122
1123 /* There are only two local interrupt pins. */
1124 AssertMsgReturn(u8Pin <= 1, ("Invalid LAPIC pin %d\n", u8Pin), VERR_INVALID_PARAMETER);
1125
1126 /* NB: We currently only deliver local interrupts to the first CPU. In theory they
1127 * should be delivered to all CPUs and it is the guest's responsibility to ensure
1128 * no more than one CPU has the interrupt unmasked.
1129 */
1130 uint32_t u32Lvec;
1131
1132 u32Lvec = pApic->lvt[APIC_LVT_LINT0 + u8Pin]; /* Fetch corresponding LVT entry. */
1133 /* Drop int if entry is masked. May not be correct for level-triggered interrupts. */
1134 if (!(u32Lvec & APIC_LVT_MASKED))
1135 { uint8_t u8Delivery;
1136 PDMAPICIRQ enmType;
1137
1138 u8Delivery = (u32Lvec >> 8) & 7;
1139 switch (u8Delivery)
1140 {
1141 case APIC_DM_EXTINT:
1142 Assert(u8Pin == 0); /* PIC should be wired to LINT0. */
1143 enmType = PDMAPICIRQ_EXTINT;
1144 /* ExtINT can be both set and cleared, NMI/SMI/INIT can only be set. */
1145 LogFlow(("apicLocalInterrupt: %s ExtINT interrupt\n", u8Level ? "setting" : "clearing"));
1146 if (u8Level)
1147 apicCpuSetInterrupt(pDev, pApic, enmType);
1148 else
1149 apicCpuClearInterrupt(pDev, pApic, enmType);
1150 return VINF_SUCCESS;
1151 case APIC_DM_NMI:
1152 /* External NMI should be wired to LINT1, but Linux sometimes programs
1153 * LVT0 to NMI delivery mode as well.
1154 */
1155 enmType = PDMAPICIRQ_NMI;
1156 /* Currently delivering NMIs through here causes problems with NMI watchdogs
1157 * on certain Linux kernels, e.g. 64-bit CentOS 5.3. Disable NMIs for now.
1158 */
1159 return VINF_SUCCESS;
1160 case APIC_DM_SMI:
1161 enmType = PDMAPICIRQ_SMI;
1162 break;
1163 case APIC_DM_FIXED:
1164 {
1165 /** @todo implement APIC_DM_FIXED! */
1166 LogRelMax(5, ("APIC: Delivery type APIC_DM_FIXED not implemented. u8Pin=%d u8Level=%d\n", u8Pin, u8Level));
1167 return VINF_SUCCESS;
1168 }
1169 case APIC_DM_INIT:
1170 /** @todo implement APIC_DM_INIT? */
1171 default:
1172 {
1173 static unsigned s_c = 0;
1174 if (s_c++ < 100)
1175 AssertLogRelMsgFailed(("delivery type %d not implemented. u8Pin=%d u8Level=%d\n", u8Delivery, u8Pin, u8Level));
1176 return VERR_INTERNAL_ERROR_4;
1177 }
1178 }
1179 LogFlow(("apicLocalInterrupt: setting local interrupt type %d\n", enmType));
1180 apicCpuSetInterrupt(pDev, pApic, enmType);
1181 }
1182 return VINF_SUCCESS;
1183}
1184
1185static int apic_get_ppr(APICState const *pApic)
1186{
1187 int ppr;
1188
1189 int tpr = (pApic->tpr >> 4);
1190 int isrv = Apic256BitReg_FindLastSetBit(&pApic->isr, 0);
1191 isrv >>= 4;
1192 if (tpr >= isrv)
1193 ppr = pApic->tpr;
1194 else
1195 ppr = isrv << 4;
1196 return ppr;
1197}
1198
1199static int apic_get_ppr_zero_tpr(APICState *pApic)
1200{
1201 return Apic256BitReg_FindLastSetBit(&pApic->isr, 0);
1202}
1203
1204static int apic_get_arb_pri(APICState const *pApic)
1205{
1206 /** @todo XXX: arbitration */
1207 return 0;
1208}
1209
1210/* signal the CPU if an irq is pending */
1211static bool apic_update_irq(APICDeviceInfo *pDev, APICState *pApic)
1212{
1213 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1214 {
1215 /* Clear any pending APIC interrupt action flag. */
1216 apicCpuClearInterrupt(pDev, pApic);
1217 return false;
1218 }
1219
1220 int irrv = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1221 if (irrv < 0)
1222 return false;
1223 int ppr = apic_get_ppr(pApic);
1224 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
1225 return false;
1226 apicCpuSetInterrupt(pDev, pApic);
1227 return true;
1228}
1229
1230/* Check if the APIC has a pending interrupt/if a TPR change would active one. */
1231PDMBOTHCBDECL(bool) apicHasPendingIrq(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t *pu8PendingIrq)
1232{
1233 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1234 if (!pDev)
1235 return false;
1236
1237 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
1238
1239 APICState *pApic = apicGetStateById(pDev, idCpu);
1240
1241 /*
1242 * All our callbacks now come from single IOAPIC, thus locking
1243 * seems to be excessive now
1244 */
1245 /** @todo check excessive locking whatever... */
1246 int irrv = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1247 if (irrv < 0)
1248 return false;
1249
1250 int ppr = apic_get_ppr_zero_tpr(pApic);
1251
1252 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
1253 return false;
1254
1255 if (pu8PendingIrq)
1256 {
1257 Assert(irrv >= 0 && irrv <= (int)UINT8_MAX);
1258 *pu8PendingIrq = (uint8_t)irrv;
1259 }
1260 return true;
1261}
1262
1263static void apic_update_tpr(APICDeviceInfo *pDev, APICState *pApic, uint32_t val)
1264{
1265 bool fIrqIsActive = false;
1266 bool fIrqWasActive = false;
1267
1268 fIrqWasActive = apic_update_irq(pDev, pApic);
1269 pApic->tpr = val;
1270 fIrqIsActive = apic_update_irq(pDev, pApic);
1271
1272 /* If an interrupt is pending and now masked, then clear the FF flag. */
1273 if (fIrqWasActive && !fIrqIsActive)
1274 {
1275 Log(("apic_update_tpr: deactivate interrupt that was masked by the TPR update (%x)\n", val));
1276 STAM_COUNTER_INC(&pDev->StatClearedActiveIrq);
1277 apicCpuClearInterrupt(pDev, pApic);
1278 }
1279}
1280
1281static void apic_set_irq(APICDeviceInfo *pDev, APICState *pApic, int vector_num, int trigger_mode, uint32_t uTagSrc)
1282{
1283 LogFlow(("CPU%d: apic_set_irq vector=%x trigger_mode=%x uTagSrc=%#x\n", pApic->phys_id, vector_num, trigger_mode, uTagSrc));
1284
1285 Apic256BitReg_SetBit(&pApic->irr, vector_num);
1286 if (trigger_mode)
1287 Apic256BitReg_SetBit(&pApic->tmr, vector_num);
1288 else
1289 Apic256BitReg_ClearBit(&pApic->tmr, vector_num);
1290
1291 if (!pApic->auTags[vector_num])
1292 pApic->auTags[vector_num] = uTagSrc;
1293 else
1294 pApic->auTags[vector_num] |= RT_BIT_32(31);
1295
1296 apic_update_irq(pDev, pApic);
1297}
1298
1299static void apic_eoi(APICDeviceInfo *pDev, APICState *pApic)
1300{
1301 int isrv = Apic256BitReg_FindLastSetBit(&pApic->isr, -1);
1302 if (isrv < 0)
1303 return;
1304 Apic256BitReg_ClearBit(&pApic->isr, isrv);
1305 LogFlow(("CPU%d: apic_eoi isrv=%x\n", pApic->phys_id, isrv));
1306 /** @todo XXX: send the EOI packet to the APIC bus to allow the I/O APIC to
1307 * set the remote IRR bit for level triggered interrupts. */
1308 apic_update_irq(pDev, pApic);
1309}
1310
1311static PVMCPUSET apic_get_delivery_bitmask(APICDeviceInfo *pDev, uint8_t dest, uint8_t dest_mode, PVMCPUSET pDstSet)
1312{
1313 VMCPUSET_EMPTY(pDstSet);
1314
1315 if (dest_mode == 0)
1316 {
1317 if (dest == 0xff) /* The broadcast ID. */
1318 VMCPUSET_FILL(pDstSet);
1319 else
1320 VMCPUSET_ADD(pDstSet, dest);
1321 }
1322 else
1323 {
1324 /** @todo XXX: cluster mode */
1325 APIC_FOREACH_BEGIN(pDev);
1326 if (pCurApic->dest_mode == APIC_DESTMODE_FLAT)
1327 {
1328 if (dest & pCurApic->log_dest)
1329 VMCPUSET_ADD(pDstSet, iCurApic);
1330 }
1331 else if (pCurApic->dest_mode == APIC_DESTMODE_CLUSTER)
1332 {
1333 if ( (dest & 0xf0) == (pCurApic->log_dest & 0xf0)
1334 && (dest & pCurApic->log_dest & 0x0f))
1335 VMCPUSET_ADD(pDstSet, iCurApic);
1336 }
1337 APIC_FOREACH_END();
1338 }
1339
1340 return pDstSet;
1341}
1342
1343#ifdef IN_RING3
1344
1345static void apicR3InitIpi(APICDeviceInfo *pDev, APICState *pApic)
1346{
1347 int i;
1348
1349 for(i = 0; i < APIC_LVT_NB; i++)
1350 pApic->lvt[i] = 1 << 16; /* mask LVT */
1351 pApic->tpr = 0;
1352 pApic->spurious_vec = 0xff;
1353 pApic->log_dest = 0;
1354 pApic->dest_mode = 0xff; /** @todo 0xff???? */
1355 Apic256BitReg_Empty(&pApic->isr);
1356 Apic256BitReg_Empty(&pApic->tmr);
1357 Apic256BitReg_Empty(&pApic->irr);
1358 pApic->esr = 0;
1359 memset(pApic->icr, 0, sizeof(pApic->icr));
1360 pApic->divide_conf = 0;
1361 pApic->count_shift = 1;
1362 pApic->initial_count = 0;
1363 pApic->initial_count_load_time = 0;
1364 pApic->next_time = 0;
1365}
1366
1367
1368static void apicSendInitIpi(APICDeviceInfo *pDev, APICState *pApic)
1369{
1370 apicR3InitIpi(pDev, pApic);
1371 apicR3CpuSendInitIpi(pDev, pApic);
1372}
1373
1374/* send a SIPI message to the CPU to start it */
1375static void apicR3Startup(APICDeviceInfo *pDev, APICState *pApic, int vector_num)
1376{
1377 Log(("[SMP] apicR3Startup: %d on CPUs %d\n", vector_num, pApic->phys_id));
1378 apicR3CpuSendSipi(pDev, pApic, vector_num);
1379}
1380
1381#endif /* IN_RING3 */
1382
1383static int apic_deliver(APICDeviceInfo *pDev, APICState *pApic,
1384 uint8_t dest, uint8_t dest_mode,
1385 uint8_t delivery_mode, uint8_t vector_num,
1386 uint8_t polarity, uint8_t trigger_mode)
1387{
1388 int dest_shorthand = (pApic->icr[0] >> 18) & 3;
1389 LogFlow(("apic_deliver dest=%x dest_mode=%x dest_shorthand=%x delivery_mode=%x vector_num=%x polarity=%x trigger_mode=%x\n", dest, dest_mode, dest_shorthand, delivery_mode, vector_num, polarity, trigger_mode));
1390
1391 VMCPUSET DstSet;
1392 switch (dest_shorthand)
1393 {
1394 case 0:
1395 apic_get_delivery_bitmask(pDev, dest, dest_mode, &DstSet);
1396 break;
1397 case 1:
1398 VMCPUSET_EMPTY(&DstSet);
1399 VMCPUSET_ADD(&DstSet, pApic->id);
1400 break;
1401 case 2:
1402 VMCPUSET_FILL(&DstSet);
1403 break;
1404 case 3:
1405 VMCPUSET_FILL(&DstSet);
1406 VMCPUSET_DEL(&DstSet, pApic->id);
1407 break;
1408 }
1409
1410 switch (delivery_mode)
1411 {
1412 case APIC_DM_INIT:
1413 {
1414 uint32_t const trig_mode = (pApic->icr[0] >> 15) & 1;
1415 uint32_t const level = (pApic->icr[0] >> 14) & 1;
1416 if (level == 0 && trig_mode == 1)
1417 {
1418 APIC_FOREACH_IN_SET_BEGIN(pDev, &DstSet);
1419 pCurApic->arb_id = pCurApic->id;
1420 APIC_FOREACH_END();
1421 Log(("CPU%d: APIC_DM_INIT arbitration id(s) set\n", pApic->phys_id));
1422 return VINF_SUCCESS;
1423 }
1424 break;
1425 }
1426
1427 case APIC_DM_SIPI:
1428# ifdef IN_RING3
1429 APIC_FOREACH_IN_SET_BEGIN(pDev, &DstSet);
1430 apicR3Startup(pDev, pCurApic, vector_num);
1431 APIC_FOREACH_END();
1432 return VINF_SUCCESS;
1433# else
1434 /* We shall send SIPI only in R3, R0 calls should be
1435 rescheduled to R3 */
1436 return VINF_IOM_R3_MMIO_WRITE;
1437# endif
1438 }
1439
1440 return apic_bus_deliver(pDev, &DstSet, delivery_mode, vector_num,
1441 polarity, trigger_mode,
1442 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDev->CTX_SUFF(pDevIns), PDM_IRQ_LEVEL_HIGH));
1443}
1444
1445
1446PDMBOTHCBDECL(int) apicGetInterrupt(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t *puTagSrc)
1447{
1448 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1449 /* if the APIC is not installed or enabled, we let the 8259 handle the IRQs */
1450 if (!pDev)
1451 {
1452 Log(("apic_get_interrupt: returns -1 (!pDev)\n"));
1453 return -1;
1454 }
1455
1456 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1457
1458 APICState *pApic = apicGetStateById(pDev, idCpu);
1459
1460 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1461 {
1462 Log(("CPU%d: apic_get_interrupt: returns -1 (APIC_SV_ENABLE)\n", pApic->phys_id));
1463 return -1;
1464 }
1465
1466 /** @todo XXX: spurious IRQ handling */
1467 int intno = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1468 if (intno < 0)
1469 {
1470 Log(("CPU%d: apic_get_interrupt: returns -1 (irr)\n", pApic->phys_id));
1471 return -1;
1472 }
1473
1474 if (pApic->tpr && (uint32_t)intno <= pApic->tpr)
1475 {
1476 *puTagSrc = 0;
1477 Log(("apic_get_interrupt: returns %d (sp)\n", pApic->spurious_vec & 0xff));
1478 return pApic->spurious_vec & 0xff;
1479 }
1480
1481 Apic256BitReg_ClearBit(&pApic->irr, intno);
1482 Apic256BitReg_SetBit(&pApic->isr, intno);
1483
1484 *puTagSrc = pApic->auTags[intno];
1485 pApic->auTags[intno] = 0;
1486
1487 apic_update_irq(pDev, pApic);
1488
1489 LogFlow(("CPU%d: apic_get_interrupt: returns %d / %#x\n", pApic->phys_id, intno, *puTagSrc));
1490 return intno;
1491}
1492
1493/**
1494 * @remarks Caller (apicReadRegister) takes both the TM and APIC locks before
1495 * calling this function.
1496 */
1497static uint32_t apic_get_current_count(APICDeviceInfo const *pDev, APICState const *pApic)
1498{
1499 int64_t d = (TMTimerGet(pApic->CTX_SUFF(pTimer)) - pApic->initial_count_load_time)
1500 >> pApic->count_shift;
1501
1502 uint32_t val;
1503 if (pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC)
1504 /* periodic */
1505 val = pApic->initial_count - (d % ((uint64_t)pApic->initial_count + 1));
1506 else if (d >= pApic->initial_count)
1507 val = 0;
1508 else
1509 val = pApic->initial_count - d;
1510
1511 return val;
1512}
1513
1514/**
1515 * Does the frequency hinting and logging.
1516 *
1517 * @param pApic The device state.
1518 */
1519DECLINLINE(void) apicDoFrequencyHinting(APICState *pApic)
1520{
1521 if ( pApic->uHintedInitialCount != pApic->initial_count
1522 || pApic->uHintedCountShift != (uint32_t)pApic->count_shift)
1523 {
1524 pApic->uHintedInitialCount = pApic->initial_count;
1525 pApic->uHintedCountShift = pApic->count_shift;
1526
1527 uint32_t uHz;
1528 if (pApic->initial_count > 0)
1529 {
1530 Assert((unsigned)pApic->count_shift < 30);
1531 uint64_t cTickPerPeriod = ((uint64_t)pApic->initial_count + 1) << pApic->count_shift;
1532 uHz = TMTimerGetFreq(pApic->CTX_SUFF(pTimer)) / cTickPerPeriod;
1533 }
1534 else
1535 uHz = 0;
1536 TMTimerSetFrequencyHint(pApic->CTX_SUFF(pTimer), uHz);
1537 Log(("apic: %u Hz\n", uHz));
1538 }
1539}
1540
1541/**
1542 * Implementation of the 0380h access: Timer reset + new initial count.
1543 *
1544 * @param pDev The device state.
1545 * @param pApic The APIC sub-device state.
1546 * @param u32NewInitialCount The new initial count for the timer.
1547 */
1548static void apicTimerSetInitialCount(APICDeviceInfo *pDev, APICState *pApic, uint32_t u32NewInitialCount)
1549{
1550 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCount);
1551 pApic->initial_count = u32NewInitialCount;
1552
1553 /*
1554 * Don't (re-)arm the timer if the it's masked or if it's
1555 * a zero length one-shot timer.
1556 */
1557 if ( !(pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)
1558 && u32NewInitialCount > 0)
1559 {
1560 /*
1561 * Calculate the relative next time and perform a combined timer get/set
1562 * operation. This avoids racing the clock between get and set.
1563 */
1564 uint64_t cTicksNext = u32NewInitialCount;
1565 cTicksNext += 1;
1566 cTicksNext <<= pApic->count_shift;
1567 TMTimerSetRelative(pApic->CTX_SUFF(pTimer), cTicksNext, &pApic->initial_count_load_time);
1568 pApic->next_time = pApic->initial_count_load_time + cTicksNext;
1569 pApic->fTimerArmed = true;
1570 apicDoFrequencyHinting(pApic);
1571 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCountArm);
1572 Log(("apicTimerSetInitialCount: cTicksNext=%'llu (%#llx) ic=%#x sh=%#x nxt=%#llx\n",
1573 cTicksNext, cTicksNext, u32NewInitialCount, pApic->count_shift, pApic->next_time));
1574 }
1575 else
1576 {
1577 /* Stop it if necessary and record the load time for unmasking. */
1578 if (pApic->fTimerArmed)
1579 {
1580 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCountDisarm);
1581 TMTimerStop(pApic->CTX_SUFF(pTimer));
1582 pApic->fTimerArmed = false;
1583 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1584 }
1585 pApic->initial_count_load_time = TMTimerGet(pApic->CTX_SUFF(pTimer));
1586 Log(("apicTimerSetInitialCount: ic=%#x sh=%#x iclt=%#llx\n", u32NewInitialCount, pApic->count_shift, pApic->initial_count_load_time));
1587 }
1588}
1589
1590/**
1591 * Implementation of the 0320h access: change the LVT flags.
1592 *
1593 * @param pDev The device state.
1594 * @param pApic The APIC sub-device state to operate on.
1595 * @param fNew The new flags.
1596 */
1597static void apicTimerSetLvt(APICDeviceInfo *pDev, APICState *pApic, uint32_t fNew)
1598{
1599 STAM_COUNTER_INC(&pApic->StatTimerSetLvt);
1600
1601 /*
1602 * Make the flag change, saving the old ones so we can avoid
1603 * unnecessary work.
1604 */
1605 uint32_t const fOld = pApic->lvt[APIC_LVT_TIMER];
1606 pApic->lvt[APIC_LVT_TIMER] = fNew;
1607
1608 /* Only the masked and peridic bits are relevant (see apic_timer_update). */
1609 if ( (fOld & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC))
1610 != (fNew & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC)))
1611 {
1612 /*
1613 * If changed to one-shot from periodic, stop the timer if we're not
1614 * in the first period.
1615 */
1616 /** @todo check how clearing the periodic flag really should behave when not
1617 * in period 1. The current code just mirrors the behavior of the
1618 * original implementation. */
1619 if ( (fOld & APIC_LVT_TIMER_PERIODIC)
1620 && !(fNew & APIC_LVT_TIMER_PERIODIC))
1621 {
1622 STAM_COUNTER_INC(&pApic->StatTimerSetLvtClearPeriodic);
1623 uint64_t cTicks = (pApic->next_time - pApic->initial_count_load_time) >> pApic->count_shift;
1624 if (cTicks >= pApic->initial_count)
1625 {
1626 /* not first period, stop it. */
1627 TMTimerStop(pApic->CTX_SUFF(pTimer));
1628 pApic->fTimerArmed = false;
1629 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1630 }
1631 /* else: first period, let it fire normally. */
1632 }
1633
1634 /*
1635 * We postpone stopping the timer when it's masked, this way we can
1636 * avoid some timer work when the guest temporarily masks the timer.
1637 * (apicR3TimerCallback will stop it if still masked.)
1638 */
1639 if (fNew & APIC_LVT_MASKED)
1640 STAM_COUNTER_INC(&pApic->StatTimerSetLvtPostponed);
1641 else if (pApic->fTimerArmed)
1642 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArmed);
1643 /*
1644 * If unmasked, not armed and with a valid initial count value (according
1645 * to our interpretation of the spec), we will have to rearm the timer so
1646 * it will fire at the end of the current period.
1647 *
1648 * N.B. This is code is currently RACING the virtual sync clock!
1649 */
1650 else if ( (fOld & APIC_LVT_MASKED)
1651 && pApic->initial_count > 0)
1652 {
1653 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArm);
1654 for (unsigned cTries = 0; ; cTries++)
1655 {
1656 uint64_t NextTS;
1657 uint64_t cTicks = (TMTimerGet(pApic->CTX_SUFF(pTimer)) - pApic->initial_count_load_time) >> pApic->count_shift;
1658 if (fNew & APIC_LVT_TIMER_PERIODIC)
1659 NextTS = ((cTicks / ((uint64_t)pApic->initial_count + 1)) + 1) * ((uint64_t)pApic->initial_count + 1);
1660 else
1661 {
1662 if (cTicks >= pApic->initial_count)
1663 break;
1664 NextTS = (uint64_t)pApic->initial_count + 1;
1665 }
1666 NextTS <<= pApic->count_shift;
1667 NextTS += pApic->initial_count_load_time;
1668
1669 /* Try avoid the assertion in TM.cpp... this isn't perfect! */
1670 if ( NextTS > TMTimerGet(pApic->CTX_SUFF(pTimer))
1671 || cTries > 10)
1672 {
1673 TMTimerSet(pApic->CTX_SUFF(pTimer), NextTS);
1674 pApic->next_time = NextTS;
1675 pApic->fTimerArmed = true;
1676 apicDoFrequencyHinting(pApic);
1677 Log(("apicTimerSetLvt: ic=%#x sh=%#x nxt=%#llx\n", pApic->initial_count, pApic->count_shift, pApic->next_time));
1678 break;
1679 }
1680 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArmRetries);
1681 }
1682 }
1683 }
1684 else
1685 STAM_COUNTER_INC(&pApic->StatTimerSetLvtNoRelevantChange);
1686}
1687
1688# ifdef IN_RING3
1689
1690/**
1691 * Timer callback function.
1692 *
1693 * @param pDevIns The device state.
1694 * @param pTimer The timer handle.
1695 * @param pvUser User argument pointing to the APIC instance.
1696 */
1697static DECLCALLBACK(void) apicR3TimerCallback(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
1698{
1699 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1700 APICState *pApic = (APICState *)pvUser;
1701 Assert(pApic->pTimerR3 == pTimer);
1702 Assert(pApic->fTimerArmed);
1703 Assert(PDMCritSectIsOwner(pDev->pCritSectR3));
1704 Assert(TMTimerIsLockOwner(pTimer));
1705
1706 if (!(pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)) {
1707 LogFlow(("apic_timer: trigger irq\n"));
1708 apic_set_irq(pDev, pApic, pApic->lvt[APIC_LVT_TIMER] & 0xff, APIC_TRIGGER_EDGE,
1709 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDevIns, PDM_IRQ_LEVEL_HIGH));
1710
1711 if ( (pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC)
1712 && pApic->initial_count > 0) {
1713 /* new interval. */
1714 pApic->next_time += (((uint64_t)pApic->initial_count + 1) << pApic->count_shift);
1715 TMTimerSet(pApic->CTX_SUFF(pTimer), pApic->next_time);
1716 pApic->fTimerArmed = true;
1717 apicDoFrequencyHinting(pApic);
1718 Log2(("apicR3TimerCallback: ic=%#x sh=%#x nxt=%#llx\n", pApic->initial_count, pApic->count_shift, pApic->next_time));
1719 } else {
1720 /* single shot or disabled. */
1721 pApic->fTimerArmed = false;
1722 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1723 }
1724 } else {
1725 /* masked, do not rearm. */
1726 pApic->fTimerArmed = false;
1727 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1728 }
1729}
1730
1731static void apic_save(SSMHANDLE* f, void *opaque)
1732{
1733 APICState *pApic = (APICState*)opaque;
1734 int i;
1735
1736 SSMR3PutU32(f, pApic->apicbase);
1737 SSMR3PutU32(f, pApic->id);
1738 SSMR3PutU32(f, pApic->phys_id);
1739 SSMR3PutU32(f, pApic->arb_id);
1740 SSMR3PutU32(f, pApic->tpr);
1741 SSMR3PutU32(f, pApic->spurious_vec);
1742 SSMR3PutU8(f, pApic->log_dest);
1743 SSMR3PutU8(f, pApic->dest_mode);
1744 for (i = 0; i < 8; i++) {
1745 SSMR3PutU32(f, pApic->isr.au32Bitmap[i]);
1746 SSMR3PutU32(f, pApic->tmr.au32Bitmap[i]);
1747 SSMR3PutU32(f, pApic->irr.au32Bitmap[i]);
1748 }
1749 for (i = 0; i < APIC_LVT_NB; i++) {
1750 SSMR3PutU32(f, pApic->lvt[i]);
1751 }
1752 SSMR3PutU32(f, pApic->esr);
1753 SSMR3PutU32(f, pApic->icr[0]);
1754 SSMR3PutU32(f, pApic->icr[1]);
1755 SSMR3PutU32(f, pApic->divide_conf);
1756 SSMR3PutU32(f, pApic->count_shift);
1757 SSMR3PutU32(f, pApic->initial_count);
1758 SSMR3PutU64(f, pApic->initial_count_load_time);
1759 SSMR3PutU64(f, pApic->next_time);
1760
1761 TMR3TimerSave(pApic->CTX_SUFF(pTimer), f);
1762}
1763
1764static int apic_load(SSMHANDLE *f, void *opaque, int version_id)
1765{
1766 APICState *pApic = (APICState*)opaque;
1767 int i;
1768
1769 /** @todo XXX: what if the base changes? (registered memory regions) */
1770 SSMR3GetU32(f, &pApic->apicbase);
1771
1772 switch (version_id)
1773 {
1774 case APIC_SAVED_STATE_VERSION_ANCIENT:
1775 {
1776 uint8_t val = 0;
1777 SSMR3GetU8(f, &val);
1778 pApic->id = val;
1779 /* UP only in old saved states */
1780 pApic->phys_id = 0;
1781 SSMR3GetU8(f, &val);
1782 pApic->arb_id = val;
1783 break;
1784 }
1785 case APIC_SAVED_STATE_VERSION:
1786 case APIC_SAVED_STATE_VERSION_VBOX_30:
1787 SSMR3GetU32(f, &pApic->id);
1788 SSMR3GetU32(f, &pApic->phys_id);
1789 SSMR3GetU32(f, &pApic->arb_id);
1790 break;
1791 default:
1792 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1793 }
1794 SSMR3GetU32(f, &pApic->tpr);
1795 SSMR3GetU32(f, &pApic->spurious_vec);
1796 SSMR3GetU8(f, &pApic->log_dest);
1797 SSMR3GetU8(f, &pApic->dest_mode);
1798 for (i = 0; i < 8; i++) {
1799 SSMR3GetU32(f, &pApic->isr.au32Bitmap[i]);
1800 SSMR3GetU32(f, &pApic->tmr.au32Bitmap[i]);
1801 SSMR3GetU32(f, &pApic->irr.au32Bitmap[i]);
1802 }
1803 for (i = 0; i < APIC_LVT_NB; i++) {
1804 SSMR3GetU32(f, &pApic->lvt[i]);
1805 }
1806 SSMR3GetU32(f, &pApic->esr);
1807 SSMR3GetU32(f, &pApic->icr[0]);
1808 SSMR3GetU32(f, &pApic->icr[1]);
1809 SSMR3GetU32(f, &pApic->divide_conf);
1810 SSMR3GetU32(f, (uint32_t *)&pApic->count_shift);
1811 SSMR3GetU32(f, (uint32_t *)&pApic->initial_count);
1812 SSMR3GetU64(f, (uint64_t *)&pApic->initial_count_load_time);
1813 SSMR3GetU64(f, (uint64_t *)&pApic->next_time);
1814
1815 int rc = TMR3TimerLoad(pApic->CTX_SUFF(pTimer), f);
1816 AssertRCReturn(rc, rc);
1817 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1818 pApic->fTimerArmed = TMTimerIsActive(pApic->CTX_SUFF(pTimer));
1819 if (pApic->fTimerArmed)
1820 apicDoFrequencyHinting(pApic);
1821
1822 return VINF_SUCCESS; /** @todo darn mess! */
1823}
1824
1825#endif /* IN_RING3 */
1826
1827/* LAPIC */
1828PDMBOTHCBDECL(int) apicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
1829{
1830 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1831 APICState *pApic = apicGetStateByCurEmt(pDev);
1832
1833 Log(("CPU%d: apicMMIORead at %RGp\n", pApic->phys_id, GCPhysAddr));
1834 Assert(cb == 4);
1835
1836 /** @todo add LAPIC range validity checks (different LAPICs can
1837 * theoretically have different physical addresses, see @bugref{3092}) */
1838
1839 STAM_COUNTER_INC(&CTXSUFF(pDev->StatMMIORead));
1840#if 0 /* Note! experimental */
1841#ifndef IN_RING3
1842 uint32_t index = (GCPhysAddr >> 4) & 0xff;
1843
1844 if ( index == 0x08 /* TPR */
1845 && ++pApic->cTPRPatchAttempts < APIC_MAX_PATCH_ATTEMPTS)
1846 {
1847# ifdef IN_RC
1848 pDevIns->pDevHlpGC->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, &pApic->tpr);
1849# else
1850 RTGCPTR pDevInsGC = PDMINS2DATA_GCPTR(pDevIns);
1851 pDevIns->pHlpR0->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, pDevIns + RT_OFFSETOF(APICState, tpr));
1852# endif
1853 return VINF_PATM_HC_MMIO_PATCH_READ;
1854 }
1855#endif
1856#endif /* experimental */
1857
1858 /* Note! apicReadRegister does its own locking. */
1859 uint64_t u64Value = 0;
1860 int rc = apicReadRegister(pDev, pApic, (GCPhysAddr >> 4) & 0xff, &u64Value, VINF_IOM_R3_MMIO_READ, false /*fMsr*/);
1861 *(uint32_t *)pv = (uint32_t)u64Value;
1862 return rc;
1863}
1864
1865PDMBOTHCBDECL(int) apicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void const *pv, unsigned cb)
1866{
1867 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1868 APICState *pApic = apicGetStateByCurEmt(pDev);
1869
1870 Log(("CPU%d: apicMMIOWrite at %RGp\n", pApic->phys_id, GCPhysAddr));
1871 Assert(cb == 4);
1872
1873 /** @todo add LAPIC range validity checks (multiple LAPICs can theoretically
1874 * have different physical addresses, see @bugref{3092}) */
1875
1876 STAM_COUNTER_INC(&CTXSUFF(pDev->StatMMIOWrite));
1877 /* Note! It does its own locking. */
1878 return apicWriteRegister(pDev, pApic, (GCPhysAddr >> 4) & 0xff, *(uint32_t const *)pv,
1879 VINF_IOM_R3_MMIO_WRITE, false /*fMsr*/);
1880}
1881
1882#ifdef IN_RING3
1883
1884/**
1885 * Wrapper around apicReadRegister.
1886 *
1887 * @returns 64-bit register value.
1888 * @param pDev The PDM device instance.
1889 * @param pApic The Local APIC in question.
1890 * @param iReg The APIC register index.
1891 */
1892static uint64_t apicR3InfoReadReg(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg)
1893{
1894 uint64_t u64Value;
1895 int rc = apicReadRegister(pDev, pApic, iReg, &u64Value, VINF_SUCCESS, true /*fMsr*/);
1896 AssertRCReturn(rc, UINT64_MAX);
1897 return u64Value;
1898}
1899
1900/**
1901 * Print an 8-DWORD Local APIC bit map (256 bits).
1902 *
1903 * @param pDev The PDM device instance.
1904 * @param pApic The Local APIC in question.
1905 * @param pHlp The output helper.
1906 * @param iStartReg The register to start at.
1907 */
1908static void apicR3DumpVec(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp, uint32_t iStartReg)
1909{
1910 for (int i = 7; i >= 0; --i)
1911 pHlp->pfnPrintf(pHlp, "%08x", apicR3InfoReadReg(pDev, pApic, iStartReg + i));
1912 pHlp->pfnPrintf(pHlp, "\n");
1913}
1914
1915/**
1916 * Print the set of pending interrupts in a 256-bit map.
1917 *
1918 * @param pDev The PDM device instance.
1919 * @param pApic The Local APIC in question.
1920 * @param pHlp The output helper.
1921 * @param iStartReg The register to start at.
1922 */
1923static void apicR3DumpPending(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp, PCAPIC256BITREG pReg)
1924{
1925 APIC256BITREG pending;
1926 int iMax;
1927 int cPending = 0;
1928
1929 pending = *pReg;
1930 pHlp->pfnPrintf(pHlp, " pending =");
1931
1932 while ((iMax = Apic256BitReg_FindLastSetBit(&pending, -1)) != -1)
1933 {
1934 pHlp->pfnPrintf(pHlp, " %02x", iMax);
1935 Apic256BitReg_ClearBit(&pending, iMax);
1936 ++cPending;
1937 }
1938 if (!cPending)
1939 pHlp->pfnPrintf(pHlp, " none");
1940 pHlp->pfnPrintf(pHlp, "\n");
1941}
1942
1943/**
1944 * Print basic Local APIC state.
1945 *
1946 * @param pDev The PDM device instance.
1947 * @param pApic The Local APIC in question.
1948 * @param pHlp The output helper.
1949 */
1950static void apicR3InfoBasic(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
1951{
1952 uint64_t u64;
1953
1954 pHlp->pfnPrintf(pHlp, "Local APIC at %08llx:\n", pApic->apicbase);
1955 u64 = apicR3InfoReadReg(pDev, pApic, 0x2);
1956 pHlp->pfnPrintf(pHlp, " LAPIC ID : %08llx\n", u64);
1957 pHlp->pfnPrintf(pHlp, " APIC ID = %02llx\n", (u64 >> 24) & 0xff);
1958 u64 = apicR3InfoReadReg(pDev, pApic, 0x3);
1959 pHlp->pfnPrintf(pHlp, " APIC VER : %08llx\n", u64);
1960 pHlp->pfnPrintf(pHlp, " version = %02x\n", (int)RT_BYTE1(u64));
1961 pHlp->pfnPrintf(pHlp, " lvts = %d\n", (int)RT_BYTE3(u64) + 1);
1962 u64 = apicR3InfoReadReg(pDev, pApic, 0x8);
1963 pHlp->pfnPrintf(pHlp, " TPR : %08llx\n", u64);
1964 pHlp->pfnPrintf(pHlp, " task pri = %lld/%lld\n", (u64 >> 4) & 0xf, u64 & 0xf);
1965 u64 = apicR3InfoReadReg(pDev, pApic, 0xA);
1966 pHlp->pfnPrintf(pHlp, " PPR : %08llx\n", u64);
1967 pHlp->pfnPrintf(pHlp, " cpu pri = %lld/%lld\n", (u64 >> 4) & 0xf, u64 & 0xf);
1968 u64 = apicR3InfoReadReg(pDev, pApic, 0xD);
1969 pHlp->pfnPrintf(pHlp, " LDR : %08llx\n", u64);
1970 pHlp->pfnPrintf(pHlp, " log id = %02llx\n", (u64 >> 24) & 0xff);
1971 pHlp->pfnPrintf(pHlp, " DFR : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0xE));
1972 u64 = apicR3InfoReadReg(pDev, pApic, 0xF);
1973 pHlp->pfnPrintf(pHlp, " SVR : %08llx\n", u64);
1974 pHlp->pfnPrintf(pHlp, " focus = %s\n", u64 & RT_BIT(9) ? "check off" : "check on");
1975 pHlp->pfnPrintf(pHlp, " lapic = %s\n", u64 & RT_BIT(8) ? "ENABLED" : "DISABLED");
1976 pHlp->pfnPrintf(pHlp, " vector = %02x\n", (unsigned)RT_BYTE1(u64));
1977 pHlp->pfnPrintf(pHlp, " ISR : ");
1978 apicR3DumpVec(pDev, pApic, pHlp, 0x10);
1979 apicR3DumpPending(pDev, pApic, pHlp, &pApic->isr);
1980 pHlp->pfnPrintf(pHlp, " IRR : ");
1981 apicR3DumpVec(pDev, pApic, pHlp, 0x20);
1982 apicR3DumpPending(pDev, pApic, pHlp, &pApic->irr);
1983}
1984
1985
1986/**
1987 * Print the more interesting Local APIC LVT entries.
1988 *
1989 * @param pDev The PDM device instance.
1990 * @param pApic The Local APIC in question.
1991 * @param pHlp The output helper.
1992 */
1993static void apicR3InfoLVT(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
1994{
1995 static const char * const s_apszDeliveryModes[] =
1996 {
1997 "Fixed ", "Reserved", "SMI", "Reserved", "NMI", "INIT", "Reserved", "ExtINT"
1998 };
1999 uint64_t u64;
2000
2001 u64 = apicR3InfoReadReg(pDev, pApic, 0x32);
2002 pHlp->pfnPrintf(pHlp, " LVT Timer : %08llx\n", u64);
2003 pHlp->pfnPrintf(pHlp, " mode = %s\n", u64 & RT_BIT(17) ? "periodic" : "one-shot");
2004 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
2005 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
2006 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
2007 u64 = apicR3InfoReadReg(pDev, pApic, 0x35);
2008 pHlp->pfnPrintf(pHlp, " LVT LINT0 : %08llx\n", u64);
2009 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
2010 pHlp->pfnPrintf(pHlp, " trigger = %s\n", u64 & RT_BIT(15) ? "level" : "edge");
2011 pHlp->pfnPrintf(pHlp, " rem irr = %llu\n", (u64 >> 14) & 1);
2012 pHlp->pfnPrintf(pHlp, " polarty = %llu\n", (u64 >> 13) & 1);
2013 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
2014 pHlp->pfnPrintf(pHlp, " delivry = %s\n", s_apszDeliveryModes[(u64 >> 8) & 7]);
2015 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
2016 u64 = apicR3InfoReadReg(pDev, pApic, 0x36);
2017 pHlp->pfnPrintf(pHlp, " LVT LINT1 : %08llx\n", u64);
2018 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
2019 pHlp->pfnPrintf(pHlp, " trigger = %s\n", u64 & RT_BIT(15) ? "level" : "edge");
2020 pHlp->pfnPrintf(pHlp, " rem irr = %lld\n", (u64 >> 14) & 1);
2021 pHlp->pfnPrintf(pHlp, " polarty = %lld\n", (u64 >> 13) & 1);
2022 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
2023 pHlp->pfnPrintf(pHlp, " delivry = %s\n", s_apszDeliveryModes[(u64 >> 8) & 7]);
2024 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
2025}
2026
2027
2028/**
2029 * Print LAPIC timer state.
2030 *
2031 * @param pDev The PDM device instance.
2032 * @param pApic The Local APIC in question.
2033 * @param pHlp The output helper.
2034 */
2035static void apicR3InfoTimer(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
2036{
2037 pHlp->pfnPrintf(pHlp, "Local APIC timer:\n");
2038 pHlp->pfnPrintf(pHlp, " Initial count : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0x38));
2039 pHlp->pfnPrintf(pHlp, " Current count : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0x39));
2040 uint64_t u64 = apicR3InfoReadReg(pDev, pApic, 0x3e);
2041 pHlp->pfnPrintf(pHlp, " Divide config : %08llx\n", u64);
2042 unsigned uDivider = ((u64 >> 1) & 0x04) | (u64 & 0x03);
2043 pHlp->pfnPrintf(pHlp, " divider = %u\n", uDivider == 7 ? 1 : 2 << uDivider);
2044}
2045
2046
2047/**
2048 * @callback_method_impl{FNDBGFHANDLERDEV,
2049 * Dumps the Local APIC state according to given argument.}
2050 */
2051static DECLCALLBACK(void) apicR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
2052{
2053 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2054 APICState *pApic = apicGetStateByCurEmt(pDev);
2055
2056 if (pszArgs == NULL || !*pszArgs || !strcmp(pszArgs, "basic"))
2057 apicR3InfoBasic(pDev, pApic, pHlp);
2058 else if (!strcmp(pszArgs, "lvt"))
2059 apicR3InfoLVT(pDev, pApic, pHlp);
2060 else if (!strcmp(pszArgs, "timer"))
2061 apicR3InfoTimer(pDev, pApic, pHlp);
2062 else
2063 pHlp->pfnPrintf(pHlp, "Invalid argument. Recognized arguments are 'basic', 'lvt', 'timer'.\n");
2064}
2065
2066
2067/**
2068 * @copydoc FNSSMDEVLIVEEXEC
2069 */
2070static DECLCALLBACK(int) apicR3LiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass)
2071{
2072 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2073
2074 SSMR3PutU32( pSSM, pDev->cCpus);
2075 SSMR3PutBool(pSSM, pDev->fIoApic);
2076 SSMR3PutU32( pSSM, pDev->enmVersion);
2077 AssertCompile(PDMAPICVERSION_APIC == 2);
2078
2079 return VINF_SSM_DONT_CALL_AGAIN;
2080}
2081
2082
2083/**
2084 * @copydoc FNSSMDEVSAVEEXEC
2085 */
2086static DECLCALLBACK(int) apicR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2087{
2088 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2089
2090 /* config */
2091 apicR3LiveExec(pDevIns, pSSM, SSM_PASS_FINAL);
2092
2093 /* save all APICs data */ /** @todo is it correct? */
2094 APIC_FOREACH_BEGIN(pDev);
2095 apic_save(pSSM, pCurApic);
2096 APIC_FOREACH_END();
2097
2098 return VINF_SUCCESS;
2099}
2100
2101/**
2102 * @copydoc FNSSMDEVLOADEXEC
2103 */
2104static DECLCALLBACK(int) apicR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
2105{
2106 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2107
2108 if ( uVersion != APIC_SAVED_STATE_VERSION
2109 && uVersion != APIC_SAVED_STATE_VERSION_VBOX_30
2110 && uVersion != APIC_SAVED_STATE_VERSION_ANCIENT)
2111 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
2112
2113 /* config */
2114 if (uVersion > APIC_SAVED_STATE_VERSION_VBOX_30)
2115 {
2116 uint32_t cCpus;
2117 int rc = SSMR3GetU32(pSSM, &cCpus); AssertRCReturn(rc, rc);
2118 if (cCpus != pDev->cCpus)
2119 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - cCpus: saved=%#x config=%#x"), cCpus, pDev->cCpus);
2120
2121 bool fIoApic;
2122 rc = SSMR3GetBool(pSSM, &fIoApic); AssertRCReturn(rc, rc);
2123 if (fIoApic != pDev->fIoApic)
2124 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - fIoApic: saved=%RTbool config=%RTbool"), fIoApic, pDev->fIoApic);
2125
2126 uint32_t uApicVersion;
2127 rc = SSMR3GetU32(pSSM, &uApicVersion); AssertRCReturn(rc, rc);
2128 if (uApicVersion != (uint32_t)pDev->enmVersion)
2129 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - uApicVersion: saved=%#x config=%#x"), uApicVersion, pDev->enmVersion);
2130 }
2131
2132 if (uPass != SSM_PASS_FINAL)
2133 return VINF_SUCCESS;
2134
2135 /* load all APICs data */ /** @todo is it correct? */
2136 APIC_LOCK(pDev, VERR_INTERNAL_ERROR_3);
2137
2138 int rc = VINF_SUCCESS;
2139 APIC_FOREACH_BEGIN(pDev);
2140 rc = apic_load(pSSM, pCurApic, uVersion);
2141 if (RT_FAILURE(rc))
2142 break;
2143 APIC_FOREACH_END();
2144
2145 APIC_UNLOCK(pDev);
2146 return rc;
2147}
2148
2149/**
2150 * @copydoc FNPDMDEVRESET
2151 */
2152static DECLCALLBACK(void) apicR3Reset(PPDMDEVINS pDevIns)
2153{
2154 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2155 TMTimerLock(pDev->paLapicsR3[0].pTimerR3, VERR_IGNORED);
2156 APIC_LOCK_VOID(pDev, VERR_IGNORED);
2157
2158 /* Reset all APICs. */
2159 for (VMCPUID i = 0; i < pDev->cCpus; i++)
2160 {
2161 APICState *pApic = &pDev->CTX_SUFF(paLapics)[i];
2162 TMTimerStop(pApic->CTX_SUFF(pTimer));
2163
2164 /* Clear LAPIC state as if an INIT IPI was sent. */
2165 apicR3InitIpi(pDev, pApic);
2166
2167 /* The IDs are not touched by apicR3InitIpi() and must be reset now. */
2168 pApic->arb_id = pApic->id = i;
2169 Assert(pApic->id == pApic->phys_id); /* The two should match again. */
2170
2171 /* Reset should re-enable the APIC, see comment in msi.h */
2172 pApic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2173 if (pApic->phys_id == 0)
2174 pApic->apicbase |= MSR_IA32_APICBASE_BSP;
2175
2176 /* Clear any pending APIC interrupt action flag. */
2177 apicCpuClearInterrupt(pDev, pApic);
2178 }
2179
2180 LogRel(("APIC: Re-activating Local APIC\n"));
2181 pDev->pApicHlpR3->pfnChangeFeature(pDev->pDevInsR3, pDev->enmVersion);
2182
2183 APIC_UNLOCK(pDev);
2184 TMTimerUnlock(pDev->paLapicsR3[0].pTimerR3);
2185}
2186
2187
2188/**
2189 * @copydoc FNPDMDEVRELOCATE
2190 */
2191static DECLCALLBACK(void) apicR3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
2192{
2193 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2194 pDev->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2195 pDev->pApicHlpRC = pDev->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2196 pDev->paLapicsRC = MMHyperR3ToRC(PDMDevHlpGetVM(pDevIns), pDev->paLapicsR3);
2197 pDev->pCritSectRC = pDev->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2198 for (uint32_t i = 0; i < pDev->cCpus; i++)
2199 pDev->paLapicsR3[i].pTimerRC = TMTimerRCPtr(pDev->paLapicsR3[i].pTimerR3);
2200}
2201
2202
2203/**
2204 * Initializes the state of one local APIC.
2205 *
2206 * @param pApic The Local APIC state to init.
2207 * @param id The Local APIC ID.
2208 */
2209static void apicR3StateInit(APICState *pApic, uint8_t id)
2210{
2211 memset(pApic, 0, sizeof(*pApic));
2212
2213 /* See comment in msi.h for LAPIC base info. */
2214 pApic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2215 if (id == 0) /* Mark first CPU as BSP. */
2216 pApic->apicbase |= MSR_IA32_APICBASE_BSP;
2217
2218 for (int i = 0; i < APIC_LVT_NB; i++)
2219 pApic->lvt[i] = RT_BIT_32(16); /* mask LVT */
2220
2221 pApic->spurious_vec = 0xff;
2222 pApic->phys_id = id;
2223 pApic->id = id;
2224}
2225
2226
2227/**
2228 * @copydoc FNPDMDEVCONSTRUCT
2229 */
2230static DECLCALLBACK(int) apicR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2231{
2232 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2233 uint32_t i;
2234
2235 /*
2236 * Only single device instance.
2237 */
2238 Assert(iInstance == 0);
2239
2240 /*
2241 * Validate configuration.
2242 */
2243 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "IOAPIC|RZEnabled|NumCPUs", "");
2244
2245 bool fIoApic;
2246 int rc = CFGMR3QueryBoolDef(pCfg, "IOAPIC", &fIoApic, true);
2247 if (RT_FAILURE(rc))
2248 return PDMDEV_SET_ERROR(pDevIns, rc,
2249 N_("Configuration error: Failed to read \"IOAPIC\""));
2250
2251 bool fRZEnabled;
2252 rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &fRZEnabled, true);
2253 if (RT_FAILURE(rc))
2254 return PDMDEV_SET_ERROR(pDevIns, rc,
2255 N_("Configuration error: Failed to query boolean value \"RZEnabled\""));
2256
2257 uint32_t cCpus;
2258 rc = CFGMR3QueryU32Def(pCfg, "NumCPUs", &cCpus, 1);
2259 if (RT_FAILURE(rc))
2260 return PDMDEV_SET_ERROR(pDevIns, rc,
2261 N_("Configuration error: Failed to query integer value \"NumCPUs\""));
2262
2263 Log(("APIC: cCpus=%d fRZEnabled=%RTbool fIoApic=%RTbool\n", cCpus, fRZEnabled, fIoApic));
2264 if (cCpus > 255)
2265 return PDMDEV_SET_ERROR(pDevIns, rc,
2266 N_("Configuration error: Invalid value for \"NumCPUs\""));
2267
2268 /*
2269 * Init the data.
2270 */
2271 pDev->pDevInsR3 = pDevIns;
2272 pDev->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
2273 pDev->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2274 pDev->cCpus = cCpus;
2275 pDev->fIoApic = fIoApic;
2276 /** @todo Finish X2APIC implementation. Must, among other things, set
2277 * PDMAPICVERSION_X2APIC here when X2APIC is configured. */
2278 pDev->enmVersion = PDMAPICVERSION_APIC;
2279
2280 /* Disable locking in this device. */
2281 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
2282 AssertRCReturn(rc, rc);
2283
2284 PVM pVM = PDMDevHlpGetVM(pDevIns);
2285
2286 /*
2287 * We are not freeing this memory, as it's automatically released when guest exits.
2288 */
2289 rc = MMHyperAlloc(pVM, cCpus * sizeof(APICState), 1, MM_TAG_PDM_DEVICE_USER, (void **)&pDev->paLapicsR3);
2290 if (RT_FAILURE(rc))
2291 return VERR_NO_MEMORY;
2292 pDev->paLapicsR0 = MMHyperR3ToR0(pVM, pDev->paLapicsR3);
2293 pDev->paLapicsRC = MMHyperR3ToRC(pVM, pDev->paLapicsR3);
2294
2295 for (i = 0; i < cCpus; i++)
2296 apicR3StateInit(&pDev->paLapicsR3[i], i);
2297
2298 /*
2299 * Register the APIC.
2300 */
2301 PDMAPICREG ApicReg;
2302 ApicReg.u32Version = PDM_APICREG_VERSION;
2303 ApicReg.pfnGetInterruptR3 = apicGetInterrupt;
2304 ApicReg.pfnHasPendingIrqR3 = apicHasPendingIrq;
2305 ApicReg.pfnSetBaseR3 = apicSetBase;
2306 ApicReg.pfnGetBaseR3 = apicGetBase;
2307 ApicReg.pfnSetTPRR3 = apicSetTPR;
2308 ApicReg.pfnGetTPRR3 = apicGetTPR;
2309 ApicReg.pfnWriteMSRR3 = apicWriteMSR;
2310 ApicReg.pfnReadMSRR3 = apicReadMSR;
2311 ApicReg.pfnBusDeliverR3 = apicBusDeliverCallback;
2312 ApicReg.pfnLocalInterruptR3 = apicLocalInterrupt;
2313 ApicReg.pfnGetTimerFreqR3 = apicGetTimerFreq;
2314 if (fRZEnabled)
2315 {
2316 ApicReg.pszGetInterruptRC = "apicGetInterrupt";
2317 ApicReg.pszHasPendingIrqRC = "apicHasPendingIrq";
2318 ApicReg.pszSetBaseRC = "apicSetBase";
2319 ApicReg.pszGetBaseRC = "apicGetBase";
2320 ApicReg.pszSetTPRRC = "apicSetTPR";
2321 ApicReg.pszGetTPRRC = "apicGetTPR";
2322 ApicReg.pszWriteMSRRC = "apicWriteMSR";
2323 ApicReg.pszReadMSRRC = "apicReadMSR";
2324 ApicReg.pszBusDeliverRC = "apicBusDeliverCallback";
2325 ApicReg.pszLocalInterruptRC = "apicLocalInterrupt";
2326 ApicReg.pszGetTimerFreqRC = "apicGetTimerFreq";
2327
2328 ApicReg.pszGetInterruptR0 = "apicGetInterrupt";
2329 ApicReg.pszHasPendingIrqR0 = "apicHasPendingIrq";
2330 ApicReg.pszSetBaseR0 = "apicSetBase";
2331 ApicReg.pszGetBaseR0 = "apicGetBase";
2332 ApicReg.pszSetTPRR0 = "apicSetTPR";
2333 ApicReg.pszGetTPRR0 = "apicGetTPR";
2334 ApicReg.pszWriteMSRR0 = "apicWriteMSR";
2335 ApicReg.pszReadMSRR0 = "apicReadMSR";
2336 ApicReg.pszBusDeliverR0 = "apicBusDeliverCallback";
2337 ApicReg.pszLocalInterruptR0 = "apicLocalInterrupt";
2338 ApicReg.pszGetTimerFreqR0 = "apicGetTimerFreq";
2339 }
2340 else
2341 {
2342 ApicReg.pszGetInterruptRC = NULL;
2343 ApicReg.pszHasPendingIrqRC = NULL;
2344 ApicReg.pszSetBaseRC = NULL;
2345 ApicReg.pszGetBaseRC = NULL;
2346 ApicReg.pszSetTPRRC = NULL;
2347 ApicReg.pszGetTPRRC = NULL;
2348 ApicReg.pszWriteMSRRC = NULL;
2349 ApicReg.pszReadMSRRC = NULL;
2350 ApicReg.pszBusDeliverRC = NULL;
2351 ApicReg.pszLocalInterruptRC = NULL;
2352 ApicReg.pszGetTimerFreqRC = NULL;
2353
2354 ApicReg.pszGetInterruptR0 = NULL;
2355 ApicReg.pszHasPendingIrqR0 = NULL;
2356 ApicReg.pszSetBaseR0 = NULL;
2357 ApicReg.pszGetBaseR0 = NULL;
2358 ApicReg.pszSetTPRR0 = NULL;
2359 ApicReg.pszGetTPRR0 = NULL;
2360 ApicReg.pszWriteMSRR0 = NULL;
2361 ApicReg.pszReadMSRR0 = NULL;
2362 ApicReg.pszBusDeliverR0 = NULL;
2363 ApicReg.pszLocalInterruptR0 = NULL;
2364 ApicReg.pszGetTimerFreqR0 = NULL;
2365 }
2366
2367 rc = PDMDevHlpAPICRegister(pDevIns, &ApicReg, &pDev->pApicHlpR3);
2368 AssertLogRelRCReturn(rc, rc);
2369 pDev->pCritSectR3 = pDev->pApicHlpR3->pfnGetR3CritSect(pDevIns);
2370
2371 /*
2372 * The CPUID feature bit.
2373 */
2374 LogRel(("APIC: Activating Local APIC\n"));
2375 pDev->pApicHlpR3->pfnChangeFeature(pDevIns, pDev->enmVersion);
2376
2377 /*
2378 * Register the MMIO range.
2379 */
2380 /** @todo shall reregister, if base changes. */
2381 uint32_t ApicBase = pDev->paLapicsR3[0].apicbase & ~0xfff;
2382 rc = PDMDevHlpMMIORegister(pDevIns, ApicBase, 0x1000, pDev,
2383 IOMMMIO_FLAGS_READ_DWORD | IOMMMIO_FLAGS_WRITE_DWORD_ZEROED,
2384 apicMMIOWrite, apicMMIORead, "APIC Memory");
2385 if (RT_FAILURE(rc))
2386 return rc;
2387
2388 if (fRZEnabled)
2389 {
2390 pDev->pApicHlpRC = pDev->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2391 pDev->pCritSectRC = pDev->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2392 rc = PDMDevHlpMMIORegisterRC(pDevIns, ApicBase, 0x1000, NIL_RTRCPTR /*pvUser*/, "apicMMIOWrite", "apicMMIORead");
2393 if (RT_FAILURE(rc))
2394 return rc;
2395
2396 pDev->pApicHlpR0 = pDev->pApicHlpR3->pfnGetR0Helpers(pDevIns);
2397 pDev->pCritSectR0 = pDev->pApicHlpR3->pfnGetR0CritSect(pDevIns);
2398 rc = PDMDevHlpMMIORegisterR0(pDevIns, ApicBase, 0x1000, NIL_RTR0PTR /*pvUser*/, "apicMMIOWrite", "apicMMIORead");
2399 if (RT_FAILURE(rc))
2400 return rc;
2401 }
2402
2403 /*
2404 * Create the APIC timers.
2405 */
2406 for (i = 0; i < cCpus; i++)
2407 {
2408 APICState *pApic = &pDev->paLapicsR3[i];
2409 pApic->pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_USER, "APIC Timer #%u", i);
2410 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, apicR3TimerCallback, pApic,
2411 TMTIMER_FLAGS_NO_CRIT_SECT, pApic->pszDesc, &pApic->pTimerR3);
2412 if (RT_FAILURE(rc))
2413 return rc;
2414 pApic->pTimerR0 = TMTimerR0Ptr(pApic->pTimerR3);
2415 pApic->pTimerRC = TMTimerRCPtr(pApic->pTimerR3);
2416 TMR3TimerSetCritSect(pApic->pTimerR3, pDev->pCritSectR3);
2417 }
2418
2419 /*
2420 * Saved state.
2421 */
2422 rc = PDMDevHlpSSMRegister3(pDevIns, APIC_SAVED_STATE_VERSION, sizeof(*pDev),
2423 apicR3LiveExec, apicR3SaveExec, apicR3LoadExec);
2424 if (RT_FAILURE(rc))
2425 return rc;
2426
2427 /*
2428 * Register debugger info callback.
2429 */
2430 PDMDevHlpDBGFInfoRegister(pDevIns, "apic", "Display Local APIC state for current CPU. "
2431 "Recognizes 'basic', 'lvt', 'timer' as arguments, defaulting to 'basic'.", apicR3Info);
2432
2433#ifdef VBOX_WITH_STATISTICS
2434 /*
2435 * Statistics.
2436 */
2437 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOReadGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in GC.");
2438 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOReadHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in HC.");
2439 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOWriteGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in GC.");
2440 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOWriteHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in HC.");
2441 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatClearedActiveIrq,STAMTYPE_COUNTER, "/Devices/APIC/MaskedActiveIRQ", STAMUNIT_OCCURENCES, "Number of cleared irqs.");
2442 for (i = 0; i < cCpus; i++)
2443 {
2444 APICState *pApic = &pDev->paLapicsR3[i];
2445 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCount, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetInitialCount.", "/Devices/APIC/%u/TimerSetInitialCount", i);
2446 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSetRelative calls.", "/Devices/APIC/%u/TimerSetInitialCount/Arm", i);
2447 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountDisarm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop calls.", "/Devices/APIC/%u/TimerSetInitialCount/Disasm", i);
2448 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvt, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetLvt.", "/Devices/APIC/%u/TimerSetLvt", i);
2449 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtClearPeriodic, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Clearing APIC_LVT_TIMER_PERIODIC.", "/Devices/APIC/%u/TimerSetLvt/ClearPeriodic", i);
2450 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtPostponed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop postponed.", "/Devices/APIC/%u/TimerSetLvt/Postponed", i);
2451 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet avoided.", "/Devices/APIC/%u/TimerSetLvt/Armed", i);
2452 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet necessary.", "/Devices/APIC/%u/TimerSetLvt/Arm", i);
2453 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmRetries, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet retries.", "/Devices/APIC/%u/TimerSetLvt/ArmRetries", i);
2454 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtNoRelevantChange,STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "No relevant flags changed.", "/Devices/APIC/%u/TimerSetLvt/NoRelevantChange", i);
2455 }
2456#endif
2457
2458 return VINF_SUCCESS;
2459}
2460
2461
2462/**
2463 * APIC device registration structure.
2464 */
2465const PDMDEVREG g_DeviceAPIC =
2466{
2467 /* u32Version */
2468 PDM_DEVREG_VERSION,
2469 /* szName */
2470 "apic",
2471 /* szRCMod */
2472 "VBoxDD2RC.rc",
2473 /* szR0Mod */
2474 "VBoxDD2R0.r0",
2475 /* pszDescription */
2476 "Advanced Programmable Interrupt Controller (APIC) Device",
2477 /* fFlags */
2478 PDM_DEVREG_FLAGS_HOST_BITS_DEFAULT | PDM_DEVREG_FLAGS_GUEST_BITS_32_64 | PDM_DEVREG_FLAGS_PAE36 | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
2479 /* fClass */
2480 PDM_DEVREG_CLASS_PIC,
2481 /* cMaxInstances */
2482 1,
2483 /* cbInstance */
2484 sizeof(APICState),
2485 /* pfnConstruct */
2486 apicR3Construct,
2487 /* pfnDestruct */
2488 NULL,
2489 /* pfnRelocate */
2490 apicR3Relocate,
2491 /* pfnMemSetup */
2492 NULL,
2493 /* pfnPowerOn */
2494 NULL,
2495 /* pfnReset */
2496 apicR3Reset,
2497 /* pfnSuspend */
2498 NULL,
2499 /* pfnResume */
2500 NULL,
2501 /* pfnAttach */
2502 NULL,
2503 /* pfnDetach */
2504 NULL,
2505 /* pfnQueryInterface. */
2506 NULL,
2507 /* pfnInitComplete */
2508 NULL,
2509 /* pfnPowerOff */
2510 NULL,
2511 /* pfnSoftReset */
2512 NULL,
2513 /* u32VersionEnd */
2514 PDM_DEVREG_VERSION
2515};
2516
2517#endif /* IN_RING3 */
2518#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
2519
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette