VirtualBox

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

Last change on this file since 52157 was 52157, checked in by vboxsync, 10 years ago

DevAPIC: fixes debug logging

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 89.6 KB
Line 
1/* $Id: DevAPIC.cpp 52157 2014-07-24 06:55:34Z 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 /* See @bugref{7097}. Intel IA-32/64 Spec 10.4.3:
610 * "When IA32_APIC_BASE[11] is 0, the processor is functionally equivalent to
611 * an IA-32 processor without an on-chip APIC. The CPUID feature flag for the
612 * APIC (see Section 10.4.2, 'Presence of the Local APIC') is also set to 0."
613 */
614 pDev->CTX_SUFF(pApicHlp)->pfnChangeFeature(pDevIns, PDMAPICVERSION_NONE);
615 break;
616 }
617 case PDMAPICVERSION_APIC:
618 /** @todo map MMIO ranges, if needed */
619 break;
620 case PDMAPICVERSION_X2APIC:
621 /** @todo unmap MMIO ranges of this APIC, according to the spec. This is how
622 * real hw works! (Remember the problem disabling NMI watchdog timers in
623 * the world switchers when host used x2apic?)! */
624 break;
625 default:
626 break;
627 }
628 }
629 /* APIC_UNLOCK(pDev); */
630}
631
632PDMBOTHCBDECL(uint64_t) apicGetBase(PPDMDEVINS pDevIns, VMCPUID idCpu)
633{
634 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
635 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
636 APICState *pApic = apicGetStateById(pDev, idCpu);
637 LogFlow(("apicGetBase: %016llx\n", (uint64_t)pApic->apicbase));
638 return pApic->apicbase;
639}
640
641PDMBOTHCBDECL(void) apicSetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t val)
642{
643 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
644 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
645 APICState *pApic = apicGetStateById(pDev, idCpu);
646 LogFlow(("apicSetTPR: val=%#x (trp %#x -> %#x)\n", val, pApic->tpr, val));
647 apic_update_tpr(pDev, pApic, val);
648}
649
650PDMBOTHCBDECL(uint8_t) apicGetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu)
651{
652 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
653 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
654 APICState *pApic = apicGetStateById(pDev, idCpu);
655 Log2(("apicGetTPR: returns %#x\n", pApic->tpr));
656 return pApic->tpr;
657}
658
659
660/**
661 * apicWriteRegister helper for dealing with invalid register access.
662 *
663 * @returns Strict VBox status code.
664 * @param pDev The PDM device instance.
665 * @param pApic The APIC being written to.
666 * @param iReg The APIC register index.
667 * @param u64Value The value being written.
668 * @param rcBusy The busy return code to employ. See
669 * PDMCritSectEnter for a description.
670 * @param fMsr Set if called via MSR, clear if MMIO.
671 */
672static int apicWriteRegisterInvalid(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t u64Value,
673 int rcBusy, bool fMsr)
674{
675 Log(("apicWriteRegisterInvalid/%u: iReg=%#x fMsr=%RTbool u64Value=%#llx\n", pApic->phys_id, iReg, fMsr, u64Value));
676 int rc = PDMDevHlpDBGFStop(pDev->CTX_SUFF(pDevIns), RT_SRC_POS,
677 "iReg=%#x fMsr=%RTbool u64Value=%#llx id=%u\n", iReg, fMsr, u64Value, pApic->phys_id);
678 APIC_LOCK(pDev, rcBusy);
679 pApic->esr |= ESR_ILLEGAL_ADDRESS;
680 APIC_UNLOCK(pDev);
681 return rc;
682}
683
684
685
686/**
687 * Writes to an APIC register via MMIO or MSR.
688 *
689 * @returns Strict VBox status code.
690 * @param pDev The PDM device instance.
691 * @param pApic The APIC being written to.
692 * @param iReg The APIC register index.
693 * @param u64Value The value being written.
694 * @param rcBusy The busy return code to employ. See
695 * PDMCritSectEnter for a description.
696 * @param fMsr Set if called via MSR, clear if MMIO.
697 */
698static int apicWriteRegister(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t u64Value,
699 int rcBusy, bool fMsr)
700{
701 Assert(!PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
702
703 int rc = VINF_SUCCESS;
704 switch (iReg)
705 {
706 case 0x02:
707 APIC_LOCK(pDev, rcBusy);
708 pApic->id = (u64Value >> 24); /** @todo r=bird: Is the range supposed to be 40 bits??? */
709 APIC_UNLOCK(pDev);
710 break;
711
712 case 0x03:
713 /* read only, ignore write. */
714 break;
715
716 case 0x08:
717 APIC_LOCK(pDev, rcBusy);
718 apic_update_tpr(pDev, pApic, u64Value);
719 APIC_UNLOCK(pDev);
720 break;
721
722 case 0x09: case 0x0a:
723 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
724 break;
725
726 case 0x0b: /* EOI */
727 APIC_LOCK(pDev, rcBusy);
728 apic_eoi(pDev, pApic);
729 APIC_UNLOCK(pDev);
730 break;
731
732 case 0x0d:
733 APIC_LOCK(pDev, rcBusy);
734 pApic->log_dest = (u64Value >> 24) & 0xff;
735 APIC_UNLOCK(pDev);
736 break;
737
738 case 0x0e:
739 APIC_LOCK(pDev, rcBusy);
740 pApic->dest_mode = u64Value >> 28; /** @todo r=bird: range? This used to be 32-bit before morphed into an MSR handler. */
741 APIC_UNLOCK(pDev);
742 break;
743
744 case 0x0f:
745 APIC_LOCK(pDev, rcBusy);
746 pApic->spurious_vec = u64Value & 0x1ff;
747 apic_update_irq(pDev, pApic);
748 APIC_UNLOCK(pDev);
749 break;
750
751 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
752 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
753 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
754 case 0x28:
755 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
756 break;
757
758 case 0x30:
759 APIC_LOCK(pDev, rcBusy);
760 pApic->icr[0] = (uint32_t)u64Value;
761 if (fMsr) /* Here one of the differences with regular APIC: ICR is single 64-bit register */
762 pApic->icr[1] = (uint32_t)(u64Value >> 32);
763 rc = apic_deliver(pDev, pApic, (pApic->icr[1] >> 24) & 0xff, (pApic->icr[0] >> 11) & 1,
764 (pApic->icr[0] >> 8) & 7, (pApic->icr[0] & 0xff),
765 (pApic->icr[0] >> 14) & 1, (pApic->icr[0] >> 15) & 1);
766 APIC_UNLOCK(pDev);
767 break;
768
769 case 0x31:
770 if (!fMsr)
771 {
772 APIC_LOCK(pDev, rcBusy);
773 pApic->icr[1] = (uint64_t)u64Value;
774 APIC_UNLOCK(pDev);
775 }
776 else
777 rc = apicWriteRegisterInvalid(pDev, pApic, iReg, u64Value, rcBusy, fMsr);
778 break;
779
780 case 0x32 + APIC_LVT_TIMER:
781 AssertCompile(APIC_LVT_TIMER == 0);
782 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
783 apicTimerSetLvt(pDev, pApic, u64Value);
784 APIC_AND_TM_UNLOCK(pDev, pApic);
785 break;
786
787 case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
788 APIC_LOCK(pDev, rcBusy);
789 pApic->lvt[iReg - 0x32] = u64Value;
790 APIC_UNLOCK(pDev);
791 break;
792
793 case 0x38:
794 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
795 apicTimerSetInitialCount(pDev, pApic, u64Value);
796 APIC_AND_TM_UNLOCK(pDev, pApic);
797 break;
798
799 case 0x39:
800 Log(("apicWriteRegister: write to read-only register %d ignored\n", iReg));
801 break;
802
803 case 0x3e:
804 {
805 APIC_LOCK(pDev, rcBusy);
806 pApic->divide_conf = u64Value & 0xb;
807 int v = (pApic->divide_conf & 3) | ((pApic->divide_conf >> 1) & 4);
808 pApic->count_shift = (v + 1) & 7;
809 APIC_UNLOCK(pDev);
810 break;
811 }
812
813 case 0x3f:
814 if (fMsr)
815 {
816 /* Self IPI, see x2APIC book 2.4.5 */
817 APIC_LOCK(pDev, rcBusy);
818 int vector = u64Value & 0xff;
819 VMCPUSET SelfSet;
820 VMCPUSET_EMPTY(&SelfSet);
821 VMCPUSET_ADD(&SelfSet, pApic->id);
822 rc = apic_bus_deliver(pDev,
823 &SelfSet,
824 0 /* Delivery mode - fixed */,
825 vector,
826 0 /* Polarity - conform to the bus */,
827 0 /* Trigger mode - edge */,
828 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDev->CTX_SUFF(pDevIns), PDM_IRQ_LEVEL_HIGH));
829 APIC_UNLOCK(pDev);
830 break;
831 }
832 /* else: fall thru */
833
834 default:
835 rc = apicWriteRegisterInvalid(pDev, pApic, iReg, u64Value, rcBusy, fMsr);
836 break;
837 }
838
839 return rc;
840}
841
842
843/**
844 * apicReadRegister helper for dealing with invalid register access.
845 *
846 * @returns Strict VBox status code.
847 * @param pDev The PDM device instance.
848 * @param pApic The APIC being read to.
849 * @param iReg The APIC register index.
850 * @param pu64Value Where to store the value we've read.
851 * @param rcBusy The busy return code to employ. See
852 * PDMCritSectEnter for a description.
853 * @param fMsr Set if called via MSR, clear if MMIO.
854 */
855static int apicReadRegisterInvalid(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t *pu64Value,
856 int rcBusy, bool fMsr)
857{
858 Log(("apicReadRegisterInvalid/%u: iReg=%#x fMsr=%RTbool\n", pApic->phys_id, iReg, fMsr));
859 int rc = PDMDevHlpDBGFStop(pDev->CTX_SUFF(pDevIns), RT_SRC_POS,
860 "iReg=%#x fMsr=%RTbool id=%u\n", iReg, fMsr, pApic->phys_id);
861 APIC_LOCK(pDev, rcBusy);
862 pApic->esr |= ESR_ILLEGAL_ADDRESS;
863 APIC_UNLOCK(pDev);
864 *pu64Value = 0;
865 return rc;
866}
867
868
869/**
870 * Read from an APIC register via MMIO or MSR.
871 *
872 * @returns Strict VBox status code.
873 * @param pDev The PDM device instance.
874 * @param pApic The APIC being read to.
875 * @param iReg The APIC register index.
876 * @param pu64Value Where to store the value we've read.
877 * @param rcBusy The busy return code to employ. See
878 * PDMCritSectEnter for a description.
879 * @param fMsr Set if called via MSR, clear if MMIO.
880 */
881static int apicReadRegister(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg, uint64_t *pu64Value,
882 int rcBusy, bool fMsr)
883{
884 Assert(!PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
885
886 int rc = VINF_SUCCESS;
887 switch (iReg)
888 {
889 case 0x02: /* id */
890 APIC_LOCK(pDev, rcBusy);
891 *pu64Value = pApic->id << 24;
892 APIC_UNLOCK(pDev);
893 break;
894
895 case 0x03: /* version */
896 APIC_LOCK(pDev, rcBusy);
897 *pu64Value = APIC_HW_VERSION
898 | ((APIC_LVT_NB - 1) << 16) /* Max LVT index */
899#if 0
900 | (0 << 24) /* Support for EOI broadcast suppression */
901#endif
902 ;
903 APIC_UNLOCK(pDev);
904 break;
905
906 case 0x08:
907 APIC_LOCK(pDev, rcBusy);
908 *pu64Value = pApic->tpr;
909 APIC_UNLOCK(pDev);
910 break;
911
912 case 0x09:
913 *pu64Value = apic_get_arb_pri(pApic);
914 break;
915
916 case 0x0a:
917 /* ppr */
918 APIC_LOCK(pDev, rcBusy);
919 *pu64Value = apic_get_ppr(pApic);
920 APIC_UNLOCK(pDev);
921 break;
922
923 case 0x0b:
924 Log(("apicReadRegister: %x -> write only returning 0\n", iReg));
925 *pu64Value = 0;
926 break;
927
928 case 0x0d:
929 APIC_LOCK(pDev, rcBusy);
930 *pu64Value = (uint64_t)pApic->log_dest << 24;
931 APIC_UNLOCK(pDev);
932 break;
933
934 case 0x0e:
935 /* Bottom 28 bits are always 1 */
936 APIC_LOCK(pDev, rcBusy);
937 *pu64Value = ((uint64_t)pApic->dest_mode << 28) | UINT32_C(0xfffffff);
938 APIC_UNLOCK(pDev);
939 break;
940
941 case 0x0f:
942 APIC_LOCK(pDev, rcBusy);
943 *pu64Value = pApic->spurious_vec;
944 APIC_UNLOCK(pDev);
945 break;
946
947 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
948 APIC_LOCK(pDev, rcBusy);
949 *pu64Value = pApic->isr.au32Bitmap[iReg & 7];
950 APIC_UNLOCK(pDev);
951 break;
952
953 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
954 APIC_LOCK(pDev, rcBusy);
955 *pu64Value = pApic->tmr.au32Bitmap[iReg & 7];
956 APIC_UNLOCK(pDev);
957 break;
958
959 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
960 APIC_LOCK(pDev, rcBusy);
961 *pu64Value = pApic->irr.au32Bitmap[iReg & 7];
962 APIC_UNLOCK(pDev);
963 break;
964
965 case 0x28:
966 APIC_LOCK(pDev, rcBusy);
967 *pu64Value = pApic->esr;
968 APIC_UNLOCK(pDev);
969 break;
970
971 case 0x30:
972 /* Here one of the differences with regular APIC: ICR is single 64-bit register */
973 APIC_LOCK(pDev, rcBusy);
974 if (fMsr)
975 *pu64Value = RT_MAKE_U64(pApic->icr[0], pApic->icr[1]);
976 else
977 *pu64Value = pApic->icr[0];
978 APIC_UNLOCK(pDev);
979 break;
980
981 case 0x31:
982 if (fMsr)
983 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
984 else
985 {
986 APIC_LOCK(pDev, rcBusy);
987 *pu64Value = pApic->icr[1];
988 APIC_UNLOCK(pDev);
989 }
990 break;
991
992 case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
993 APIC_LOCK(pDev, rcBusy);
994 *pu64Value = pApic->lvt[iReg - 0x32];
995 APIC_UNLOCK(pDev);
996 break;
997
998 case 0x38:
999 APIC_LOCK(pDev, rcBusy);
1000 *pu64Value = pApic->initial_count;
1001 APIC_UNLOCK(pDev);
1002 break;
1003
1004 case 0x39:
1005 APIC_AND_TM_LOCK(pDev, pApic, rcBusy);
1006 *pu64Value = apic_get_current_count(pDev, pApic);
1007 APIC_AND_TM_UNLOCK(pDev, pApic);
1008 break;
1009
1010 case 0x3e:
1011 APIC_LOCK(pDev, rcBusy);
1012 *pu64Value = pApic->divide_conf;
1013 APIC_UNLOCK(pDev);
1014 break;
1015
1016 case 0x3f:
1017 if (fMsr)
1018 {
1019 /* Self IPI register is write only */
1020 Log(("apicReadMSR: read from write-only register %d ignored\n", iReg));
1021 *pu64Value = 0;
1022 }
1023 else
1024 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
1025 break;
1026 case 0x2f: /** @todo Correctable machine check exception vector, implement me! */
1027 default:
1028 /**
1029 * @todo: according to spec when APIC writes to ESR it msut raise error interrupt,
1030 * i.e. LVT[5]
1031 */
1032 rc = apicReadRegisterInvalid(pDev, pApic, iReg, pu64Value, rcBusy, fMsr);
1033 break;
1034 }
1035 return rc;
1036}
1037
1038/**
1039 * @interface_method_impl{PDMAPICREG,pfnWriteMSRR3}
1040 */
1041PDMBOTHCBDECL(int) apicWriteMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t u64Value)
1042{
1043 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1044 if (pDev->enmVersion < PDMAPICVERSION_X2APIC)
1045 return VERR_EM_INTERPRETER; /** @todo tell the caller to raise hell (\#GP(0)). */
1046
1047 APICState *pApic = apicGetStateById(pDev, idCpu);
1048 uint32_t iReg = (u32Reg - MSR_IA32_X2APIC_START) & 0xff;
1049 return apicWriteRegister(pDev, pApic, iReg, u64Value, VINF_SUCCESS /*rcBusy*/, true /*fMsr*/);
1050}
1051
1052
1053/**
1054 * @interface_method_impl{PDMAPICREG,pfnReadMSRR3}
1055 */
1056PDMBOTHCBDECL(int) apicReadMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t *pu64Value)
1057{
1058 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1059
1060 if (pDev->enmVersion < PDMAPICVERSION_X2APIC)
1061 return VERR_EM_INTERPRETER;
1062
1063 APICState *pApic = apicGetStateById(pDev, idCpu);
1064 uint32_t iReg = (u32Reg - MSR_IA32_X2APIC_START) & 0xff;
1065 return apicReadRegister(pDev, pApic, iReg, pu64Value, VINF_SUCCESS /*rcBusy*/, true /*fMsr*/);
1066}
1067
1068/**
1069 * More or less private interface between IOAPIC, only PDM is responsible
1070 * for connecting the two devices.
1071 */
1072PDMBOTHCBDECL(int) apicBusDeliverCallback(PPDMDEVINS pDevIns, uint8_t u8Dest, uint8_t u8DestMode,
1073 uint8_t u8DeliveryMode, uint8_t iVector, uint8_t u8Polarity,
1074 uint8_t u8TriggerMode, uint32_t uTagSrc)
1075{
1076 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1077 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1078 LogFlow(("apicBusDeliverCallback: pDevIns=%p u8Dest=%#x u8DestMode=%#x u8DeliveryMode=%#x iVector=%#x u8Polarity=%#x u8TriggerMode=%#x uTagSrc=%#x\n",
1079 pDevIns, u8Dest, u8DestMode, u8DeliveryMode, iVector, u8Polarity, u8TriggerMode, uTagSrc));
1080 VMCPUSET DstSet;
1081 return apic_bus_deliver(pDev, apic_get_delivery_bitmask(pDev, u8Dest, u8DestMode, &DstSet),
1082 u8DeliveryMode, iVector, u8Polarity, u8TriggerMode, uTagSrc);
1083}
1084
1085/**
1086 * Local interrupt delivery, for devices attached to the CPU's LINT0/LINT1 pin.
1087 * Normally used for 8259A PIC and NMI.
1088 */
1089PDMBOTHCBDECL(int) apicLocalInterrupt(PPDMDEVINS pDevIns, uint8_t u8Pin, uint8_t u8Level)
1090{
1091 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1092 APICState *pApic = apicGetStateById(pDev, 0);
1093
1094 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1095 LogFlow(("apicLocalInterrupt: pDevIns=%p u8Pin=%x u8Level=%x\n", pDevIns, u8Pin, u8Level));
1096
1097 /* If LAPIC is disabled, go straight to the CPU. */
1098 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1099 {
1100 LogFlow(("apicLocalInterrupt: LAPIC disabled, delivering directly to CPU core.\n"));
1101 if (u8Level)
1102 apicCpuSetInterrupt(pDev, pApic, PDMAPICIRQ_EXTINT);
1103 else
1104 apicCpuClearInterrupt(pDev, pApic, PDMAPICIRQ_EXTINT);
1105
1106 return VINF_SUCCESS;
1107 }
1108
1109 /* If LAPIC is enabled, interrupts are subject to LVT programming. */
1110
1111 /* There are only two local interrupt pins. */
1112 AssertMsgReturn(u8Pin <= 1, ("Invalid LAPIC pin %d\n", u8Pin), VERR_INVALID_PARAMETER);
1113
1114 /* NB: We currently only deliver local interrupts to the first CPU. In theory they
1115 * should be delivered to all CPUs and it is the guest's responsibility to ensure
1116 * no more than one CPU has the interrupt unmasked.
1117 */
1118 uint32_t u32Lvec;
1119
1120 u32Lvec = pApic->lvt[APIC_LVT_LINT0 + u8Pin]; /* Fetch corresponding LVT entry. */
1121 /* Drop int if entry is masked. May not be correct for level-triggered interrupts. */
1122 if (!(u32Lvec & APIC_LVT_MASKED))
1123 { uint8_t u8Delivery;
1124 PDMAPICIRQ enmType;
1125
1126 u8Delivery = (u32Lvec >> 8) & 7;
1127 switch (u8Delivery)
1128 {
1129 case APIC_DM_EXTINT:
1130 Assert(u8Pin == 0); /* PIC should be wired to LINT0. */
1131 enmType = PDMAPICIRQ_EXTINT;
1132 /* ExtINT can be both set and cleared, NMI/SMI/INIT can only be set. */
1133 LogFlow(("apicLocalInterrupt: %s ExtINT interrupt\n", u8Level ? "setting" : "clearing"));
1134 if (u8Level)
1135 apicCpuSetInterrupt(pDev, pApic, enmType);
1136 else
1137 apicCpuClearInterrupt(pDev, pApic, enmType);
1138 return VINF_SUCCESS;
1139 case APIC_DM_NMI:
1140 /* External NMI should be wired to LINT1, but Linux sometimes programs
1141 * LVT0 to NMI delivery mode as well.
1142 */
1143 enmType = PDMAPICIRQ_NMI;
1144 /* Currently delivering NMIs through here causes problems with NMI watchdogs
1145 * on certain Linux kernels, e.g. 64-bit CentOS 5.3. Disable NMIs for now.
1146 */
1147 return VINF_SUCCESS;
1148 case APIC_DM_SMI:
1149 enmType = PDMAPICIRQ_SMI;
1150 break;
1151 case APIC_DM_FIXED:
1152 {
1153 /** @todo implement APIC_DM_FIXED! */
1154 static unsigned s_c = 0;
1155 if (s_c++ < 5)
1156 LogRel(("delivery type APIC_DM_FIXED not implemented. u8Pin=%d u8Level=%d\n", u8Pin, u8Level));
1157 return VINF_SUCCESS;
1158 }
1159 case APIC_DM_INIT:
1160 /** @todo implement APIC_DM_INIT? */
1161 default:
1162 {
1163 static unsigned s_c = 0;
1164 if (s_c++ < 100)
1165 AssertLogRelMsgFailed(("delivery type %d not implemented. u8Pin=%d u8Level=%d\n", u8Delivery, u8Pin, u8Level));
1166 return VERR_INTERNAL_ERROR_4;
1167 }
1168 }
1169 LogFlow(("apicLocalInterrupt: setting local interrupt type %d\n", enmType));
1170 apicCpuSetInterrupt(pDev, pApic, enmType);
1171 }
1172 return VINF_SUCCESS;
1173}
1174
1175static int apic_get_ppr(APICState const *pApic)
1176{
1177 int ppr;
1178
1179 int tpr = (pApic->tpr >> 4);
1180 int isrv = Apic256BitReg_FindLastSetBit(&pApic->isr, 0);
1181 isrv >>= 4;
1182 if (tpr >= isrv)
1183 ppr = pApic->tpr;
1184 else
1185 ppr = isrv << 4;
1186 return ppr;
1187}
1188
1189static int apic_get_ppr_zero_tpr(APICState *pApic)
1190{
1191 return Apic256BitReg_FindLastSetBit(&pApic->isr, 0);
1192}
1193
1194static int apic_get_arb_pri(APICState const *pApic)
1195{
1196 /** @todo XXX: arbitration */
1197 return 0;
1198}
1199
1200/* signal the CPU if an irq is pending */
1201static bool apic_update_irq(APICDeviceInfo *pDev, APICState *pApic)
1202{
1203 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1204 {
1205 /* Clear any pending APIC interrupt action flag. */
1206 apicCpuClearInterrupt(pDev, pApic);
1207 return false;
1208 }
1209
1210 int irrv = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1211 if (irrv < 0)
1212 return false;
1213 int ppr = apic_get_ppr(pApic);
1214 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
1215 return false;
1216 apicCpuSetInterrupt(pDev, pApic);
1217 return true;
1218}
1219
1220/* Check if the APIC has a pending interrupt/if a TPR change would active one. */
1221PDMBOTHCBDECL(bool) apicHasPendingIrq(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t *pu8PendingIrq)
1222{
1223 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1224 if (!pDev)
1225 return false;
1226
1227 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
1228
1229 APICState *pApic = apicGetStateById(pDev, idCpu);
1230
1231 /*
1232 * All our callbacks now come from single IOAPIC, thus locking
1233 * seems to be excessive now
1234 */
1235 /** @todo check excessive locking whatever... */
1236 int irrv = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1237 if (irrv < 0)
1238 return false;
1239
1240 int ppr = apic_get_ppr_zero_tpr(pApic);
1241
1242 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
1243 return false;
1244
1245 if (pu8PendingIrq)
1246 {
1247 Assert(irrv >= 0 && irrv <= (int)UINT8_MAX);
1248 *pu8PendingIrq = (uint8_t)irrv;
1249 }
1250 return true;
1251}
1252
1253static void apic_update_tpr(APICDeviceInfo *pDev, APICState *pApic, uint32_t val)
1254{
1255 bool fIrqIsActive = false;
1256 bool fIrqWasActive = false;
1257
1258 fIrqWasActive = apic_update_irq(pDev, pApic);
1259 pApic->tpr = val;
1260 fIrqIsActive = apic_update_irq(pDev, pApic);
1261
1262 /* If an interrupt is pending and now masked, then clear the FF flag. */
1263 if (fIrqWasActive && !fIrqIsActive)
1264 {
1265 Log(("apic_update_tpr: deactivate interrupt that was masked by the TPR update (%x)\n", val));
1266 STAM_COUNTER_INC(&pDev->StatClearedActiveIrq);
1267 apicCpuClearInterrupt(pDev, pApic);
1268 }
1269}
1270
1271static void apic_set_irq(APICDeviceInfo *pDev, APICState *pApic, int vector_num, int trigger_mode, uint32_t uTagSrc)
1272{
1273 LogFlow(("CPU%d: apic_set_irq vector=%x trigger_mode=%x uTagSrc=%#x\n", pApic->phys_id, vector_num, trigger_mode, uTagSrc));
1274
1275 Apic256BitReg_SetBit(&pApic->irr, vector_num);
1276 if (trigger_mode)
1277 Apic256BitReg_SetBit(&pApic->tmr, vector_num);
1278 else
1279 Apic256BitReg_ClearBit(&pApic->tmr, vector_num);
1280
1281 if (!pApic->auTags[vector_num])
1282 pApic->auTags[vector_num] = uTagSrc;
1283 else
1284 pApic->auTags[vector_num] |= RT_BIT_32(31);
1285
1286 apic_update_irq(pDev, pApic);
1287}
1288
1289static void apic_eoi(APICDeviceInfo *pDev, APICState *pApic)
1290{
1291 int isrv = Apic256BitReg_FindLastSetBit(&pApic->isr, -1);
1292 if (isrv < 0)
1293 return;
1294 Apic256BitReg_ClearBit(&pApic->isr, isrv);
1295 LogFlow(("CPU%d: apic_eoi isrv=%x\n", pApic->phys_id, isrv));
1296 /** @todo XXX: send the EOI packet to the APIC bus to allow the I/O APIC to
1297 * set the remote IRR bit for level triggered interrupts. */
1298 apic_update_irq(pDev, pApic);
1299}
1300
1301static PVMCPUSET apic_get_delivery_bitmask(APICDeviceInfo *pDev, uint8_t dest, uint8_t dest_mode, PVMCPUSET pDstSet)
1302{
1303 VMCPUSET_EMPTY(pDstSet);
1304
1305 if (dest_mode == 0)
1306 {
1307 if (dest == 0xff) /* The broadcast ID. */
1308 VMCPUSET_FILL(pDstSet);
1309 else
1310 VMCPUSET_ADD(pDstSet, dest);
1311 }
1312 else
1313 {
1314 /** @todo XXX: cluster mode */
1315 APIC_FOREACH_BEGIN(pDev);
1316 if (pCurApic->dest_mode == APIC_DESTMODE_FLAT)
1317 {
1318 if (dest & pCurApic->log_dest)
1319 VMCPUSET_ADD(pDstSet, iCurApic);
1320 }
1321 else if (pCurApic->dest_mode == APIC_DESTMODE_CLUSTER)
1322 {
1323 if ( (dest & 0xf0) == (pCurApic->log_dest & 0xf0)
1324 && (dest & pCurApic->log_dest & 0x0f))
1325 VMCPUSET_ADD(pDstSet, iCurApic);
1326 }
1327 APIC_FOREACH_END();
1328 }
1329
1330 return pDstSet;
1331}
1332
1333#ifdef IN_RING3
1334
1335static void apicR3InitIpi(APICDeviceInfo *pDev, APICState *pApic)
1336{
1337 int i;
1338
1339 for(i = 0; i < APIC_LVT_NB; i++)
1340 pApic->lvt[i] = 1 << 16; /* mask LVT */
1341 pApic->tpr = 0;
1342 pApic->spurious_vec = 0xff;
1343 pApic->log_dest = 0;
1344 pApic->dest_mode = 0xff; /** @todo 0xff???? */
1345 Apic256BitReg_Empty(&pApic->isr);
1346 Apic256BitReg_Empty(&pApic->tmr);
1347 Apic256BitReg_Empty(&pApic->irr);
1348 pApic->esr = 0;
1349 memset(pApic->icr, 0, sizeof(pApic->icr));
1350 pApic->divide_conf = 0;
1351 pApic->count_shift = 1;
1352 pApic->initial_count = 0;
1353 pApic->initial_count_load_time = 0;
1354 pApic->next_time = 0;
1355}
1356
1357
1358static void apicSendInitIpi(APICDeviceInfo *pDev, APICState *pApic)
1359{
1360 apicR3InitIpi(pDev, pApic);
1361 apicR3CpuSendInitIpi(pDev, pApic);
1362}
1363
1364/* send a SIPI message to the CPU to start it */
1365static void apicR3Startup(APICDeviceInfo *pDev, APICState *pApic, int vector_num)
1366{
1367 Log(("[SMP] apicR3Startup: %d on CPUs %d\n", vector_num, pApic->phys_id));
1368 apicR3CpuSendSipi(pDev, pApic, vector_num);
1369}
1370
1371#endif /* IN_RING3 */
1372
1373static int apic_deliver(APICDeviceInfo *pDev, APICState *pApic,
1374 uint8_t dest, uint8_t dest_mode,
1375 uint8_t delivery_mode, uint8_t vector_num,
1376 uint8_t polarity, uint8_t trigger_mode)
1377{
1378 int dest_shorthand = (pApic->icr[0] >> 18) & 3;
1379 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));
1380
1381 VMCPUSET DstSet;
1382 switch (dest_shorthand)
1383 {
1384 case 0:
1385 apic_get_delivery_bitmask(pDev, dest, dest_mode, &DstSet);
1386 break;
1387 case 1:
1388 VMCPUSET_EMPTY(&DstSet);
1389 VMCPUSET_ADD(&DstSet, pApic->id);
1390 break;
1391 case 2:
1392 VMCPUSET_FILL(&DstSet);
1393 break;
1394 case 3:
1395 VMCPUSET_FILL(&DstSet);
1396 VMCPUSET_DEL(&DstSet, pApic->id);
1397 break;
1398 }
1399
1400 switch (delivery_mode)
1401 {
1402 case APIC_DM_INIT:
1403 {
1404 uint32_t const trig_mode = (pApic->icr[0] >> 15) & 1;
1405 uint32_t const level = (pApic->icr[0] >> 14) & 1;
1406 if (level == 0 && trig_mode == 1)
1407 {
1408 APIC_FOREACH_IN_SET_BEGIN(pDev, &DstSet);
1409 pCurApic->arb_id = pCurApic->id;
1410 APIC_FOREACH_END();
1411 Log(("CPU%d: APIC_DM_INIT arbitration id(s) set\n", pApic->phys_id));
1412 return VINF_SUCCESS;
1413 }
1414 break;
1415 }
1416
1417 case APIC_DM_SIPI:
1418# ifdef IN_RING3
1419 APIC_FOREACH_IN_SET_BEGIN(pDev, &DstSet);
1420 apicR3Startup(pDev, pCurApic, vector_num);
1421 APIC_FOREACH_END();
1422 return VINF_SUCCESS;
1423# else
1424 /* We shall send SIPI only in R3, R0 calls should be
1425 rescheduled to R3 */
1426 return VINF_IOM_R3_MMIO_WRITE;
1427# endif
1428 }
1429
1430 return apic_bus_deliver(pDev, &DstSet, delivery_mode, vector_num,
1431 polarity, trigger_mode,
1432 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDev->CTX_SUFF(pDevIns), PDM_IRQ_LEVEL_HIGH));
1433}
1434
1435
1436PDMBOTHCBDECL(int) apicGetInterrupt(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t *puTagSrc)
1437{
1438 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1439 /* if the APIC is not installed or enabled, we let the 8259 handle the IRQs */
1440 if (!pDev)
1441 {
1442 Log(("apic_get_interrupt: returns -1 (!pDev)\n"));
1443 return -1;
1444 }
1445
1446 Assert(PDMCritSectIsOwner(pDev->CTX_SUFF(pCritSect)));
1447
1448 APICState *pApic = apicGetStateById(pDev, idCpu);
1449
1450 if (!(pApic->spurious_vec & APIC_SV_ENABLE))
1451 {
1452 Log(("CPU%d: apic_get_interrupt: returns -1 (APIC_SV_ENABLE)\n", pApic->phys_id));
1453 return -1;
1454 }
1455
1456 /** @todo XXX: spurious IRQ handling */
1457 int intno = Apic256BitReg_FindLastSetBit(&pApic->irr, -1);
1458 if (intno < 0)
1459 {
1460 Log(("CPU%d: apic_get_interrupt: returns -1 (irr)\n", pApic->phys_id));
1461 return -1;
1462 }
1463
1464 if (pApic->tpr && (uint32_t)intno <= pApic->tpr)
1465 {
1466 *puTagSrc = 0;
1467 Log(("apic_get_interrupt: returns %d (sp)\n", pApic->spurious_vec & 0xff));
1468 return pApic->spurious_vec & 0xff;
1469 }
1470
1471 Apic256BitReg_ClearBit(&pApic->irr, intno);
1472 Apic256BitReg_SetBit(&pApic->isr, intno);
1473
1474 *puTagSrc = pApic->auTags[intno];
1475 pApic->auTags[intno] = 0;
1476
1477 apic_update_irq(pDev, pApic);
1478
1479 LogFlow(("CPU%d: apic_get_interrupt: returns %d / %#x\n", pApic->phys_id, intno, *puTagSrc));
1480 return intno;
1481}
1482
1483/**
1484 * @remarks Caller (apicReadRegister) takes both the TM and APIC locks before
1485 * calling this function.
1486 */
1487static uint32_t apic_get_current_count(APICDeviceInfo const *pDev, APICState const *pApic)
1488{
1489 int64_t d = (TMTimerGet(pApic->CTX_SUFF(pTimer)) - pApic->initial_count_load_time)
1490 >> pApic->count_shift;
1491
1492 uint32_t val;
1493 if (pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC)
1494 /* periodic */
1495 val = pApic->initial_count - (d % ((uint64_t)pApic->initial_count + 1));
1496 else if (d >= pApic->initial_count)
1497 val = 0;
1498 else
1499 val = pApic->initial_count - d;
1500
1501 return val;
1502}
1503
1504/**
1505 * Does the frequency hinting and logging.
1506 *
1507 * @param pApic The device state.
1508 */
1509DECLINLINE(void) apicDoFrequencyHinting(APICState *pApic)
1510{
1511 if ( pApic->uHintedInitialCount != pApic->initial_count
1512 || pApic->uHintedCountShift != (uint32_t)pApic->count_shift)
1513 {
1514 pApic->uHintedInitialCount = pApic->initial_count;
1515 pApic->uHintedCountShift = pApic->count_shift;
1516
1517 uint32_t uHz;
1518 if (pApic->initial_count > 0)
1519 {
1520 Assert((unsigned)pApic->count_shift < 30);
1521 uint64_t cTickPerPeriod = ((uint64_t)pApic->initial_count + 1) << pApic->count_shift;
1522 uHz = TMTimerGetFreq(pApic->CTX_SUFF(pTimer)) / cTickPerPeriod;
1523 }
1524 else
1525 uHz = 0;
1526 TMTimerSetFrequencyHint(pApic->CTX_SUFF(pTimer), uHz);
1527 Log(("apic: %u Hz\n", uHz));
1528 }
1529}
1530
1531/**
1532 * Implementation of the 0380h access: Timer reset + new initial count.
1533 *
1534 * @param pDev The device state.
1535 * @param pApic The APIC sub-device state.
1536 * @param u32NewInitialCount The new initial count for the timer.
1537 */
1538static void apicTimerSetInitialCount(APICDeviceInfo *pDev, APICState *pApic, uint32_t u32NewInitialCount)
1539{
1540 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCount);
1541 pApic->initial_count = u32NewInitialCount;
1542
1543 /*
1544 * Don't (re-)arm the timer if the it's masked or if it's
1545 * a zero length one-shot timer.
1546 */
1547 if ( !(pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)
1548 && u32NewInitialCount > 0)
1549 {
1550 /*
1551 * Calculate the relative next time and perform a combined timer get/set
1552 * operation. This avoids racing the clock between get and set.
1553 */
1554 uint64_t cTicksNext = u32NewInitialCount;
1555 cTicksNext += 1;
1556 cTicksNext <<= pApic->count_shift;
1557 TMTimerSetRelative(pApic->CTX_SUFF(pTimer), cTicksNext, &pApic->initial_count_load_time);
1558 pApic->next_time = pApic->initial_count_load_time + cTicksNext;
1559 pApic->fTimerArmed = true;
1560 apicDoFrequencyHinting(pApic);
1561 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCountArm);
1562 Log(("apicTimerSetInitialCount: cTicksNext=%'llu (%#llx) ic=%#x sh=%#x nxt=%#llx\n",
1563 cTicksNext, cTicksNext, u32NewInitialCount, pApic->count_shift, pApic->next_time));
1564 }
1565 else
1566 {
1567 /* Stop it if necessary and record the load time for unmasking. */
1568 if (pApic->fTimerArmed)
1569 {
1570 STAM_COUNTER_INC(&pApic->StatTimerSetInitialCountDisarm);
1571 TMTimerStop(pApic->CTX_SUFF(pTimer));
1572 pApic->fTimerArmed = false;
1573 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1574 }
1575 pApic->initial_count_load_time = TMTimerGet(pApic->CTX_SUFF(pTimer));
1576 Log(("apicTimerSetInitialCount: ic=%#x sh=%#x iclt=%#llx\n", u32NewInitialCount, pApic->count_shift, pApic->initial_count_load_time));
1577 }
1578}
1579
1580/**
1581 * Implementation of the 0320h access: change the LVT flags.
1582 *
1583 * @param pDev The device state.
1584 * @param pApic The APIC sub-device state to operate on.
1585 * @param fNew The new flags.
1586 */
1587static void apicTimerSetLvt(APICDeviceInfo *pDev, APICState *pApic, uint32_t fNew)
1588{
1589 STAM_COUNTER_INC(&pApic->StatTimerSetLvt);
1590
1591 /*
1592 * Make the flag change, saving the old ones so we can avoid
1593 * unnecessary work.
1594 */
1595 uint32_t const fOld = pApic->lvt[APIC_LVT_TIMER];
1596 pApic->lvt[APIC_LVT_TIMER] = fNew;
1597
1598 /* Only the masked and peridic bits are relevant (see apic_timer_update). */
1599 if ( (fOld & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC))
1600 != (fNew & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC)))
1601 {
1602 /*
1603 * If changed to one-shot from periodic, stop the timer if we're not
1604 * in the first period.
1605 */
1606 /** @todo check how clearing the periodic flag really should behave when not
1607 * in period 1. The current code just mirrors the behavior of the
1608 * original implementation. */
1609 if ( (fOld & APIC_LVT_TIMER_PERIODIC)
1610 && !(fNew & APIC_LVT_TIMER_PERIODIC))
1611 {
1612 STAM_COUNTER_INC(&pApic->StatTimerSetLvtClearPeriodic);
1613 uint64_t cTicks = (pApic->next_time - pApic->initial_count_load_time) >> pApic->count_shift;
1614 if (cTicks >= pApic->initial_count)
1615 {
1616 /* not first period, stop it. */
1617 TMTimerStop(pApic->CTX_SUFF(pTimer));
1618 pApic->fTimerArmed = false;
1619 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1620 }
1621 /* else: first period, let it fire normally. */
1622 }
1623
1624 /*
1625 * We postpone stopping the timer when it's masked, this way we can
1626 * avoid some timer work when the guest temporarily masks the timer.
1627 * (apicR3TimerCallback will stop it if still masked.)
1628 */
1629 if (fNew & APIC_LVT_MASKED)
1630 STAM_COUNTER_INC(&pApic->StatTimerSetLvtPostponed);
1631 else if (pApic->fTimerArmed)
1632 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArmed);
1633 /*
1634 * If unmasked, not armed and with a valid initial count value (according
1635 * to our interpretation of the spec), we will have to rearm the timer so
1636 * it will fire at the end of the current period.
1637 *
1638 * N.B. This is code is currently RACING the virtual sync clock!
1639 */
1640 else if ( (fOld & APIC_LVT_MASKED)
1641 && pApic->initial_count > 0)
1642 {
1643 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArm);
1644 for (unsigned cTries = 0; ; cTries++)
1645 {
1646 uint64_t NextTS;
1647 uint64_t cTicks = (TMTimerGet(pApic->CTX_SUFF(pTimer)) - pApic->initial_count_load_time) >> pApic->count_shift;
1648 if (fNew & APIC_LVT_TIMER_PERIODIC)
1649 NextTS = ((cTicks / ((uint64_t)pApic->initial_count + 1)) + 1) * ((uint64_t)pApic->initial_count + 1);
1650 else
1651 {
1652 if (cTicks >= pApic->initial_count)
1653 break;
1654 NextTS = (uint64_t)pApic->initial_count + 1;
1655 }
1656 NextTS <<= pApic->count_shift;
1657 NextTS += pApic->initial_count_load_time;
1658
1659 /* Try avoid the assertion in TM.cpp... this isn't perfect! */
1660 if ( NextTS > TMTimerGet(pApic->CTX_SUFF(pTimer))
1661 || cTries > 10)
1662 {
1663 TMTimerSet(pApic->CTX_SUFF(pTimer), NextTS);
1664 pApic->next_time = NextTS;
1665 pApic->fTimerArmed = true;
1666 apicDoFrequencyHinting(pApic);
1667 Log(("apicTimerSetLvt: ic=%#x sh=%#x nxt=%#llx\n", pApic->initial_count, pApic->count_shift, pApic->next_time));
1668 break;
1669 }
1670 STAM_COUNTER_INC(&pApic->StatTimerSetLvtArmRetries);
1671 }
1672 }
1673 }
1674 else
1675 STAM_COUNTER_INC(&pApic->StatTimerSetLvtNoRelevantChange);
1676}
1677
1678# ifdef IN_RING3
1679
1680/**
1681 * Timer callback function.
1682 *
1683 * @param pDevIns The device state.
1684 * @param pTimer The timer handle.
1685 * @param pvUser User argument pointing to the APIC instance.
1686 */
1687static DECLCALLBACK(void) apicR3TimerCallback(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
1688{
1689 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1690 APICState *pApic = (APICState *)pvUser;
1691 Assert(pApic->pTimerR3 == pTimer);
1692 Assert(pApic->fTimerArmed);
1693 Assert(PDMCritSectIsOwner(pDev->pCritSectR3));
1694 Assert(TMTimerIsLockOwner(pTimer));
1695
1696 if (!(pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)) {
1697 LogFlow(("apic_timer: trigger irq\n"));
1698 apic_set_irq(pDev, pApic, pApic->lvt[APIC_LVT_TIMER] & 0xff, APIC_TRIGGER_EDGE,
1699 pDev->CTX_SUFF(pApicHlp)->pfnCalcIrqTag(pDevIns, PDM_IRQ_LEVEL_HIGH));
1700
1701 if ( (pApic->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC)
1702 && pApic->initial_count > 0) {
1703 /* new interval. */
1704 pApic->next_time += (((uint64_t)pApic->initial_count + 1) << pApic->count_shift);
1705 TMTimerSet(pApic->CTX_SUFF(pTimer), pApic->next_time);
1706 pApic->fTimerArmed = true;
1707 apicDoFrequencyHinting(pApic);
1708 Log2(("apicR3TimerCallback: ic=%#x sh=%#x nxt=%#llx\n", pApic->initial_count, pApic->count_shift, pApic->next_time));
1709 } else {
1710 /* single shot or disabled. */
1711 pApic->fTimerArmed = false;
1712 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1713 }
1714 } else {
1715 /* masked, do not rearm. */
1716 pApic->fTimerArmed = false;
1717 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1718 }
1719}
1720
1721static void apic_save(SSMHANDLE* f, void *opaque)
1722{
1723 APICState *pApic = (APICState*)opaque;
1724 int i;
1725
1726 SSMR3PutU32(f, pApic->apicbase);
1727 SSMR3PutU32(f, pApic->id);
1728 SSMR3PutU32(f, pApic->phys_id);
1729 SSMR3PutU32(f, pApic->arb_id);
1730 SSMR3PutU32(f, pApic->tpr);
1731 SSMR3PutU32(f, pApic->spurious_vec);
1732 SSMR3PutU8(f, pApic->log_dest);
1733 SSMR3PutU8(f, pApic->dest_mode);
1734 for (i = 0; i < 8; i++) {
1735 SSMR3PutU32(f, pApic->isr.au32Bitmap[i]);
1736 SSMR3PutU32(f, pApic->tmr.au32Bitmap[i]);
1737 SSMR3PutU32(f, pApic->irr.au32Bitmap[i]);
1738 }
1739 for (i = 0; i < APIC_LVT_NB; i++) {
1740 SSMR3PutU32(f, pApic->lvt[i]);
1741 }
1742 SSMR3PutU32(f, pApic->esr);
1743 SSMR3PutU32(f, pApic->icr[0]);
1744 SSMR3PutU32(f, pApic->icr[1]);
1745 SSMR3PutU32(f, pApic->divide_conf);
1746 SSMR3PutU32(f, pApic->count_shift);
1747 SSMR3PutU32(f, pApic->initial_count);
1748 SSMR3PutU64(f, pApic->initial_count_load_time);
1749 SSMR3PutU64(f, pApic->next_time);
1750
1751 TMR3TimerSave(pApic->CTX_SUFF(pTimer), f);
1752}
1753
1754static int apic_load(SSMHANDLE *f, void *opaque, int version_id)
1755{
1756 APICState *pApic = (APICState*)opaque;
1757 int i;
1758
1759 /** @todo XXX: what if the base changes? (registered memory regions) */
1760 SSMR3GetU32(f, &pApic->apicbase);
1761
1762 switch (version_id)
1763 {
1764 case APIC_SAVED_STATE_VERSION_ANCIENT:
1765 {
1766 uint8_t val = 0;
1767 SSMR3GetU8(f, &val);
1768 pApic->id = val;
1769 /* UP only in old saved states */
1770 pApic->phys_id = 0;
1771 SSMR3GetU8(f, &val);
1772 pApic->arb_id = val;
1773 break;
1774 }
1775 case APIC_SAVED_STATE_VERSION:
1776 case APIC_SAVED_STATE_VERSION_VBOX_30:
1777 SSMR3GetU32(f, &pApic->id);
1778 SSMR3GetU32(f, &pApic->phys_id);
1779 SSMR3GetU32(f, &pApic->arb_id);
1780 break;
1781 default:
1782 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1783 }
1784 SSMR3GetU32(f, &pApic->tpr);
1785 SSMR3GetU32(f, &pApic->spurious_vec);
1786 SSMR3GetU8(f, &pApic->log_dest);
1787 SSMR3GetU8(f, &pApic->dest_mode);
1788 for (i = 0; i < 8; i++) {
1789 SSMR3GetU32(f, &pApic->isr.au32Bitmap[i]);
1790 SSMR3GetU32(f, &pApic->tmr.au32Bitmap[i]);
1791 SSMR3GetU32(f, &pApic->irr.au32Bitmap[i]);
1792 }
1793 for (i = 0; i < APIC_LVT_NB; i++) {
1794 SSMR3GetU32(f, &pApic->lvt[i]);
1795 }
1796 SSMR3GetU32(f, &pApic->esr);
1797 SSMR3GetU32(f, &pApic->icr[0]);
1798 SSMR3GetU32(f, &pApic->icr[1]);
1799 SSMR3GetU32(f, &pApic->divide_conf);
1800 SSMR3GetU32(f, (uint32_t *)&pApic->count_shift);
1801 SSMR3GetU32(f, (uint32_t *)&pApic->initial_count);
1802 SSMR3GetU64(f, (uint64_t *)&pApic->initial_count_load_time);
1803 SSMR3GetU64(f, (uint64_t *)&pApic->next_time);
1804
1805 int rc = TMR3TimerLoad(pApic->CTX_SUFF(pTimer), f);
1806 AssertRCReturn(rc, rc);
1807 pApic->uHintedCountShift = pApic->uHintedInitialCount = 0;
1808 pApic->fTimerArmed = TMTimerIsActive(pApic->CTX_SUFF(pTimer));
1809 if (pApic->fTimerArmed)
1810 apicDoFrequencyHinting(pApic);
1811
1812 return VINF_SUCCESS; /** @todo darn mess! */
1813}
1814
1815#endif /* IN_RING3 */
1816
1817/* LAPIC */
1818PDMBOTHCBDECL(int) apicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
1819{
1820 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1821 APICState *pApic = apicGetStateByCurEmt(pDev);
1822
1823 Log(("CPU%d: apicMMIORead at %RGp\n", pApic->phys_id, GCPhysAddr));
1824 Assert(cb == 4);
1825
1826 /** @todo add LAPIC range validity checks (different LAPICs can
1827 * theoretically have different physical addresses, see @bugref{3092}) */
1828
1829 STAM_COUNTER_INC(&CTXSUFF(pDev->StatMMIORead));
1830#if 0 /* Note! experimental */
1831#ifndef IN_RING3
1832 uint32_t index = (GCPhysAddr >> 4) & 0xff;
1833
1834 if ( index == 0x08 /* TPR */
1835 && ++pApic->cTPRPatchAttempts < APIC_MAX_PATCH_ATTEMPTS)
1836 {
1837# ifdef IN_RC
1838 pDevIns->pDevHlpGC->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, &pApic->tpr);
1839# else
1840 RTGCPTR pDevInsGC = PDMINS2DATA_GCPTR(pDevIns);
1841 pDevIns->pHlpR0->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, pDevIns + RT_OFFSETOF(APICState, tpr));
1842# endif
1843 return VINF_PATM_HC_MMIO_PATCH_READ;
1844 }
1845#endif
1846#endif /* experimental */
1847
1848 /* Note! apicReadRegister does its own locking. */
1849 uint64_t u64Value = 0;
1850 int rc = apicReadRegister(pDev, pApic, (GCPhysAddr >> 4) & 0xff, &u64Value, VINF_IOM_R3_MMIO_READ, false /*fMsr*/);
1851 *(uint32_t *)pv = (uint32_t)u64Value;
1852 return rc;
1853}
1854
1855PDMBOTHCBDECL(int) apicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void const *pv, unsigned cb)
1856{
1857 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1858 APICState *pApic = apicGetStateByCurEmt(pDev);
1859
1860 Log(("CPU%d: apicMMIOWrite at %RGp\n", pApic->phys_id, GCPhysAddr));
1861 Assert(cb == 4);
1862
1863 /** @todo add LAPIC range validity checks (multiple LAPICs can theoretically
1864 * have different physical addresses, see @bugref{3092}) */
1865
1866 STAM_COUNTER_INC(&CTXSUFF(pDev->StatMMIOWrite));
1867 /* Note! It does its own locking. */
1868 return apicWriteRegister(pDev, pApic, (GCPhysAddr >> 4) & 0xff, *(uint32_t const *)pv,
1869 VINF_IOM_R3_MMIO_WRITE, false /*fMsr*/);
1870}
1871
1872#ifdef IN_RING3
1873
1874/**
1875 * Wrapper around apicReadRegister.
1876 *
1877 * @returns 64-bit register value.
1878 * @param pDev The PDM device instance.
1879 * @param pApic The Local APIC in question.
1880 * @param iReg The APIC register index.
1881 */
1882static uint64_t apicR3InfoReadReg(APICDeviceInfo *pDev, APICState *pApic, uint32_t iReg)
1883{
1884 uint64_t u64Value;
1885 int rc = apicReadRegister(pDev, pApic, iReg, &u64Value, VINF_SUCCESS, true /*fMsr*/);
1886 AssertRCReturn(rc, UINT64_MAX);
1887 return u64Value;
1888}
1889
1890/**
1891 * Print an 8-DWORD Local APIC bit map (256 bits).
1892 *
1893 * @param pDev The PDM device instance.
1894 * @param pApic The Local APIC in question.
1895 * @param pHlp The output helper.
1896 * @param iStartReg The register to start at.
1897 */
1898static void apicR3DumpVec(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp, uint32_t iStartReg)
1899{
1900 for (int i = 7; i >= 0; --i)
1901 pHlp->pfnPrintf(pHlp, "%08x", apicR3InfoReadReg(pDev, pApic, iStartReg + i));
1902 pHlp->pfnPrintf(pHlp, "\n");
1903}
1904
1905/**
1906 * Print the set of pending interrupts in a 256-bit map.
1907 *
1908 * @param pDev The PDM device instance.
1909 * @param pApic The Local APIC in question.
1910 * @param pHlp The output helper.
1911 * @param iStartReg The register to start at.
1912 */
1913static void apicR3DumpPending(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp, PCAPIC256BITREG pReg)
1914{
1915 APIC256BITREG pending;
1916 int iMax;
1917 int cPending = 0;
1918
1919 pending = *pReg;
1920 pHlp->pfnPrintf(pHlp, " pending =");
1921
1922 while ((iMax = Apic256BitReg_FindLastSetBit(&pending, -1)) != -1)
1923 {
1924 pHlp->pfnPrintf(pHlp, " %02x", iMax);
1925 Apic256BitReg_ClearBit(&pending, iMax);
1926 ++cPending;
1927 }
1928 if (!cPending)
1929 pHlp->pfnPrintf(pHlp, " none");
1930 pHlp->pfnPrintf(pHlp, "\n");
1931}
1932
1933/**
1934 * Print basic Local APIC state.
1935 *
1936 * @param pDev The PDM device instance.
1937 * @param pApic The Local APIC in question.
1938 * @param pHlp The output helper.
1939 */
1940static void apicR3InfoBasic(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
1941{
1942 uint64_t u64;
1943
1944 pHlp->pfnPrintf(pHlp, "Local APIC at %08llx:\n", pApic->apicbase);
1945 u64 = apicR3InfoReadReg(pDev, pApic, 0x2);
1946 pHlp->pfnPrintf(pHlp, " LAPIC ID : %08llx\n", u64);
1947 pHlp->pfnPrintf(pHlp, " APIC ID = %02llx\n", (u64 >> 24) & 0xff);
1948 u64 = apicR3InfoReadReg(pDev, pApic, 0x3);
1949 pHlp->pfnPrintf(pHlp, " APIC VER : %08llx\n", u64);
1950 pHlp->pfnPrintf(pHlp, " version = %02x\n", (int)RT_BYTE1(u64));
1951 pHlp->pfnPrintf(pHlp, " lvts = %d\n", (int)RT_BYTE3(u64) + 1);
1952 u64 = apicR3InfoReadReg(pDev, pApic, 0x8);
1953 pHlp->pfnPrintf(pHlp, " TPR : %08llx\n", u64);
1954 pHlp->pfnPrintf(pHlp, " task pri = %lld/%lld\n", (u64 >> 4) & 0xf, u64 & 0xf);
1955 u64 = apicR3InfoReadReg(pDev, pApic, 0xA);
1956 pHlp->pfnPrintf(pHlp, " PPR : %08llx\n", u64);
1957 pHlp->pfnPrintf(pHlp, " cpu pri = %lld/%lld\n", (u64 >> 4) & 0xf, u64 & 0xf);
1958 u64 = apicR3InfoReadReg(pDev, pApic, 0xD);
1959 pHlp->pfnPrintf(pHlp, " LDR : %08llx\n", u64);
1960 pHlp->pfnPrintf(pHlp, " log id = %02llx\n", (u64 >> 24) & 0xff);
1961 pHlp->pfnPrintf(pHlp, " DFR : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0xE));
1962 u64 = apicR3InfoReadReg(pDev, pApic, 0xF);
1963 pHlp->pfnPrintf(pHlp, " SVR : %08llx\n", u64);
1964 pHlp->pfnPrintf(pHlp, " focus = %s\n", u64 & RT_BIT(9) ? "check off" : "check on");
1965 pHlp->pfnPrintf(pHlp, " lapic = %s\n", u64 & RT_BIT(8) ? "ENABLED" : "DISABLED");
1966 pHlp->pfnPrintf(pHlp, " vector = %02x\n", (unsigned)RT_BYTE1(u64));
1967 pHlp->pfnPrintf(pHlp, " ISR : ");
1968 apicR3DumpVec(pDev, pApic, pHlp, 0x10);
1969 apicR3DumpPending(pDev, pApic, pHlp, &pApic->isr);
1970 pHlp->pfnPrintf(pHlp, " IRR : ");
1971 apicR3DumpVec(pDev, pApic, pHlp, 0x20);
1972 apicR3DumpPending(pDev, pApic, pHlp, &pApic->irr);
1973}
1974
1975
1976/**
1977 * Print the more interesting Local APIC LVT entries.
1978 *
1979 * @param pDev The PDM device instance.
1980 * @param pApic The Local APIC in question.
1981 * @param pHlp The output helper.
1982 */
1983static void apicR3InfoLVT(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
1984{
1985 static const char * const s_apszDeliveryModes[] =
1986 {
1987 "Fixed ", "Reserved", "SMI", "Reserved", "NMI", "INIT", "Reserved", "ExtINT"
1988 };
1989 uint64_t u64;
1990
1991 u64 = apicR3InfoReadReg(pDev, pApic, 0x32);
1992 pHlp->pfnPrintf(pHlp, " LVT Timer : %08llx\n", u64);
1993 pHlp->pfnPrintf(pHlp, " mode = %s\n", u64 & RT_BIT(17) ? "periodic" : "one-shot");
1994 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
1995 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
1996 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
1997 u64 = apicR3InfoReadReg(pDev, pApic, 0x35);
1998 pHlp->pfnPrintf(pHlp, " LVT LINT0 : %08llx\n", u64);
1999 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
2000 pHlp->pfnPrintf(pHlp, " trigger = %s\n", u64 & RT_BIT(15) ? "level" : "edge");
2001 pHlp->pfnPrintf(pHlp, " rem irr = %llu\n", (u64 >> 14) & 1);
2002 pHlp->pfnPrintf(pHlp, " polarty = %llu\n", (u64 >> 13) & 1);
2003 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
2004 pHlp->pfnPrintf(pHlp, " delivry = %s\n", s_apszDeliveryModes[(u64 >> 8) & 7]);
2005 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
2006 u64 = apicR3InfoReadReg(pDev, pApic, 0x36);
2007 pHlp->pfnPrintf(pHlp, " LVT LINT1 : %08llx\n", u64);
2008 pHlp->pfnPrintf(pHlp, " mask = %llu\n", (u64 >> 16) & 1);
2009 pHlp->pfnPrintf(pHlp, " trigger = %s\n", u64 & RT_BIT(15) ? "level" : "edge");
2010 pHlp->pfnPrintf(pHlp, " rem irr = %lld\n", (u64 >> 14) & 1);
2011 pHlp->pfnPrintf(pHlp, " polarty = %lld\n", (u64 >> 13) & 1);
2012 pHlp->pfnPrintf(pHlp, " status = %s\n", u64 & RT_BIT(12) ? "pending" : "idle");
2013 pHlp->pfnPrintf(pHlp, " delivry = %s\n", s_apszDeliveryModes[(u64 >> 8) & 7]);
2014 pHlp->pfnPrintf(pHlp, " vector = %02llx\n", u64 & 0xff);
2015}
2016
2017
2018/**
2019 * Print LAPIC timer state.
2020 *
2021 * @param pDev The PDM device instance.
2022 * @param pApic The Local APIC in question.
2023 * @param pHlp The output helper.
2024 */
2025static void apicR3InfoTimer(APICDeviceInfo *pDev, APICState *pApic, PCDBGFINFOHLP pHlp)
2026{
2027 pHlp->pfnPrintf(pHlp, "Local APIC timer:\n");
2028 pHlp->pfnPrintf(pHlp, " Initial count : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0x38));
2029 pHlp->pfnPrintf(pHlp, " Current count : %08llx\n", apicR3InfoReadReg(pDev, pApic, 0x39));
2030 uint64_t u64 = apicR3InfoReadReg(pDev, pApic, 0x3e);
2031 pHlp->pfnPrintf(pHlp, " Divide config : %08llx\n", u64);
2032 unsigned uDivider = ((u64 >> 1) & 0x04) | (u64 & 0x03);
2033 pHlp->pfnPrintf(pHlp, " divider = %u\n", uDivider == 7 ? 1 : 2 << uDivider);
2034}
2035
2036
2037/**
2038 * @callback_method_impl{FNDBGFHANDLERDEV,
2039 * Dumps the Local APIC state according to given argument.}
2040 */
2041static DECLCALLBACK(void) apicR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
2042{
2043 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2044 APICState *pApic = apicGetStateByCurEmt(pDev);
2045
2046 if (pszArgs == NULL || !*pszArgs || !strcmp(pszArgs, "basic"))
2047 apicR3InfoBasic(pDev, pApic, pHlp);
2048 else if (!strcmp(pszArgs, "lvt"))
2049 apicR3InfoLVT(pDev, pApic, pHlp);
2050 else if (!strcmp(pszArgs, "timer"))
2051 apicR3InfoTimer(pDev, pApic, pHlp);
2052 else
2053 pHlp->pfnPrintf(pHlp, "Invalid argument. Recognized arguments are 'basic', 'lvt', 'timer'.\n");
2054}
2055
2056
2057/**
2058 * @copydoc FNSSMDEVLIVEEXEC
2059 */
2060static DECLCALLBACK(int) apicR3LiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass)
2061{
2062 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2063
2064 SSMR3PutU32( pSSM, pDev->cCpus);
2065 SSMR3PutBool(pSSM, pDev->fIoApic);
2066 SSMR3PutU32( pSSM, pDev->enmVersion);
2067 AssertCompile(PDMAPICVERSION_APIC == 2);
2068
2069 return VINF_SSM_DONT_CALL_AGAIN;
2070}
2071
2072
2073/**
2074 * @copydoc FNSSMDEVSAVEEXEC
2075 */
2076static DECLCALLBACK(int) apicR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2077{
2078 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2079
2080 /* config */
2081 apicR3LiveExec(pDevIns, pSSM, SSM_PASS_FINAL);
2082
2083 /* save all APICs data */ /** @todo is it correct? */
2084 APIC_FOREACH_BEGIN(pDev);
2085 apic_save(pSSM, pCurApic);
2086 APIC_FOREACH_END();
2087
2088 return VINF_SUCCESS;
2089}
2090
2091/**
2092 * @copydoc FNSSMDEVLOADEXEC
2093 */
2094static DECLCALLBACK(int) apicR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
2095{
2096 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2097
2098 if ( uVersion != APIC_SAVED_STATE_VERSION
2099 && uVersion != APIC_SAVED_STATE_VERSION_VBOX_30
2100 && uVersion != APIC_SAVED_STATE_VERSION_ANCIENT)
2101 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
2102
2103 /* config */
2104 if (uVersion > APIC_SAVED_STATE_VERSION_VBOX_30)
2105 {
2106 uint32_t cCpus;
2107 int rc = SSMR3GetU32(pSSM, &cCpus); AssertRCReturn(rc, rc);
2108 if (cCpus != pDev->cCpus)
2109 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - cCpus: saved=%#x config=%#x"), cCpus, pDev->cCpus);
2110
2111 bool fIoApic;
2112 rc = SSMR3GetBool(pSSM, &fIoApic); AssertRCReturn(rc, rc);
2113 if (fIoApic != pDev->fIoApic)
2114 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - fIoApic: saved=%RTbool config=%RTbool"), fIoApic, pDev->fIoApic);
2115
2116 uint32_t uApicVersion;
2117 rc = SSMR3GetU32(pSSM, &uApicVersion); AssertRCReturn(rc, rc);
2118 if (uApicVersion != (uint32_t)pDev->enmVersion)
2119 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - uApicVersion: saved=%#x config=%#x"), uApicVersion, pDev->enmVersion);
2120 }
2121
2122 if (uPass != SSM_PASS_FINAL)
2123 return VINF_SUCCESS;
2124
2125 /* load all APICs data */ /** @todo is it correct? */
2126 APIC_LOCK(pDev, VERR_INTERNAL_ERROR_3);
2127
2128 int rc = VINF_SUCCESS;
2129 APIC_FOREACH_BEGIN(pDev);
2130 rc = apic_load(pSSM, pCurApic, uVersion);
2131 if (RT_FAILURE(rc))
2132 break;
2133 APIC_FOREACH_END();
2134
2135 APIC_UNLOCK(pDev);
2136 return rc;
2137}
2138
2139/**
2140 * @copydoc FNPDMDEVRESET
2141 */
2142static DECLCALLBACK(void) apicR3Reset(PPDMDEVINS pDevIns)
2143{
2144 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2145 TMTimerLock(pDev->paLapicsR3[0].pTimerR3, VERR_IGNORED);
2146 APIC_LOCK_VOID(pDev, VERR_IGNORED);
2147
2148 /* Reset all APICs. */
2149 for (VMCPUID i = 0; i < pDev->cCpus; i++)
2150 {
2151 APICState *pApic = &pDev->CTX_SUFF(paLapics)[i];
2152 TMTimerStop(pApic->CTX_SUFF(pTimer));
2153
2154 /* Clear LAPIC state as if an INIT IPI was sent. */
2155 apicR3InitIpi(pDev, pApic);
2156
2157 /* The IDs are not touched by apicR3InitIpi() and must be reset now. */
2158 pApic->arb_id = pApic->id = i;
2159 Assert(pApic->id == pApic->phys_id); /* The two should match again. */
2160
2161 /* Reset should re-enable the APIC, see comment in msi.h */
2162 pApic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2163 if (pApic->phys_id == 0)
2164 pApic->apicbase |= MSR_IA32_APICBASE_BSP;
2165
2166 /* Clear any pending APIC interrupt action flag. */
2167 apicCpuClearInterrupt(pDev, pApic);
2168 }
2169
2170 LogRel(("DevAPIC: Re-activating Local APIC\n"));
2171 pDev->pApicHlpR3->pfnChangeFeature(pDev->pDevInsR3, pDev->enmVersion);
2172
2173 APIC_UNLOCK(pDev);
2174 TMTimerUnlock(pDev->paLapicsR3[0].pTimerR3);
2175}
2176
2177
2178/**
2179 * @copydoc FNPDMDEVRELOCATE
2180 */
2181static DECLCALLBACK(void) apicR3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
2182{
2183 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2184 pDev->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2185 pDev->pApicHlpRC = pDev->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2186 pDev->paLapicsRC = MMHyperR3ToRC(PDMDevHlpGetVM(pDevIns), pDev->paLapicsR3);
2187 pDev->pCritSectRC = pDev->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2188 for (uint32_t i = 0; i < pDev->cCpus; i++)
2189 pDev->paLapicsR3[i].pTimerRC = TMTimerRCPtr(pDev->paLapicsR3[i].pTimerR3);
2190}
2191
2192
2193/**
2194 * Initializes the state of one local APIC.
2195 *
2196 * @param pApic The Local APIC state to init.
2197 * @param id The Local APIC ID.
2198 */
2199static void apicR3StateInit(APICState *pApic, uint8_t id)
2200{
2201 memset(pApic, 0, sizeof(*pApic));
2202
2203 /* See comment in msi.h for LAPIC base info. */
2204 pApic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2205 if (id == 0) /* Mark first CPU as BSP. */
2206 pApic->apicbase |= MSR_IA32_APICBASE_BSP;
2207
2208 for (int i = 0; i < APIC_LVT_NB; i++)
2209 pApic->lvt[i] = RT_BIT_32(16); /* mask LVT */
2210
2211 pApic->spurious_vec = 0xff;
2212 pApic->phys_id = id;
2213 pApic->id = id;
2214}
2215
2216
2217/**
2218 * @copydoc FNPDMDEVCONSTRUCT
2219 */
2220static DECLCALLBACK(int) apicR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2221{
2222 APICDeviceInfo *pDev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2223 uint32_t i;
2224
2225 /*
2226 * Only single device instance.
2227 */
2228 Assert(iInstance == 0);
2229
2230 /*
2231 * Validate configuration.
2232 */
2233 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "IOAPIC|RZEnabled|NumCPUs", "");
2234
2235 bool fIoApic;
2236 int rc = CFGMR3QueryBoolDef(pCfg, "IOAPIC", &fIoApic, true);
2237 if (RT_FAILURE(rc))
2238 return PDMDEV_SET_ERROR(pDevIns, rc,
2239 N_("Configuration error: Failed to read \"IOAPIC\""));
2240
2241 bool fRZEnabled;
2242 rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &fRZEnabled, true);
2243 if (RT_FAILURE(rc))
2244 return PDMDEV_SET_ERROR(pDevIns, rc,
2245 N_("Configuration error: Failed to query boolean value \"RZEnabled\""));
2246
2247 uint32_t cCpus;
2248 rc = CFGMR3QueryU32Def(pCfg, "NumCPUs", &cCpus, 1);
2249 if (RT_FAILURE(rc))
2250 return PDMDEV_SET_ERROR(pDevIns, rc,
2251 N_("Configuration error: Failed to query integer value \"NumCPUs\""));
2252
2253 Log(("APIC: cCpus=%d fRZEnabled=%RTbool fIoApic=%RTbool\n", cCpus, fRZEnabled, fIoApic));
2254 if (cCpus > 255)
2255 return PDMDEV_SET_ERROR(pDevIns, rc,
2256 N_("Configuration error: Invalid value for \"NumCPUs\""));
2257
2258 /*
2259 * Init the data.
2260 */
2261 pDev->pDevInsR3 = pDevIns;
2262 pDev->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
2263 pDev->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2264 pDev->cCpus = cCpus;
2265 pDev->fIoApic = fIoApic;
2266 /** @todo Finish X2APIC implementation. Must, among other things, set
2267 * PDMAPICVERSION_X2APIC here when X2APIC is configured. */
2268 pDev->enmVersion = PDMAPICVERSION_APIC;
2269
2270 /* Disable locking in this device. */
2271 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
2272 AssertRCReturn(rc, rc);
2273
2274 PVM pVM = PDMDevHlpGetVM(pDevIns);
2275
2276 /*
2277 * We are not freeing this memory, as it's automatically released when guest exits.
2278 */
2279 rc = MMHyperAlloc(pVM, cCpus * sizeof(APICState), 1, MM_TAG_PDM_DEVICE_USER, (void **)&pDev->paLapicsR3);
2280 if (RT_FAILURE(rc))
2281 return VERR_NO_MEMORY;
2282 pDev->paLapicsR0 = MMHyperR3ToR0(pVM, pDev->paLapicsR3);
2283 pDev->paLapicsRC = MMHyperR3ToRC(pVM, pDev->paLapicsR3);
2284
2285 for (i = 0; i < cCpus; i++)
2286 apicR3StateInit(&pDev->paLapicsR3[i], i);
2287
2288 /*
2289 * Register the APIC.
2290 */
2291 PDMAPICREG ApicReg;
2292 ApicReg.u32Version = PDM_APICREG_VERSION;
2293 ApicReg.pfnGetInterruptR3 = apicGetInterrupt;
2294 ApicReg.pfnHasPendingIrqR3 = apicHasPendingIrq;
2295 ApicReg.pfnSetBaseR3 = apicSetBase;
2296 ApicReg.pfnGetBaseR3 = apicGetBase;
2297 ApicReg.pfnSetTPRR3 = apicSetTPR;
2298 ApicReg.pfnGetTPRR3 = apicGetTPR;
2299 ApicReg.pfnWriteMSRR3 = apicWriteMSR;
2300 ApicReg.pfnReadMSRR3 = apicReadMSR;
2301 ApicReg.pfnBusDeliverR3 = apicBusDeliverCallback;
2302 ApicReg.pfnLocalInterruptR3 = apicLocalInterrupt;
2303 if (fRZEnabled)
2304 {
2305 ApicReg.pszGetInterruptRC = "apicGetInterrupt";
2306 ApicReg.pszHasPendingIrqRC = "apicHasPendingIrq";
2307 ApicReg.pszSetBaseRC = "apicSetBase";
2308 ApicReg.pszGetBaseRC = "apicGetBase";
2309 ApicReg.pszSetTPRRC = "apicSetTPR";
2310 ApicReg.pszGetTPRRC = "apicGetTPR";
2311 ApicReg.pszWriteMSRRC = "apicWriteMSR";
2312 ApicReg.pszReadMSRRC = "apicReadMSR";
2313 ApicReg.pszBusDeliverRC = "apicBusDeliverCallback";
2314 ApicReg.pszLocalInterruptRC = "apicLocalInterrupt";
2315
2316 ApicReg.pszGetInterruptR0 = "apicGetInterrupt";
2317 ApicReg.pszHasPendingIrqR0 = "apicHasPendingIrq";
2318 ApicReg.pszSetBaseR0 = "apicSetBase";
2319 ApicReg.pszGetBaseR0 = "apicGetBase";
2320 ApicReg.pszSetTPRR0 = "apicSetTPR";
2321 ApicReg.pszGetTPRR0 = "apicGetTPR";
2322 ApicReg.pszWriteMSRR0 = "apicWriteMSR";
2323 ApicReg.pszReadMSRR0 = "apicReadMSR";
2324 ApicReg.pszBusDeliverR0 = "apicBusDeliverCallback";
2325 ApicReg.pszLocalInterruptR0 = "apicLocalInterrupt";
2326 }
2327 else
2328 {
2329 ApicReg.pszGetInterruptRC = NULL;
2330 ApicReg.pszHasPendingIrqRC = NULL;
2331 ApicReg.pszSetBaseRC = NULL;
2332 ApicReg.pszGetBaseRC = NULL;
2333 ApicReg.pszSetTPRRC = NULL;
2334 ApicReg.pszGetTPRRC = NULL;
2335 ApicReg.pszWriteMSRRC = NULL;
2336 ApicReg.pszReadMSRRC = NULL;
2337 ApicReg.pszBusDeliverRC = NULL;
2338 ApicReg.pszLocalInterruptRC = NULL;
2339
2340 ApicReg.pszGetInterruptR0 = NULL;
2341 ApicReg.pszHasPendingIrqR0 = NULL;
2342 ApicReg.pszSetBaseR0 = NULL;
2343 ApicReg.pszGetBaseR0 = NULL;
2344 ApicReg.pszSetTPRR0 = NULL;
2345 ApicReg.pszGetTPRR0 = NULL;
2346 ApicReg.pszWriteMSRR0 = NULL;
2347 ApicReg.pszReadMSRR0 = NULL;
2348 ApicReg.pszBusDeliverR0 = NULL;
2349 ApicReg.pszLocalInterruptR0 = NULL;
2350 }
2351
2352 rc = PDMDevHlpAPICRegister(pDevIns, &ApicReg, &pDev->pApicHlpR3);
2353 AssertLogRelRCReturn(rc, rc);
2354 pDev->pCritSectR3 = pDev->pApicHlpR3->pfnGetR3CritSect(pDevIns);
2355
2356 /*
2357 * The CPUID feature bit.
2358 */
2359 LogRel(("DevAPIC: Activating Local APIC\n"));
2360 pDev->pApicHlpR3->pfnChangeFeature(pDevIns, pDev->enmVersion);
2361
2362 /*
2363 * Register the MMIO range.
2364 */
2365 /** @todo shall reregister, if base changes. */
2366 uint32_t ApicBase = pDev->paLapicsR3[0].apicbase & ~0xfff;
2367 rc = PDMDevHlpMMIORegister(pDevIns, ApicBase, 0x1000, pDev,
2368 IOMMMIO_FLAGS_READ_DWORD | IOMMMIO_FLAGS_WRITE_ONLY_DWORD,
2369 apicMMIOWrite, apicMMIORead, "APIC Memory");
2370 if (RT_FAILURE(rc))
2371 return rc;
2372
2373 if (fRZEnabled)
2374 {
2375 pDev->pApicHlpRC = pDev->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2376 pDev->pCritSectRC = pDev->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2377 rc = PDMDevHlpMMIORegisterRC(pDevIns, ApicBase, 0x1000, NIL_RTRCPTR /*pvUser*/, "apicMMIOWrite", "apicMMIORead");
2378 if (RT_FAILURE(rc))
2379 return rc;
2380
2381 pDev->pApicHlpR0 = pDev->pApicHlpR3->pfnGetR0Helpers(pDevIns);
2382 pDev->pCritSectR0 = pDev->pApicHlpR3->pfnGetR0CritSect(pDevIns);
2383 rc = PDMDevHlpMMIORegisterR0(pDevIns, ApicBase, 0x1000, NIL_RTR0PTR /*pvUser*/, "apicMMIOWrite", "apicMMIORead");
2384 if (RT_FAILURE(rc))
2385 return rc;
2386 }
2387
2388 /*
2389 * Create the APIC timers.
2390 */
2391 for (i = 0; i < cCpus; i++)
2392 {
2393 APICState *pApic = &pDev->paLapicsR3[i];
2394 pApic->pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_USER, "APIC Timer #%u", i);
2395 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, apicR3TimerCallback, pApic,
2396 TMTIMER_FLAGS_NO_CRIT_SECT, pApic->pszDesc, &pApic->pTimerR3);
2397 if (RT_FAILURE(rc))
2398 return rc;
2399 pApic->pTimerR0 = TMTimerR0Ptr(pApic->pTimerR3);
2400 pApic->pTimerRC = TMTimerRCPtr(pApic->pTimerR3);
2401 TMR3TimerSetCritSect(pApic->pTimerR3, pDev->pCritSectR3);
2402 }
2403
2404 /*
2405 * Saved state.
2406 */
2407 rc = PDMDevHlpSSMRegister3(pDevIns, APIC_SAVED_STATE_VERSION, sizeof(*pDev),
2408 apicR3LiveExec, apicR3SaveExec, apicR3LoadExec);
2409 if (RT_FAILURE(rc))
2410 return rc;
2411
2412 /*
2413 * Register debugger info callback.
2414 */
2415 PDMDevHlpDBGFInfoRegister(pDevIns, "apic", "Display Local APIC state for current CPU. "
2416 "Recognizes 'basic', 'lvt', 'timer' as arguments, defaulting to 'basic'.", apicR3Info);
2417
2418#ifdef VBOX_WITH_STATISTICS
2419 /*
2420 * Statistics.
2421 */
2422 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOReadGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in GC.");
2423 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOReadHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in HC.");
2424 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOWriteGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in GC.");
2425 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatMMIOWriteHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in HC.");
2426 PDMDevHlpSTAMRegister(pDevIns, &pDev->StatClearedActiveIrq,STAMTYPE_COUNTER, "/Devices/APIC/MaskedActiveIRQ", STAMUNIT_OCCURENCES, "Number of cleared irqs.");
2427 for (i = 0; i < cCpus; i++)
2428 {
2429 APICState *pApic = &pDev->paLapicsR3[i];
2430 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCount, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetInitialCount.", "/Devices/APIC/%u/TimerSetInitialCount", i);
2431 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSetRelative calls.", "/Devices/APIC/%u/TimerSetInitialCount/Arm", i);
2432 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountDisarm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop calls.", "/Devices/APIC/%u/TimerSetInitialCount/Disasm", i);
2433 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvt, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetLvt.", "/Devices/APIC/%u/TimerSetLvt", i);
2434 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtClearPeriodic, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Clearing APIC_LVT_TIMER_PERIODIC.", "/Devices/APIC/%u/TimerSetLvt/ClearPeriodic", i);
2435 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtPostponed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop postponed.", "/Devices/APIC/%u/TimerSetLvt/Postponed", i);
2436 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet avoided.", "/Devices/APIC/%u/TimerSetLvt/Armed", i);
2437 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet necessary.", "/Devices/APIC/%u/TimerSetLvt/Arm", i);
2438 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmRetries, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet retries.", "/Devices/APIC/%u/TimerSetLvt/ArmRetries", i);
2439 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtNoRelevantChange,STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "No relevant flags changed.", "/Devices/APIC/%u/TimerSetLvt/NoRelevantChange", i);
2440 }
2441#endif
2442
2443 return VINF_SUCCESS;
2444}
2445
2446
2447/**
2448 * APIC device registration structure.
2449 */
2450const PDMDEVREG g_DeviceAPIC =
2451{
2452 /* u32Version */
2453 PDM_DEVREG_VERSION,
2454 /* szName */
2455 "apic",
2456 /* szRCMod */
2457 "VBoxDD2GC.gc",
2458 /* szR0Mod */
2459 "VBoxDD2R0.r0",
2460 /* pszDescription */
2461 "Advanced Programmable Interrupt Controller (APIC) Device",
2462 /* fFlags */
2463 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,
2464 /* fClass */
2465 PDM_DEVREG_CLASS_PIC,
2466 /* cMaxInstances */
2467 1,
2468 /* cbInstance */
2469 sizeof(APICState),
2470 /* pfnConstruct */
2471 apicR3Construct,
2472 /* pfnDestruct */
2473 NULL,
2474 /* pfnRelocate */
2475 apicR3Relocate,
2476 /* pfnMemSetup */
2477 NULL,
2478 /* pfnPowerOn */
2479 NULL,
2480 /* pfnReset */
2481 apicR3Reset,
2482 /* pfnSuspend */
2483 NULL,
2484 /* pfnResume */
2485 NULL,
2486 /* pfnAttach */
2487 NULL,
2488 /* pfnDetach */
2489 NULL,
2490 /* pfnQueryInterface. */
2491 NULL,
2492 /* pfnInitComplete */
2493 NULL,
2494 /* pfnPowerOff */
2495 NULL,
2496 /* pfnSoftReset */
2497 NULL,
2498 /* u32VersionEnd */
2499 PDM_DEVREG_VERSION
2500};
2501
2502#endif /* IN_RING3 */
2503#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
2504
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