VirtualBox

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

Last change on this file since 49437 was 49437, checked in by vboxsync, 11 years ago

DevAPIC.cpp: Don't disable the CPUID feature bit just because someone disables the APIC.

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