VirtualBox

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

Last change on this file since 39053 was 39053, checked in by vboxsync, 13 years ago

DevApic.cpp: Don't assert on invalid register accesses, do a DBGFStop instead.

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