VirtualBox

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

最後變更 在這個檔案從32960是 32960,由 vboxsync 提交於 14 年 前

PCI: bad typo in PCI address computation, now Windows boots fine with MCFG

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id
檔案大小: 102.8 KB
 
1/* $Id: DevAPIC.cpp 32960 2010-10-06 16:59:56Z 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.alldomusa.eu.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
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#define LOG_GROUP LOG_GROUP_DEV_APIC
28#include <VBox/pdmdev.h>
29
30#include <VBox/log.h>
31#include <VBox/stam.h>
32#include <iprt/assert.h>
33#include <iprt/asm.h>
34
35#include <VBox/msi.h>
36
37#include "Builtins2.h"
38
39#define MSR_IA32_APICBASE 0x1b
40#define MSR_IA32_APICBASE_BSP (1<<8)
41#define MSR_IA32_APICBASE_ENABLE (1<<11)
42#define MSR_IA32_APICBASE_X2ENABLE (1<<10)
43#define MSR_IA32_APICBASE_BASE (0xfffff<<12)
44
45#ifdef _MSC_VER
46# pragma warning(disable:4244)
47#endif
48
49/** The current saved state version.*/
50#define APIC_SAVED_STATE_VERSION 3
51/** The saved state version used by VirtualBox v3 and earlier.
52 * This does not include the config. */
53#define APIC_SAVED_STATE_VERSION_VBOX_30 2
54/** Some ancient version... */
55#define APIC_SAVED_STATE_VERSION_ANCIENT 1
56
57/* version 0x14: Pentium 4, Xeon; LVT count depends on that */
58#define APIC_HW_VERSION 0x14
59
60/** @def APIC_LOCK
61 * Acquires the PDM lock. */
62#define APIC_LOCK(pThis, rcBusy) \
63 do { \
64 int rc2 = PDMCritSectEnter((pThis)->CTX_SUFF(pCritSect), (rcBusy)); \
65 if (rc2 != VINF_SUCCESS) \
66 return rc2; \
67 } while (0)
68
69/** @def APIC_LOCK_VOID
70 * Acquires the PDM lock and does not expect failure (i.e. ring-3 only!). */
71#define APIC_LOCK_VOID(pThis, rcBusy) \
72 do { \
73 int rc2 = PDMCritSectEnter((pThis)->CTX_SUFF(pCritSect), (rcBusy)); \
74 AssertLogRelRCReturnVoid(rc2); \
75 } while (0)
76
77/** @def APIC_UNLOCK
78 * Releases the PDM lock. */
79#define APIC_UNLOCK(pThis) \
80 PDMCritSectLeave((pThis)->CTX_SUFF(pCritSect))
81
82/** @def IOAPIC_LOCK
83 * Acquires the PDM lock. */
84#define IOAPIC_LOCK(pThis, rc) \
85 do { \
86 int rc2 = (pThis)->CTX_SUFF(pIoApicHlp)->pfnLock((pThis)->CTX_SUFF(pDevIns), rc); \
87 if (rc2 != VINF_SUCCESS) \
88 return rc2; \
89 } while (0)
90
91/** @def IOAPIC_UNLOCK
92 * Releases the PDM lock. */
93#define IOAPIC_UNLOCK(pThis) (pThis)->CTX_SUFF(pIoApicHlp)->pfnUnlock((pThis)->CTX_SUFF(pDevIns))
94
95
96#define foreach_apic(dev, mask, code) \
97 do { \
98 uint32_t i; \
99 APICState *apic = (dev)->CTX_SUFF(paLapics); \
100 for (i = 0; i < (dev)->cCpus; i++) \
101 { \
102 if (mask & (1 << (apic->id))) \
103 { \
104 code; \
105 } \
106 apic++; \
107 } \
108 } while (0)
109
110# define set_bit(pvBitmap, iBit) ASMBitSet(pvBitmap, iBit)
111# define reset_bit(pvBitmap, iBit) ASMBitClear(pvBitmap, iBit)
112# define fls_bit(value) (ASMBitLastSetU32(value) - 1)
113# define ffs_bit(value) (ASMBitFirstSetU32(value) - 1)
114
115/*
116 * APIC support
117 *
118 * Copyright (c) 2004-2005 Fabrice Bellard
119 *
120 * This library is free software; you can redistribute it and/or
121 * modify it under the terms of the GNU Lesser General Public
122 * License as published by the Free Software Foundation; either
123 * version 2 of the License, or (at your option) any later version.
124 *
125 * This library is distributed in the hope that it will be useful,
126 * but WITHOUT ANY WARRANTY; without even the implied warranty of
127 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
128 * Lesser General Public License for more details.
129 *
130 * You should have received a copy of the GNU Lesser General Public
131 * License along with this library; if not, write to the Free Software
132 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
133 */
134#define DEBUG_APIC
135#define DEBUG_IOAPIC
136
137/* APIC Local Vector Table */
138#define APIC_LVT_TIMER 0
139#define APIC_LVT_THERMAL 1
140#define APIC_LVT_PERFORM 2
141#define APIC_LVT_LINT0 3
142#define APIC_LVT_LINT1 4
143#define APIC_LVT_ERROR 5
144#define APIC_LVT_NB 6
145
146/* APIC delivery modes */
147#define APIC_DM_FIXED 0
148#define APIC_DM_LOWPRI 1
149#define APIC_DM_SMI 2
150#define APIC_DM_NMI 4
151#define APIC_DM_INIT 5
152#define APIC_DM_SIPI 6
153#define APIC_DM_EXTINT 7
154
155/* APIC destination mode */
156#define APIC_DESTMODE_FLAT 0xf
157#define APIC_DESTMODE_CLUSTER 0x0
158
159#define APIC_TRIGGER_EDGE 0
160#define APIC_TRIGGER_LEVEL 1
161
162#define APIC_LVT_TIMER_PERIODIC (1<<17)
163#define APIC_LVT_MASKED (1<<16)
164#define APIC_LVT_LEVEL_TRIGGER (1<<15)
165#define APIC_LVT_REMOTE_IRR (1<<14)
166#define APIC_INPUT_POLARITY (1<<13)
167#define APIC_SEND_PENDING (1<<12)
168
169#define IOAPIC_NUM_PINS 0x18
170
171#define ESR_ILLEGAL_ADDRESS (1 << 7)
172
173#define APIC_SV_ENABLE (1 << 8)
174
175#define APIC_MAX_PATCH_ATTEMPTS 100
176
177typedef uint32_t PhysApicId;
178typedef uint32_t LogApicId;
179
180typedef struct APICState {
181 uint32_t apicbase;
182 /* Task priority register (interrupt level) */
183 uint32_t tpr;
184 /* Logical APIC id - user programmable */
185 LogApicId id;
186 /* Physical APIC id - not visible to user, constant */
187 PhysApicId phys_id;
188 /** @todo: is it logical or physical? Not really used anyway now. */
189 PhysApicId arb_id;
190 uint32_t spurious_vec;
191 uint8_t log_dest;
192 uint8_t dest_mode;
193 uint32_t isr[8]; /* in service register */
194 uint32_t tmr[8]; /* trigger mode register */
195 uint32_t irr[8]; /* interrupt request register */
196 uint32_t lvt[APIC_LVT_NB];
197 uint32_t esr; /* error register */
198 uint32_t icr[2];
199 uint32_t divide_conf;
200 int count_shift;
201 uint32_t initial_count;
202 uint32_t Alignment0;
203
204 /** The time stamp of the initial_count load, i.e. when it was started. */
205 uint64_t initial_count_load_time;
206 /** The time stamp of the next timer callback. */
207 uint64_t next_time;
208 /** The APIC timer - R3 Ptr. */
209 PTMTIMERR3 pTimerR3;
210 /** The APIC timer - R0 Ptr. */
211 PTMTIMERR0 pTimerR0;
212 /** The APIC timer - RC Ptr. */
213 PTMTIMERRC pTimerRC;
214 /** Whether the timer is armed or not */
215 bool fTimerArmed;
216 /** Alignment */
217 bool afAlignment[3];
218 /** The initial_count value used for the current frequency hint. */
219 uint32_t uHintedInitialCount;
220 /** The count_shift value used for the current frequency hint. */
221 uint32_t uHintedCountShift;
222 /** Timer description timer. */
223 R3PTRTYPE(char *) pszDesc;
224# ifdef VBOX_WITH_STATISTICS
225# if HC_ARCH_BITS == 32
226 uint32_t u32Alignment0;
227# endif
228 STAMCOUNTER StatTimerSetInitialCount;
229 STAMCOUNTER StatTimerSetInitialCountArm;
230 STAMCOUNTER StatTimerSetInitialCountDisarm;
231 STAMCOUNTER StatTimerSetLvt;
232 STAMCOUNTER StatTimerSetLvtClearPeriodic;
233 STAMCOUNTER StatTimerSetLvtPostponed;
234 STAMCOUNTER StatTimerSetLvtArmed;
235 STAMCOUNTER StatTimerSetLvtArm;
236 STAMCOUNTER StatTimerSetLvtArmRetries;
237 STAMCOUNTER StatTimerSetLvtNoRelevantChange;
238# endif
239
240} APICState;
241
242AssertCompileMemberAlignment(APICState, initial_count_load_time, 8);
243# ifdef VBOX_WITH_STATISTICS
244AssertCompileMemberAlignment(APICState, StatTimerSetInitialCount, 8);
245# endif
246
247struct IOAPICState {
248 uint8_t id;
249 uint8_t ioregsel;
250
251 uint32_t irr;
252 uint64_t ioredtbl[IOAPIC_NUM_PINS];
253
254 /** The device instance - R3 Ptr. */
255 PPDMDEVINSR3 pDevInsR3;
256 /** The IOAPIC helpers - R3 Ptr. */
257 PCPDMIOAPICHLPR3 pIoApicHlpR3;
258
259 /** The device instance - R0 Ptr. */
260 PPDMDEVINSR0 pDevInsR0;
261 /** The IOAPIC helpers - R0 Ptr. */
262 PCPDMIOAPICHLPR0 pIoApicHlpR0;
263
264 /** The device instance - RC Ptr. */
265 PPDMDEVINSRC pDevInsRC;
266 /** The IOAPIC helpers - RC Ptr. */
267 PCPDMIOAPICHLPRC pIoApicHlpRC;
268
269# ifdef VBOX_WITH_STATISTICS
270 STAMCOUNTER StatMMIOReadGC;
271 STAMCOUNTER StatMMIOReadHC;
272 STAMCOUNTER StatMMIOWriteGC;
273 STAMCOUNTER StatMMIOWriteHC;
274 STAMCOUNTER StatSetIrqGC;
275 STAMCOUNTER StatSetIrqHC;
276# endif
277};
278
279typedef struct IOAPICState IOAPICState;
280
281typedef struct
282{
283 /** The device instance - R3 Ptr. */
284 PPDMDEVINSR3 pDevInsR3;
285 /** The APIC helpers - R3 Ptr. */
286 PCPDMAPICHLPR3 pApicHlpR3;
287 /** LAPICs states - R3 Ptr */
288 R3PTRTYPE(APICState *) paLapicsR3;
289 /** The critical section - R3 Ptr. */
290 R3PTRTYPE(PPDMCRITSECT) pCritSectR3;
291
292 /** The device instance - R0 Ptr. */
293 PPDMDEVINSR0 pDevInsR0;
294 /** The APIC helpers - R0 Ptr. */
295 PCPDMAPICHLPR0 pApicHlpR0;
296 /** LAPICs states - R0 Ptr */
297 R0PTRTYPE(APICState *) paLapicsR0;
298 /** The critical section - R3 Ptr. */
299 R0PTRTYPE(PPDMCRITSECT) pCritSectR0;
300
301 /** The device instance - RC Ptr. */
302 PPDMDEVINSRC pDevInsRC;
303 /** The APIC helpers - RC Ptr. */
304 PCPDMAPICHLPRC pApicHlpRC;
305 /** LAPICs states - RC Ptr */
306 RCPTRTYPE(APICState *) paLapicsRC;
307 /** The critical section - R3 Ptr. */
308 RCPTRTYPE(PPDMCRITSECT) pCritSectRC;
309
310 /** APIC specification version in this virtual hardware configuration. */
311 PDMAPICVERSION enmVersion;
312
313 /** Number of attempts made to optimize TPR accesses. */
314 uint32_t cTPRPatchAttempts;
315
316 /** Number of CPUs on the system (same as LAPIC count). */
317 uint32_t cCpus;
318 /** Whether we've got an IO APIC or not. */
319 bool fIoApic;
320 /** Alignment padding. */
321 bool afPadding[3];
322
323# ifdef VBOX_WITH_STATISTICS
324 STAMCOUNTER StatMMIOReadGC;
325 STAMCOUNTER StatMMIOReadHC;
326 STAMCOUNTER StatMMIOWriteGC;
327 STAMCOUNTER StatMMIOWriteHC;
328 STAMCOUNTER StatClearedActiveIrq;
329# endif
330} APICDeviceInfo;
331# ifdef VBOX_WITH_STATISTICS
332AssertCompileMemberAlignment(APICDeviceInfo, StatMMIOReadGC, 8);
333# endif
334
335#ifndef VBOX_DEVICE_STRUCT_TESTCASE
336
337/*******************************************************************************
338* Internal Functions *
339*******************************************************************************/
340RT_C_DECLS_BEGIN
341PDMBOTHCBDECL(int) apicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb);
342PDMBOTHCBDECL(int) apicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb);
343PDMBOTHCBDECL(int) apicGetInterrupt(PPDMDEVINS pDevIns);
344PDMBOTHCBDECL(bool) apicHasPendingIrq(PPDMDEVINS pDevIns);
345PDMBOTHCBDECL(void) apicSetBase(PPDMDEVINS pDevIns, uint64_t val);
346PDMBOTHCBDECL(uint64_t) apicGetBase(PPDMDEVINS pDevIns);
347PDMBOTHCBDECL(void) apicSetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t val);
348PDMBOTHCBDECL(uint8_t) apicGetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu);
349PDMBOTHCBDECL(int) apicBusDeliverCallback(PPDMDEVINS pDevIns, uint8_t u8Dest, uint8_t u8DestMode,
350 uint8_t u8DeliveryMode, uint8_t iVector, uint8_t u8Polarity,
351 uint8_t u8TriggerMode);
352PDMBOTHCBDECL(int) apicLocalInterrupt(PPDMDEVINS pDevIns, uint8_t u8Pin, uint8_t u8Level);
353PDMBOTHCBDECL(int) apicWriteMSR(PPDMDEVINS pDevIns, VMCPUID iCpu, uint32_t u32Reg, uint64_t u64Value);
354PDMBOTHCBDECL(int) apicReadMSR(PPDMDEVINS pDevIns, VMCPUID iCpu, uint32_t u32Reg, uint64_t *pu64Value);
355PDMBOTHCBDECL(int) ioapicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb);
356PDMBOTHCBDECL(int) ioapicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb);
357PDMBOTHCBDECL(void) ioapicSetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel);
358PDMBOTHCBDECL(void) ioapicSendMsi(PPDMDEVINS pDevIns, RTGCPHYS GCAddr, uint32_t uValue);
359
360static void apic_update_tpr(APICDeviceInfo *dev, APICState* s, uint32_t val);
361RT_C_DECLS_END
362
363static void apic_eoi(APICDeviceInfo *dev, APICState* s); /* */
364static uint32_t apic_get_delivery_bitmask(APICDeviceInfo* dev, uint8_t dest, uint8_t dest_mode);
365static int apic_deliver(APICDeviceInfo* dev, APICState *s,
366 uint8_t dest, uint8_t dest_mode,
367 uint8_t delivery_mode, uint8_t vector_num,
368 uint8_t polarity, uint8_t trigger_mode);
369static int apic_get_arb_pri(APICState *s);
370static int apic_get_ppr(APICState *s);
371static uint32_t apic_get_current_count(APICDeviceInfo* dev, APICState *s);
372static void apicTimerSetInitialCount(APICDeviceInfo *dev, APICState *s, uint32_t initial_count);
373static void apicTimerSetLvt(APICDeviceInfo *dev, APICState *pThis, uint32_t fNew);
374static void apicSendInitIpi(APICDeviceInfo* dev, APICState *s);
375
376static void apic_init_ipi(APICDeviceInfo* dev, APICState *s);
377static void apic_set_irq(APICDeviceInfo* dev, APICState *s, int vector_num, int trigger_mode);
378static bool apic_update_irq(APICDeviceInfo* dev, APICState *s);
379
380
381DECLINLINE(APICState*) getLapicById(APICDeviceInfo* dev, VMCPUID id)
382{
383 AssertFatalMsg(id < dev->cCpus, ("CPU id %d out of range\n", id));
384 return &dev->CTX_SUFF(paLapics)[id];
385}
386
387DECLINLINE(APICState*) getLapic(APICDeviceInfo* dev)
388{
389 /* LAPIC's array is indexed by CPU id */
390 VMCPUID id = dev->CTX_SUFF(pApicHlp)->pfnGetCpuId(dev->CTX_SUFF(pDevIns));
391 return getLapicById(dev, id);
392}
393
394DECLINLINE(VMCPUID) getCpuFromLapic(APICDeviceInfo* dev, APICState *s)
395{
396 /* for now we assume LAPIC physical id == CPU id */
397 return VMCPUID(s->phys_id);
398}
399
400DECLINLINE(void) cpuSetInterrupt(APICDeviceInfo* dev, APICState *s, PDMAPICIRQ enmType = PDMAPICIRQ_HARDWARE)
401{
402 LogFlow(("apic: setting interrupt flag for cpu %d\n", getCpuFromLapic(dev, s)));
403 dev->CTX_SUFF(pApicHlp)->pfnSetInterruptFF(dev->CTX_SUFF(pDevIns), enmType,
404 getCpuFromLapic(dev, s));
405}
406
407DECLINLINE(void) cpuClearInterrupt(APICDeviceInfo* dev, APICState *s, PDMAPICIRQ enmType = PDMAPICIRQ_HARDWARE)
408{
409 LogFlow(("apic: clear interrupt flag\n"));
410 dev->CTX_SUFF(pApicHlp)->pfnClearInterruptFF(dev->CTX_SUFF(pDevIns), enmType,
411 getCpuFromLapic(dev, s));
412}
413
414# ifdef IN_RING3
415
416DECLINLINE(void) cpuSendSipi(APICDeviceInfo* dev, APICState *s, int vector)
417{
418 Log2(("apic: send SIPI vector=%d\n", vector));
419
420 dev->pApicHlpR3->pfnSendSipi(dev->pDevInsR3,
421 getCpuFromLapic(dev, s),
422 vector);
423}
424
425DECLINLINE(void) cpuSendInitIpi(APICDeviceInfo* dev, APICState *s)
426{
427 Log2(("apic: send init IPI\n"));
428
429 dev->pApicHlpR3->pfnSendInitIpi(dev->pDevInsR3,
430 getCpuFromLapic(dev, s));
431}
432
433# endif /* IN_RING3 */
434
435DECLINLINE(uint32_t) getApicEnableBits(APICDeviceInfo* dev)
436{
437 switch (dev->enmVersion)
438 {
439 case PDMAPICVERSION_NONE:
440 return 0;
441 case PDMAPICVERSION_APIC:
442 return MSR_IA32_APICBASE_ENABLE;
443 case PDMAPICVERSION_X2APIC:
444 return MSR_IA32_APICBASE_ENABLE | MSR_IA32_APICBASE_X2ENABLE ;
445 default:
446 AssertMsgFailed(("Unsuported APIC version %d\n", dev->enmVersion));
447 return 0;
448 }
449}
450
451DECLINLINE(PDMAPICVERSION) getApicMode(APICState *apic)
452{
453 switch (((apic->apicbase) >> 10) & 0x3)
454 {
455 case 0:
456 return PDMAPICVERSION_NONE;
457 case 1:
458 default:
459 /* Invalid */
460 return PDMAPICVERSION_NONE;
461 case 2:
462 return PDMAPICVERSION_APIC;
463 case 3:
464 return PDMAPICVERSION_X2APIC;
465 }
466}
467
468static int apic_bus_deliver(APICDeviceInfo* dev,
469 uint32_t deliver_bitmask, uint8_t delivery_mode,
470 uint8_t vector_num, uint8_t polarity,
471 uint8_t trigger_mode)
472{
473 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));
474 switch (delivery_mode) {
475 case APIC_DM_LOWPRI:
476 {
477 int d = -1;
478 if (deliver_bitmask)
479 d = ffs_bit(deliver_bitmask);
480 if (d >= 0)
481 {
482 APICState* apic = getLapicById(dev, d);
483 apic_set_irq(dev, apic, vector_num, trigger_mode);
484 }
485 return VINF_SUCCESS;
486 }
487 case APIC_DM_FIXED:
488 /* XXX: arbitration */
489 break;
490
491 case APIC_DM_SMI:
492 foreach_apic(dev, deliver_bitmask,
493 cpuSetInterrupt(dev, apic, PDMAPICIRQ_SMI));
494 return VINF_SUCCESS;
495
496 case APIC_DM_NMI:
497 foreach_apic(dev, deliver_bitmask,
498 cpuSetInterrupt(dev, apic, PDMAPICIRQ_NMI));
499 return VINF_SUCCESS;
500
501 case APIC_DM_INIT:
502 /* normal INIT IPI sent to processors */
503#ifdef IN_RING3
504 foreach_apic(dev, deliver_bitmask,
505 apicSendInitIpi(dev, apic));
506 return VINF_SUCCESS;
507#else
508 /* We shall send init IPI only in R3, R0 calls should be
509 rescheduled to R3 */
510 return VINF_IOM_HC_MMIO_READ_WRITE;
511#endif /* IN_RING3 */
512 case APIC_DM_EXTINT:
513 /* handled in I/O APIC code */
514 break;
515
516 default:
517 return VINF_SUCCESS;
518 }
519
520 foreach_apic(dev, deliver_bitmask,
521 apic_set_irq (dev, apic, vector_num, trigger_mode));
522 return VINF_SUCCESS;
523}
524
525
526PDMBOTHCBDECL(void) apicSetBase(PPDMDEVINS pDevIns, uint64_t val)
527{
528 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
529 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
530 APICState *s = getLapic(dev); /** @todo fix interface */
531 Log(("apicSetBase: %016RX64\n", val));
532
533 /** @todo: do we need to lock here ? */
534 /* APIC_LOCK_VOID(dev, VERR_INTERNAL_ERROR); */
535 /** @todo If this change is valid immediately, then we should change the MMIO registration! */
536 /* We cannot change if this CPU is BSP or not by writing to MSR - it's hardwired */
537 PDMAPICVERSION oldMode = getApicMode(s);
538 s->apicbase =
539 (val & 0xfffff000) | /* base */
540 (val & getApicEnableBits(dev)) | /* mode */
541 (s->apicbase & MSR_IA32_APICBASE_BSP) /* keep BSP bit */;
542 PDMAPICVERSION newMode = getApicMode(s);
543
544 if (oldMode != newMode)
545 {
546 switch (newMode)
547 {
548 case PDMAPICVERSION_NONE:
549 {
550 s->spurious_vec &= ~APIC_SV_ENABLE;
551 /* Clear any pending APIC interrupt action flag. */
552 cpuClearInterrupt(dev, s);
553 /** @todo: why do we do that? */
554 dev->CTX_SUFF(pApicHlp)->pfnChangeFeature(pDevIns, PDMAPICVERSION_NONE);
555 break;
556 }
557 case PDMAPICVERSION_APIC:
558 /** @todo: map MMIO ranges, if needed */
559 break;
560 case PDMAPICVERSION_X2APIC:
561 /** @todo: unmap MMIO ranges of this APIC, according to the spec */
562 break;
563 default:
564 break;
565 }
566 }
567 /* APIC_UNLOCK(dev); */
568}
569
570PDMBOTHCBDECL(uint64_t) apicGetBase(PPDMDEVINS pDevIns)
571{
572 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
573 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
574 APICState *s = getLapic(dev); /** @todo fix interface */
575 LogFlow(("apicGetBase: %016llx\n", (uint64_t)s->apicbase));
576 return s->apicbase;
577}
578
579PDMBOTHCBDECL(void) apicSetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint8_t val)
580{
581 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
582 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
583 APICState *s = getLapicById(dev, idCpu);
584 LogFlow(("apicSetTPR: val=%#x (trp %#x -> %#x)\n", val, s->tpr, val));
585 apic_update_tpr(dev, s, val);
586}
587
588PDMBOTHCBDECL(uint8_t) apicGetTPR(PPDMDEVINS pDevIns, VMCPUID idCpu)
589{
590 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
591 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
592 APICState *s = getLapicById(dev, idCpu);
593 Log2(("apicGetTPR: returns %#x\n", s->tpr));
594 return s->tpr;
595}
596
597/**
598 * x2APIC MSR write interface.
599 *
600 * @returns VBox status code.
601 *
602 * @param pDevIns The device instance.
603 * @param idCpu The ID of the virtual CPU and thereby APIC index.
604 * @param u32Reg Register to write (ecx).
605 * @param u64Value The value to write (eax:edx / rax).
606 *
607 */
608PDMBOTHCBDECL(int) apicWriteMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t u64Value)
609{
610 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
611 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
612 int rc = VINF_SUCCESS;
613
614 if (dev->enmVersion < PDMAPICVERSION_X2APIC)
615 return VERR_EM_INTERPRETER;
616
617 APICState *pThis = getLapicById(dev, idCpu);
618
619 uint32_t index = (u32Reg - MSR_IA32_APIC_START) & 0xff;
620 switch (index)
621 {
622 case 0x02:
623 pThis->id = (u64Value >> 24);
624 break;
625 case 0x03:
626 break;
627 case 0x08:
628 apic_update_tpr(dev, pThis, u64Value);
629 break;
630 case 0x09: case 0x0a:
631 Log(("apicWriteMSR: write to read-only register %d ignored\n", index));
632 break;
633 case 0x0b: /* EOI */
634 apic_eoi(dev, pThis);
635 break;
636 case 0x0d:
637 pThis->log_dest = u64Value >> 24;
638 break;
639 case 0x0e:
640 pThis->dest_mode = u64Value >> 28;
641 break;
642 case 0x0f:
643 pThis->spurious_vec = u64Value & 0x1ff;
644 apic_update_irq(dev, pThis);
645 break;
646 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
647 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
648 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
649 case 0x28:
650 Log(("apicWriteMSR: write to read-only register %d ignored\n", index));
651 break;
652
653 case 0x30:
654 /* Here one of the differences with regular APIC: ICR is single 64-bit register */
655 pThis->icr[0] = (uint32_t)u64Value;
656 pThis->icr[1] = (uint32_t)(u64Value >> 32);
657 rc = apic_deliver(dev, pThis, (pThis->icr[1] >> 24) & 0xff, (pThis->icr[0] >> 11) & 1,
658 (pThis->icr[0] >> 8) & 7, (pThis->icr[0] & 0xff),
659 (pThis->icr[0] >> 14) & 1, (pThis->icr[0] >> 15) & 1);
660 break;
661 case 0x32 + APIC_LVT_TIMER:
662 AssertCompile(APIC_LVT_TIMER == 0);
663 apicTimerSetLvt(dev, pThis, u64Value);
664 break;
665
666 case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
667 pThis->lvt[index - 0x32] = u64Value;
668 break;
669 case 0x38:
670 apicTimerSetInitialCount(dev, pThis, u64Value);
671 break;
672 case 0x39:
673 Log(("apicWriteMSR: write to read-only register %d ignored\n", index));
674 break;
675 case 0x3e:
676 {
677 int v;
678 pThis->divide_conf = u64Value & 0xb;
679 v = (pThis->divide_conf & 3) | ((pThis->divide_conf >> 1) & 4);
680 pThis->count_shift = (v + 1) & 7;
681 break;
682 }
683 case 0x3f:
684 {
685 /* Self IPI, see x2APIC book 2.4.5 */
686 int vector = u64Value & 0xff;
687 rc = apic_bus_deliver(dev,
688 1 << getLapicById(dev, idCpu)->id /* Self */,
689 0 /* Delivery mode - fixed */,
690 vector,
691 0 /* Polarity - conform to the bus */,
692 0 /* Trigger mode - edge */);
693 break;
694 }
695 default:
696 AssertMsgFailed(("apicWriteMSR: unknown index %x\n", index));
697 pThis->esr |= ESR_ILLEGAL_ADDRESS;
698 break;
699 }
700
701 return rc;
702}
703
704/**
705 * x2APIC MSR read interface.
706 *
707 * @returns VBox status code.
708 *
709 * @param pDevIns The device instance.
710 * @param idCpu The ID of the virtual CPU and thereby APIC index.
711 * @param u32Reg Register to write (ecx).
712 * @param pu64Value Where to return the value (eax:edx / rax).
713 */
714PDMBOTHCBDECL(int) apicReadMSR(PPDMDEVINS pDevIns, VMCPUID idCpu, uint32_t u32Reg, uint64_t *pu64Value)
715{
716 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
717 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
718
719 if (dev->enmVersion < PDMAPICVERSION_X2APIC)
720 return VERR_EM_INTERPRETER;
721
722 uint32_t index = (u32Reg - MSR_IA32_APIC_START) & 0xff;
723 APICState* apic = getLapicById(dev, idCpu);
724 uint64_t val = 0;
725
726 switch (index)
727 {
728 case 0x02: /* id */
729 val = apic->id << 24;
730 break;
731 case 0x03: /* version */
732 val = APIC_HW_VERSION |
733 ((APIC_LVT_NB - 1) << 16) /* Max LVT index */ |
734 (0 << 24) /* Support for EOI broadcast supression */;
735 break;
736 case 0x08:
737 val = apic->tpr;
738 break;
739 case 0x09:
740 val = apic_get_arb_pri(apic);
741 break;
742 case 0x0a:
743 /* ppr */
744 val = apic_get_ppr(apic);
745 break;
746 case 0x0b:
747 val = 0;
748 break;
749 case 0x0d:
750 val = (uint64_t)apic->log_dest << 24;
751 break;
752 case 0x0e:
753 /* Bottom 28 bits are always 1 */
754 val = ((uint64_t)apic->dest_mode << 28) | 0xfffffff;
755 break;
756 case 0x0f:
757 val = apic->spurious_vec;
758 break;
759 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
760 val = apic->isr[index & 7];
761 break;
762 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
763 val = apic->tmr[index & 7];
764 break;
765 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
766 val = apic->irr[index & 7];
767 break;
768 case 0x28:
769 val = apic->esr;
770 break;
771 case 0x30:
772 /* Here one of the differences with regular APIC: ICR is single 64-bit register */
773 val = ((uint64_t)apic->icr[1] << 32) | apic->icr[0];
774 break;
775 case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
776 val = apic->lvt[index - 0x32];
777 break;
778 case 0x38:
779 val = apic->initial_count;
780 break;
781 case 0x39:
782 val = apic_get_current_count(dev, apic);
783 break;
784 case 0x3e:
785 val = apic->divide_conf;
786 break;
787 case 0x3f:
788 /* Self IPI register is write only */
789 Log(("apicReadMSR: read from write-only register %d ignored\n", index));
790 break;
791 case 0x2f:
792 /**
793 * Correctable machine check exception vector, @todo: implement me!
794 */
795 default:
796 AssertMsgFailed(("apicReadMSR: unknown index %x\n", index));
797 /**
798 * @todo: according to spec when APIC writes to ESR it msut raise error interrupt,
799 * i.e. LVT[5]
800 */
801 apic->esr |= ESR_ILLEGAL_ADDRESS;
802 val = 0;
803 break;
804 }
805 *pu64Value = val;
806 return VINF_SUCCESS;
807}
808
809/**
810 * More or less private interface between IOAPIC, only PDM is responsible
811 * for connecting the two devices.
812 */
813PDMBOTHCBDECL(int) apicBusDeliverCallback(PPDMDEVINS pDevIns, uint8_t u8Dest, uint8_t u8DestMode,
814 uint8_t u8DeliveryMode, uint8_t iVector, uint8_t u8Polarity,
815 uint8_t u8TriggerMode)
816{
817 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
818 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
819 LogFlow(("apicBusDeliverCallback: pDevIns=%p u8Dest=%#x u8DestMode=%#x u8DeliveryMode=%#x iVector=%#x u8Polarity=%#x u8TriggerMode=%#x\n",
820 pDevIns, u8Dest, u8DestMode, u8DeliveryMode, iVector, u8Polarity, u8TriggerMode));
821 return apic_bus_deliver(dev, apic_get_delivery_bitmask(dev, u8Dest, u8DestMode),
822 u8DeliveryMode, iVector, u8Polarity, u8TriggerMode);
823}
824
825/**
826 * Local interrupt delivery, for devices attached to the CPU's LINT0/LINT1 pin.
827 * Normally used for 8259A PIC and NMI.
828 */
829PDMBOTHCBDECL(int) apicLocalInterrupt(PPDMDEVINS pDevIns, uint8_t u8Pin, uint8_t u8Level)
830{
831 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
832 APICState *s = getLapicById(dev, 0);
833
834 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
835 LogFlow(("apicLocalInterrupt: pDevIns=%p u8Pin=%x u8Level=%x\n", pDevIns, u8Pin, u8Level));
836
837 /* If LAPIC is disabled, go straight to the CPU. */
838 if (!(s->spurious_vec & APIC_SV_ENABLE))
839 {
840 LogFlow(("apicLocalInterrupt: LAPIC disabled, delivering directly to CPU core.\n"));
841 if (u8Level)
842 cpuSetInterrupt(dev, s, PDMAPICIRQ_EXTINT);
843 else
844 cpuClearInterrupt(dev, s, PDMAPICIRQ_EXTINT);
845
846 return VINF_SUCCESS;
847 }
848
849 /* If LAPIC is enabled, interrupts are subject to LVT programming. */
850
851 /* There are only two local interrupt pins. */
852 AssertMsgReturn(u8Pin <= 1, ("Invalid LAPIC pin %d\n", u8Pin), VERR_INVALID_PARAMETER);
853
854 /* NB: We currently only deliver local interrupts to the first CPU. In theory they
855 * should be delivered to all CPUs and it is the guest's responsibility to ensure
856 * no more than one CPU has the interrupt unmasked.
857 */
858 uint32_t u32Lvec;
859
860 u32Lvec = s->lvt[APIC_LVT_LINT0 + u8Pin]; /* Fetch corresponding LVT entry. */
861 /* Drop int if entry is masked. May not be correct for level-triggered interrupts. */
862 if (!(u32Lvec & APIC_LVT_MASKED))
863 { uint8_t u8Delivery;
864 PDMAPICIRQ enmType;
865
866 u8Delivery = (u32Lvec >> 8) & 7;
867 switch (u8Delivery)
868 {
869 case APIC_DM_EXTINT:
870 Assert(u8Pin == 0); /* PIC should be wired to LINT0. */
871 enmType = PDMAPICIRQ_EXTINT;
872 /* ExtINT can be both set and cleared, NMI/SMI/INIT can only be set. */
873 LogFlow(("apicLocalInterrupt: %s ExtINT interrupt\n", u8Level ? "setting" : "clearing"));
874 if (u8Level)
875 cpuSetInterrupt(dev, s, enmType);
876 else
877 cpuClearInterrupt(dev, s, enmType);
878 return VINF_SUCCESS;
879 case APIC_DM_NMI:
880 /* External NMI should be wired to LINT1, but Linux sometimes programs
881 * LVT0 to NMI delivery mode as well.
882 */
883 enmType = PDMAPICIRQ_NMI;
884 /* Currently delivering NMIs through here causes problems with NMI watchdogs
885 * on certain Linux kernels, e.g. 64-bit CentOS 5.3. Disable NMIs for now.
886 */
887 return VINF_SUCCESS;
888 case APIC_DM_SMI:
889 enmType = PDMAPICIRQ_SMI;
890 break;
891 case APIC_DM_FIXED:
892 {
893 /** @todo implement APIC_DM_FIXED! */
894 static unsigned s_c = 0;
895 if (s_c++ < 5)
896 LogRel(("delivery type APIC_DM_FIXED not implemented. u8Pin=%d u8Level=%d\n", u8Pin, u8Level));
897 return VINF_SUCCESS;
898 }
899 case APIC_DM_INIT:
900 /** @todo implement APIC_DM_INIT? */
901 default:
902 {
903 static unsigned s_c = 0;
904 if (s_c++ < 100)
905 AssertLogRelMsgFailed(("delivery type %d not implemented. u8Pin=%d u8Level=%d\n", u8Delivery, u8Pin, u8Level));
906 return VERR_INTERNAL_ERROR_4;
907 }
908 }
909 LogFlow(("apicLocalInterrupt: setting local interrupt type %d\n", enmType));
910 cpuSetInterrupt(dev, s, enmType);
911 }
912 return VINF_SUCCESS;
913}
914
915/* return -1 if no bit is set */
916static int get_highest_priority_int(uint32_t *tab)
917{
918 int i;
919 for(i = 7; i >= 0; i--) {
920 if (tab[i] != 0) {
921 return i * 32 + fls_bit(tab[i]);
922 }
923 }
924 return -1;
925}
926
927static int apic_get_ppr(APICState *s)
928{
929 int tpr, isrv, ppr;
930
931 tpr = (s->tpr >> 4);
932 isrv = get_highest_priority_int(s->isr);
933 if (isrv < 0)
934 isrv = 0;
935 isrv >>= 4;
936 if (tpr >= isrv)
937 ppr = s->tpr;
938 else
939 ppr = isrv << 4;
940 return ppr;
941}
942
943static int apic_get_ppr_zero_tpr(APICState *s)
944{
945 int isrv;
946
947 isrv = get_highest_priority_int(s->isr);
948 if (isrv < 0)
949 isrv = 0;
950 return isrv;
951}
952
953static int apic_get_arb_pri(APICState *s)
954{
955 /* XXX: arbitration */
956 return 0;
957}
958
959/* signal the CPU if an irq is pending */
960static bool apic_update_irq(APICDeviceInfo *dev, APICState* s)
961{
962 int irrv, ppr;
963 if (!(s->spurious_vec & APIC_SV_ENABLE))
964 {
965 /* Clear any pending APIC interrupt action flag. */
966 cpuClearInterrupt(dev, s);
967 return false;
968 }
969
970 irrv = get_highest_priority_int(s->irr);
971 if (irrv < 0)
972 return false;
973 ppr = apic_get_ppr(s);
974 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
975 return false;
976 cpuSetInterrupt(dev, s);
977 return true;
978}
979
980/* Check if the APIC has a pending interrupt/if a TPR change would active one. */
981PDMBOTHCBDECL(bool) apicHasPendingIrq(PPDMDEVINS pDevIns)
982{
983 int irrv, ppr;
984 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
985 if (!dev)
986 return false;
987
988 /* We don't perform any locking here as that would cause a lot of contention for VT-x/AMD-V. */
989
990 APICState *s = getLapic(dev); /** @todo fix interface */
991
992 /*
993 * All our callbacks now come from single IOAPIC, thus locking
994 * seems to be excessive now (@todo: check)
995 */
996 irrv = get_highest_priority_int(s->irr);
997 if (irrv < 0)
998 return false;
999
1000 ppr = apic_get_ppr_zero_tpr(s);
1001
1002 if (ppr && (irrv & 0xf0) <= (ppr & 0xf0))
1003 return false;
1004
1005 return true;
1006}
1007
1008static void apic_update_tpr(APICDeviceInfo *dev, APICState* s, uint32_t val)
1009{
1010 bool fIrqIsActive = false;
1011 bool fIrqWasActive = false;
1012
1013 fIrqWasActive = apic_update_irq(dev, s);
1014 s->tpr = val;
1015 fIrqIsActive = apic_update_irq(dev, s);
1016
1017 /* If an interrupt is pending and now masked, then clear the FF flag. */
1018 if (fIrqWasActive && !fIrqIsActive)
1019 {
1020 Log(("apic_update_tpr: deactivate interrupt that was masked by the TPR update (%x)\n", val));
1021 STAM_COUNTER_INC(&dev->StatClearedActiveIrq);
1022 cpuClearInterrupt(dev, s);
1023 }
1024}
1025
1026static void apic_set_irq(APICDeviceInfo *dev, APICState* s, int vector_num, int trigger_mode)
1027{
1028 LogFlow(("CPU%d: apic_set_irq vector=%x, trigger_mode=%x\n", s->phys_id, vector_num, trigger_mode));
1029 set_bit(s->irr, vector_num);
1030 if (trigger_mode)
1031 set_bit(s->tmr, vector_num);
1032 else
1033 reset_bit(s->tmr, vector_num);
1034 apic_update_irq(dev, s);
1035}
1036
1037static void apic_eoi(APICDeviceInfo *dev, APICState* s)
1038{
1039 int isrv;
1040 isrv = get_highest_priority_int(s->isr);
1041 if (isrv < 0)
1042 return;
1043 reset_bit(s->isr, isrv);
1044 LogFlow(("CPU%d: apic_eoi isrv=%x\n", s->phys_id, isrv));
1045 /* XXX: send the EOI packet to the APIC bus to allow the I/O APIC to
1046 set the remote IRR bit for level triggered interrupts. */
1047 apic_update_irq(dev, s);
1048}
1049
1050static uint32_t apic_get_delivery_bitmask(APICDeviceInfo *dev, uint8_t dest, uint8_t dest_mode)
1051{
1052 uint32_t mask = 0;
1053
1054 if (dest_mode == 0)
1055 {
1056 if (dest == 0xff)
1057 mask = 0xff;
1058 else
1059 mask = 1 << dest;
1060 }
1061 else
1062 {
1063 APICState *apic = dev->CTX_SUFF(paLapics);
1064 uint32_t i;
1065
1066 /* XXX: cluster mode */
1067 for(i = 0; i < dev->cCpus; i++)
1068 {
1069 if (apic->dest_mode == APIC_DESTMODE_FLAT)
1070 {
1071 if (dest & apic->log_dest)
1072 mask |= (1 << i);
1073 }
1074 else if (apic->dest_mode == APIC_DESTMODE_CLUSTER)
1075 {
1076 if ((dest & 0xf0) == (apic->log_dest & 0xf0)
1077 &&
1078 (dest & apic->log_dest & 0x0f))
1079 {
1080 mask |= (1 << i);
1081 }
1082 }
1083 apic++;
1084 }
1085 }
1086
1087 return mask;
1088}
1089
1090#ifdef IN_RING3
1091static void apic_init_ipi(APICDeviceInfo* dev, APICState *s)
1092{
1093 int i;
1094
1095 for(i = 0; i < APIC_LVT_NB; i++)
1096 s->lvt[i] = 1 << 16; /* mask LVT */
1097 s->tpr = 0;
1098 s->spurious_vec = 0xff;
1099 s->log_dest = 0;
1100 s->dest_mode = 0xff;
1101 memset(s->isr, 0, sizeof(s->isr));
1102 memset(s->tmr, 0, sizeof(s->tmr));
1103 memset(s->irr, 0, sizeof(s->irr));
1104 s->esr = 0;
1105 memset(s->icr, 0, sizeof(s->icr));
1106 s->divide_conf = 0;
1107 s->count_shift = 0;
1108 s->initial_count = 0;
1109 s->initial_count_load_time = 0;
1110 s->next_time = 0;
1111}
1112
1113
1114static void apicSendInitIpi(APICDeviceInfo* dev, APICState *s)
1115{
1116 apic_init_ipi(dev, s);
1117 cpuSendInitIpi(dev, s);
1118}
1119
1120/* send a SIPI message to the CPU to start it */
1121static void apic_startup(APICDeviceInfo* dev, APICState *s, int vector_num)
1122{
1123 Log(("[SMP] apic_startup: %d on CPUs %d\n", vector_num, s->phys_id));
1124 cpuSendSipi(dev, s, vector_num);
1125}
1126#endif /* IN_RING3 */
1127
1128static int apic_deliver(APICDeviceInfo* dev, APICState *s,
1129 uint8_t dest, uint8_t dest_mode,
1130 uint8_t delivery_mode, uint8_t vector_num,
1131 uint8_t polarity, uint8_t trigger_mode)
1132{
1133 uint32_t deliver_bitmask = 0;
1134 int dest_shorthand = (s->icr[0] >> 18) & 3;
1135
1136 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));
1137
1138 switch (dest_shorthand) {
1139 case 0:
1140 deliver_bitmask = apic_get_delivery_bitmask(dev, dest, dest_mode);
1141 break;
1142 case 1:
1143 deliver_bitmask = (1 << s->id);
1144 break;
1145 case 2:
1146 deliver_bitmask = 0xffffffff;
1147 break;
1148 case 3:
1149 deliver_bitmask = 0xffffffff & ~(1 << s->id);
1150 break;
1151 }
1152
1153 switch (delivery_mode) {
1154 case APIC_DM_INIT:
1155 {
1156 int trig_mode = (s->icr[0] >> 15) & 1;
1157 int level = (s->icr[0] >> 14) & 1;
1158 if (level == 0 && trig_mode == 1) {
1159 foreach_apic(dev, deliver_bitmask,
1160 apic->arb_id = apic->id);
1161 Log(("CPU%d: APIC_DM_INIT arbitration id(s) set\n", s->phys_id));
1162 return VINF_SUCCESS;
1163 }
1164 }
1165 break;
1166
1167 case APIC_DM_SIPI:
1168# ifdef IN_RING3
1169 foreach_apic(dev, deliver_bitmask,
1170 apic_startup(dev, apic, vector_num));
1171 return VINF_SUCCESS;
1172# else
1173 /* We shall send SIPI only in R3, R0 calls should be
1174 rescheduled to R3 */
1175 return VINF_IOM_HC_MMIO_WRITE;
1176# endif
1177 }
1178
1179 return apic_bus_deliver(dev, deliver_bitmask, delivery_mode, vector_num,
1180 polarity, trigger_mode);
1181}
1182
1183
1184PDMBOTHCBDECL(int) apicGetInterrupt(PPDMDEVINS pDevIns)
1185{
1186 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1187 /* if the APIC is not installed or enabled, we let the 8259 handle the
1188 IRQs */
1189 if (!dev)
1190 {
1191 Log(("apic_get_interrupt: returns -1 (!s)\n"));
1192 return -1;
1193 }
1194
1195 Assert(PDMCritSectIsOwner(dev->CTX_SUFF(pCritSect)));
1196
1197 APICState *s = getLapic(dev); /** @todo fix interface */
1198 int intno;
1199
1200 if (!(s->spurious_vec & APIC_SV_ENABLE)) {
1201 Log(("CPU%d: apic_get_interrupt: returns -1 (APIC_SV_ENABLE)\n", s->phys_id));
1202 return -1;
1203 }
1204
1205 /* XXX: spurious IRQ handling */
1206 intno = get_highest_priority_int(s->irr);
1207 if (intno < 0) {
1208 Log(("CPU%d: apic_get_interrupt: returns -1 (irr)\n", s->phys_id));
1209 return -1;
1210 }
1211 if (s->tpr && (uint32_t)intno <= s->tpr) {
1212 Log(("apic_get_interrupt: returns %d (sp)\n", s->spurious_vec & 0xff));
1213 return s->spurious_vec & 0xff;
1214 }
1215 reset_bit(s->irr, intno);
1216 set_bit(s->isr, intno);
1217 apic_update_irq(dev, s);
1218 LogFlow(("CPU%d: apic_get_interrupt: returns %d\n", s->phys_id, intno));
1219 return intno;
1220}
1221
1222static uint32_t apic_get_current_count(APICDeviceInfo *dev, APICState *s)
1223{
1224 int64_t d;
1225 uint32_t val;
1226
1227 d = (TMTimerGet(s->CTX_SUFF(pTimer)) - s->initial_count_load_time) >>
1228 s->count_shift;
1229
1230 if (s->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC) {
1231 /* periodic */
1232 val = s->initial_count - (d % ((uint64_t)s->initial_count + 1));
1233 } else {
1234 if (d >= s->initial_count)
1235 val = 0;
1236 else
1237 val = s->initial_count - d;
1238 }
1239 return val;
1240}
1241
1242/**
1243 * Does the frequency hinting and logging.
1244 *
1245 * @param pThis The device state.
1246 */
1247DECLINLINE(void) apicDoFrequencyHinting(APICState *pThis)
1248{
1249 if ( pThis->uHintedInitialCount != pThis->initial_count
1250 || pThis->uHintedCountShift != (uint32_t)pThis->count_shift)
1251 {
1252 pThis->uHintedInitialCount = pThis->initial_count;
1253 pThis->uHintedCountShift = pThis->count_shift;
1254
1255 uint64_t cTickPerPeriod = (uint64_t)pThis->initial_count << pThis->count_shift;
1256 uint32_t uHz = cTickPerPeriod > 0
1257 ? TMTimerGetFreq(pThis->CTX_SUFF(pTimer)) / cTickPerPeriod
1258 : 100 /*whatever*/;
1259 TMTimerSetFrequencyHint(pThis->CTX_SUFF(pTimer), uHz);
1260 Log(("apic: %u Hz\n", uHz));
1261 }
1262}
1263
1264/**
1265 * Implementation of the 0380h access: Timer reset + new initial count.
1266 *
1267 * @param dev The device state.
1268 * @param pThis The APIC sub-device state.
1269 * @param u32NewInitialCount The new initial count for the timer.
1270 */
1271static void apicTimerSetInitialCount(APICDeviceInfo *dev, APICState *pThis, uint32_t u32NewInitialCount)
1272{
1273 STAM_COUNTER_INC(&pThis->StatTimerSetInitialCount);
1274 pThis->initial_count = u32NewInitialCount;
1275
1276 /*
1277 * Don't (re-)arm the timer if the it's masked or if it's
1278 * a zero length one-shot timer.
1279 */
1280 /** @todo check the correct behavior of setting a 0 initial_count for a one-shot
1281 * timer. This is just copying the behavior of the original code. */
1282 if ( !(pThis->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)
1283 && ( (pThis->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC)
1284 || u32NewInitialCount != 0))
1285 {
1286 /*
1287 * Calculate the relative next time and perform a combined timer get/set
1288 * operation. This avoids racing the clock between get and set.
1289 */
1290 uint64_t cTicksNext = u32NewInitialCount;
1291 cTicksNext += 1;
1292 cTicksNext <<= pThis->count_shift;
1293 TMTimerSetRelative(pThis->CTX_SUFF(pTimer), cTicksNext, &pThis->initial_count_load_time);
1294 pThis->next_time = pThis->initial_count_load_time + cTicksNext;
1295 pThis->fTimerArmed = true;
1296 apicDoFrequencyHinting(pThis);
1297 STAM_COUNTER_INC(&pThis->StatTimerSetInitialCountArm);
1298 }
1299 else
1300 {
1301 /* Stop it if necessary and record the load time for unmasking. */
1302 if (pThis->fTimerArmed)
1303 {
1304 STAM_COUNTER_INC(&pThis->StatTimerSetInitialCountDisarm);
1305 TMTimerStop(pThis->CTX_SUFF(pTimer));
1306 pThis->fTimerArmed = false;
1307 pThis->uHintedCountShift = pThis->uHintedInitialCount = 0;
1308 }
1309 pThis->initial_count_load_time = TMTimerGet(pThis->CTX_SUFF(pTimer));
1310 }
1311}
1312
1313/**
1314 * Implementation of the 0320h access: change the LVT flags.
1315 *
1316 * @param dev The device state.
1317 * @param pThis The APIC sub-device state to operate on.
1318 * @param fNew The new flags.
1319 */
1320static void apicTimerSetLvt(APICDeviceInfo *dev, APICState *pThis, uint32_t fNew)
1321{
1322 STAM_COUNTER_INC(&pThis->StatTimerSetLvt);
1323
1324 /*
1325 * Make the flag change, saving the old ones so we can avoid
1326 * unnecessary work.
1327 */
1328 uint32_t const fOld = pThis->lvt[APIC_LVT_TIMER];
1329 pThis->lvt[APIC_LVT_TIMER] = fNew;
1330
1331 /* Only the masked and peridic bits are relevant (see apic_timer_update). */
1332 if ( (fOld & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC))
1333 != (fNew & (APIC_LVT_MASKED | APIC_LVT_TIMER_PERIODIC)))
1334 {
1335 /*
1336 * If changed to one-shot from periodic, stop the timer if we're not
1337 * in the first period.
1338 */
1339 /** @todo check how clearing the periodic flag really should behave when not
1340 * in period 1. The current code just mirrors the behavior of the
1341 * original implementation. */
1342 if ( (fOld & APIC_LVT_TIMER_PERIODIC)
1343 && !(fNew & APIC_LVT_TIMER_PERIODIC))
1344 {
1345 STAM_COUNTER_INC(&pThis->StatTimerSetLvtClearPeriodic);
1346 uint64_t cTicks = (pThis->next_time - pThis->initial_count_load_time) >> pThis->count_shift;
1347 if (cTicks >= pThis->initial_count)
1348 {
1349 /* not first period, stop it. */
1350 TMTimerStop(pThis->CTX_SUFF(pTimer));
1351 pThis->fTimerArmed = false;
1352 pThis->uHintedCountShift = pThis->uHintedInitialCount = 0;
1353 }
1354 /* else: first period, let it fire normally. */
1355 }
1356
1357 /*
1358 * We postpone stopping the timer when it's masked, this way we can
1359 * avoid some timer work when the guest temporarily masks the timer.
1360 * (apicTimerCallback will stop it if still masked.)
1361 */
1362 if (fNew & APIC_LVT_MASKED)
1363 STAM_COUNTER_INC(&pThis->StatTimerSetLvtPostponed);
1364 else if (pThis->fTimerArmed)
1365 STAM_COUNTER_INC(&pThis->StatTimerSetLvtArmed);
1366 /*
1367 * If unmasked and not armed, we have to rearm the timer so it will
1368 * fire at the end of the current period.
1369 * This is code is currently RACING the virtual sync clock!
1370 */
1371 else if (fOld & APIC_LVT_MASKED)
1372 {
1373 STAM_COUNTER_INC(&pThis->StatTimerSetLvtArm);
1374 for (unsigned cTries = 0; ; cTries++)
1375 {
1376 uint64_t NextTS;
1377 uint64_t cTicks = (TMTimerGet(pThis->CTX_SUFF(pTimer)) - pThis->initial_count_load_time) >> pThis->count_shift;
1378 if (fNew & APIC_LVT_TIMER_PERIODIC)
1379 NextTS = ((cTicks / ((uint64_t)pThis->initial_count + 1)) + 1) * ((uint64_t)pThis->initial_count + 1);
1380 else
1381 {
1382 if (cTicks >= pThis->initial_count)
1383 break;
1384 NextTS = (uint64_t)pThis->initial_count + 1;
1385 }
1386 NextTS <<= pThis->count_shift;
1387 NextTS += pThis->initial_count_load_time;
1388
1389 /* Try avoid the assertion in TM.cpp... this isn't perfect! */
1390 if ( NextTS > TMTimerGet(pThis->CTX_SUFF(pTimer))
1391 || cTries > 10)
1392 {
1393 TMTimerSet(pThis->CTX_SUFF(pTimer), NextTS);
1394 pThis->next_time = NextTS;
1395 pThis->fTimerArmed = true;
1396 apicDoFrequencyHinting(pThis);
1397 break;
1398 }
1399 STAM_COUNTER_INC(&pThis->StatTimerSetLvtArmRetries);
1400 }
1401 }
1402 }
1403 else
1404 STAM_COUNTER_INC(&pThis->StatTimerSetLvtNoRelevantChange);
1405}
1406
1407# ifdef IN_RING3
1408/**
1409 * Timer callback function.
1410 *
1411 * @param pDevIns The device state.
1412 * @param pTimer The timer handle.
1413 * @param pvUser User argument pointing to the APIC instance.
1414 */
1415static DECLCALLBACK(void) apicTimerCallback(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
1416{
1417 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1418 APICState *pThis = (APICState *)pvUser;
1419 Assert(pThis->pTimerR3 == pTimer);
1420 Assert(pThis->fTimerArmed);
1421
1422 if (!(pThis->lvt[APIC_LVT_TIMER] & APIC_LVT_MASKED)) {
1423 LogFlow(("apic_timer: trigger irq\n"));
1424 apic_set_irq(dev, pThis, pThis->lvt[APIC_LVT_TIMER] & 0xff, APIC_TRIGGER_EDGE);
1425
1426 if (pThis->lvt[APIC_LVT_TIMER] & APIC_LVT_TIMER_PERIODIC) {
1427 /* new interval. */
1428 pThis->next_time += (((uint64_t)pThis->initial_count + 1) << pThis->count_shift);
1429 TMTimerSet(pThis->CTX_SUFF(pTimer), pThis->next_time);
1430 pThis->fTimerArmed = true;
1431 apicDoFrequencyHinting(pThis);
1432 } else {
1433 /* single shot. */
1434 pThis->fTimerArmed = false;
1435 pThis->uHintedCountShift = pThis->uHintedInitialCount = 0;
1436 }
1437 } else {
1438 /* masked, do not rearm. */
1439 pThis->fTimerArmed = false;
1440 pThis->uHintedCountShift = pThis->uHintedInitialCount = 0;
1441 }
1442}
1443# endif /* IN_RING3 */
1444
1445static uint32_t apic_mem_readl(APICDeviceInfo* dev, APICState *s, RTGCPHYS addr)
1446{
1447 uint32_t val;
1448 int index;
1449
1450 index = (addr >> 4) & 0xff;
1451
1452 switch(index) {
1453 case 0x02: /* id */
1454 val = s->id << 24;
1455 break;
1456 case 0x03: /* version */
1457 val = APIC_HW_VERSION | ((APIC_LVT_NB - 1) << 16);
1458 break;
1459 case 0x08:
1460 val = s->tpr;
1461 break;
1462 case 0x09:
1463 val = apic_get_arb_pri(s);
1464 break;
1465 case 0x0a:
1466 /* ppr */
1467 val = apic_get_ppr(s);
1468 break;
1469 case 0x0b:
1470 Log(("apic_mem_readl %x %x -> write only returning 0\n", addr, index));
1471 val = 0;
1472 break;
1473 case 0x0d:
1474 val = s->log_dest << 24;
1475 break;
1476 case 0x0e:
1477 /* Bottom 28 bits are always 1 */
1478 val = (s->dest_mode << 28) | 0xfffffff;
1479 break;
1480 case 0x0f:
1481 val = s->spurious_vec;
1482 break;
1483 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
1484 val = s->isr[index & 7];
1485 break;
1486 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
1487 val = s->tmr[index & 7];
1488 break;
1489 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
1490 val = s->irr[index & 7];
1491 break;
1492 case 0x28:
1493 val = s->esr;
1494 break;
1495 case 0x30:
1496 case 0x31:
1497 val = s->icr[index & 1];
1498 break;
1499 case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
1500 val = s->lvt[index - 0x32];
1501 break;
1502 case 0x38:
1503 val = s->initial_count;
1504 break;
1505 case 0x39:
1506 val = apic_get_current_count(dev, s);
1507 break;
1508 case 0x3e:
1509 val = s->divide_conf;
1510 break;
1511 case 0x2f:
1512 /**
1513 * Correctable machine check exception vector, @todo: implement me!
1514 */
1515 default:
1516 AssertMsgFailed(("apic_mem_readl: unknown index %x\n", index));
1517 s->esr |= ESR_ILLEGAL_ADDRESS;
1518 val = 0;
1519 break;
1520 }
1521#ifdef DEBUG_APIC
1522 Log(("CPU%d: APIC read: %08x = %08x\n", s->phys_id, (uint32_t)addr, val));
1523#endif
1524 return val;
1525}
1526
1527static int apic_mem_writel(APICDeviceInfo* dev, APICState *s, RTGCPHYS addr, uint32_t val)
1528{
1529 int rc = VINF_SUCCESS;
1530 int index;
1531
1532#ifdef DEBUG_APIC
1533 Log(("CPU%d: APIC write: %08x = %08x\n", s->phys_id, (uint32_t)addr, val));
1534#endif
1535
1536 index = (addr >> 4) & 0xff;
1537
1538 switch(index) {
1539 case 0x02:
1540 s->id = (val >> 24);
1541 break;
1542 case 0x03:
1543 Log(("apic_mem_writel: write to version register; ignored\n"));
1544 break;
1545 case 0x08:
1546 apic_update_tpr(dev, s, val);
1547 break;
1548 case 0x09:
1549 case 0x0a:
1550 Log(("apic_mem_writel: write to read-only register %d ignored\n", index));
1551 break;
1552 case 0x0b: /* EOI */
1553 apic_eoi(dev, s);
1554 break;
1555 case 0x0d:
1556 s->log_dest = val >> 24;
1557 break;
1558 case 0x0e:
1559 s->dest_mode = val >> 28;
1560 break;
1561 case 0x0f:
1562 s->spurious_vec = val & 0x1ff;
1563 apic_update_irq(dev, s);
1564 break;
1565 case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
1566 case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
1567 case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
1568 case 0x28:
1569 Log(("apic_mem_writel: write to read-only register %d ignored\n", index));
1570 break;
1571
1572 case 0x30:
1573 s->icr[0] = val;
1574 rc = apic_deliver(dev, s, (s->icr[1] >> 24) & 0xff,
1575 (s->icr[0] >> 11) & 1,
1576 (s->icr[0] >> 8) & 7, (s->icr[0] & 0xff),
1577 (s->icr[0] >> 14) & 1, (s->icr[0] >> 15) & 1);
1578 break;
1579 case 0x31:
1580 s->icr[1] = val;
1581 break;
1582 case 0x32 + APIC_LVT_TIMER:
1583 AssertCompile(APIC_LVT_TIMER == 0);
1584 apicTimerSetLvt(dev, s, val);
1585 break;
1586 case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
1587 {
1588 int n = index - 0x32;
1589 s->lvt[n] = val;
1590 }
1591 break;
1592 case 0x38:
1593 apicTimerSetInitialCount(dev, s, val);
1594 break;
1595 case 0x39:
1596 Log(("apic_mem_writel: write to read-only register %d ignored\n", index));
1597 break;
1598 case 0x3e:
1599 {
1600 int v;
1601 s->divide_conf = val & 0xb;
1602 v = (s->divide_conf & 3) | ((s->divide_conf >> 1) & 4);
1603 s->count_shift = (v + 1) & 7;
1604 }
1605 break;
1606 default:
1607 AssertMsgFailed(("apic_mem_writel: unknown index %x\n", index));
1608 s->esr |= ESR_ILLEGAL_ADDRESS;
1609 break;
1610 }
1611 return rc;
1612}
1613
1614#ifdef IN_RING3
1615
1616static void apic_save(SSMHANDLE* f, void *opaque)
1617{
1618 APICState *s = (APICState*)opaque;
1619 int i;
1620
1621 SSMR3PutU32(f, s->apicbase);
1622 SSMR3PutU32(f, s->id);
1623 SSMR3PutU32(f, s->phys_id);
1624 SSMR3PutU32(f, s->arb_id);
1625 SSMR3PutU32(f, s->tpr);
1626 SSMR3PutU32(f, s->spurious_vec);
1627 SSMR3PutU8(f, s->log_dest);
1628 SSMR3PutU8(f, s->dest_mode);
1629 for (i = 0; i < 8; i++) {
1630 SSMR3PutU32(f, s->isr[i]);
1631 SSMR3PutU32(f, s->tmr[i]);
1632 SSMR3PutU32(f, s->irr[i]);
1633 }
1634 for (i = 0; i < APIC_LVT_NB; i++) {
1635 SSMR3PutU32(f, s->lvt[i]);
1636 }
1637 SSMR3PutU32(f, s->esr);
1638 SSMR3PutU32(f, s->icr[0]);
1639 SSMR3PutU32(f, s->icr[1]);
1640 SSMR3PutU32(f, s->divide_conf);
1641 SSMR3PutU32(f, s->count_shift);
1642 SSMR3PutU32(f, s->initial_count);
1643 SSMR3PutU64(f, s->initial_count_load_time);
1644 SSMR3PutU64(f, s->next_time);
1645
1646 TMR3TimerSave(s->CTX_SUFF(pTimer), f);
1647}
1648
1649static int apic_load(SSMHANDLE *f, void *opaque, int version_id)
1650{
1651 APICState *s = (APICState*)opaque;
1652 int i;
1653
1654 /* XXX: what if the base changes? (registered memory regions) */
1655 SSMR3GetU32(f, &s->apicbase);
1656
1657 switch (version_id)
1658 {
1659 case APIC_SAVED_STATE_VERSION_ANCIENT:
1660 {
1661 uint8_t val = 0;
1662 SSMR3GetU8(f, &val);
1663 s->id = val;
1664 /* UP only in old saved states */
1665 s->phys_id = 0;
1666 SSMR3GetU8(f, &val);
1667 s->arb_id = val;
1668 break;
1669 }
1670 case APIC_SAVED_STATE_VERSION:
1671 case APIC_SAVED_STATE_VERSION_VBOX_30:
1672 SSMR3GetU32(f, &s->id);
1673 SSMR3GetU32(f, &s->phys_id);
1674 SSMR3GetU32(f, &s->arb_id);
1675 break;
1676 default:
1677 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1678 }
1679 SSMR3GetU32(f, &s->tpr);
1680 SSMR3GetU32(f, &s->spurious_vec);
1681 SSMR3GetU8(f, &s->log_dest);
1682 SSMR3GetU8(f, &s->dest_mode);
1683 for (i = 0; i < 8; i++) {
1684 SSMR3GetU32(f, &s->isr[i]);
1685 SSMR3GetU32(f, &s->tmr[i]);
1686 SSMR3GetU32(f, &s->irr[i]);
1687 }
1688 for (i = 0; i < APIC_LVT_NB; i++) {
1689 SSMR3GetU32(f, &s->lvt[i]);
1690 }
1691 SSMR3GetU32(f, &s->esr);
1692 SSMR3GetU32(f, &s->icr[0]);
1693 SSMR3GetU32(f, &s->icr[1]);
1694 SSMR3GetU32(f, &s->divide_conf);
1695 SSMR3GetU32(f, (uint32_t *)&s->count_shift);
1696 SSMR3GetU32(f, (uint32_t *)&s->initial_count);
1697 SSMR3GetU64(f, (uint64_t *)&s->initial_count_load_time);
1698 SSMR3GetU64(f, (uint64_t *)&s->next_time);
1699
1700 int rc = TMR3TimerLoad(s->CTX_SUFF(pTimer), f);
1701 s->uHintedCountShift = s->uHintedInitialCount = 0;
1702 s->fTimerArmed = TMTimerIsActive(s->CTX_SUFF(pTimer));
1703 if (s->fTimerArmed)
1704 apicDoFrequencyHinting(s);
1705
1706 return VINF_SUCCESS; /** @todo darn mess! */
1707}
1708#endif /* IN_RING3 */
1709
1710static void ioapic_service(IOAPICState *s)
1711{
1712 uint8_t i;
1713 uint8_t trig_mode;
1714 uint8_t vector;
1715 uint8_t delivery_mode;
1716 uint32_t mask;
1717 uint64_t entry;
1718 uint8_t dest;
1719 uint8_t dest_mode;
1720 uint8_t polarity;
1721
1722 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
1723 mask = 1 << i;
1724 if (s->irr & mask) {
1725 entry = s->ioredtbl[i];
1726 if (!(entry & APIC_LVT_MASKED)) {
1727 trig_mode = ((entry >> 15) & 1);
1728 dest = entry >> 56;
1729 dest_mode = (entry >> 11) & 1;
1730 delivery_mode = (entry >> 8) & 7;
1731 polarity = (entry >> 13) & 1;
1732 if (trig_mode == APIC_TRIGGER_EDGE)
1733 s->irr &= ~mask;
1734 if (delivery_mode == APIC_DM_EXTINT)
1735 /* malc: i'm still not so sure about ExtINT delivery */
1736 {
1737 AssertMsgFailed(("Delivery mode ExtINT"));
1738 vector = 0xff; /* incorrect but shuts up gcc. */
1739 }
1740 else
1741 vector = entry & 0xff;
1742
1743 int rc = s->CTX_SUFF(pIoApicHlp)->pfnApicBusDeliver(s->CTX_SUFF(pDevIns),
1744 dest,
1745 dest_mode,
1746 delivery_mode,
1747 vector,
1748 polarity,
1749 trig_mode);
1750 /* We must be sure that attempts to reschedule in R3
1751 never get here */
1752 Assert(rc == VINF_SUCCESS);
1753 }
1754 }
1755 }
1756}
1757
1758
1759static void ioapic_set_irq(void *opaque, int vector, int level)
1760{
1761 IOAPICState *s = (IOAPICState*)opaque;
1762
1763 if (vector >= 0 && vector < IOAPIC_NUM_PINS) {
1764 uint32_t mask = 1 << vector;
1765 uint64_t entry = s->ioredtbl[vector];
1766
1767 if ((entry >> 15) & 1) {
1768 /* level triggered */
1769 if (level) {
1770 s->irr |= mask;
1771 ioapic_service(s);
1772 if ((level & PDM_IRQ_LEVEL_FLIP_FLOP) == PDM_IRQ_LEVEL_FLIP_FLOP) {
1773 s->irr &= ~mask;
1774 }
1775 } else {
1776 s->irr &= ~mask;
1777 }
1778 } else {
1779 /* edge triggered */
1780 if (level) {
1781 s->irr |= mask;
1782 ioapic_service(s);
1783 }
1784 }
1785 }
1786}
1787
1788static uint32_t ioapic_mem_readl(void *opaque, RTGCPHYS addr)
1789{
1790 IOAPICState *s = (IOAPICState*)opaque;
1791 int index;
1792 uint32_t val = 0;
1793
1794 addr &= 0xff;
1795 if (addr == 0x00) {
1796 val = s->ioregsel;
1797 } else if (addr == 0x10) {
1798 switch (s->ioregsel) {
1799 case 0x00:
1800 val = s->id << 24;
1801 break;
1802 case 0x01:
1803 val = 0x11 | ((IOAPIC_NUM_PINS - 1) << 16); /* version 0x11 */
1804 break;
1805 case 0x02:
1806 val = 0;
1807 break;
1808 default:
1809 index = (s->ioregsel - 0x10) >> 1;
1810 if (index >= 0 && index < IOAPIC_NUM_PINS) {
1811 if (s->ioregsel & 1)
1812 val = s->ioredtbl[index] >> 32;
1813 else
1814 val = s->ioredtbl[index] & 0xffffffff;
1815 }
1816 }
1817#ifdef DEBUG_IOAPIC
1818 Log(("I/O APIC read: %08x = %08x\n", s->ioregsel, val));
1819#endif
1820 }
1821 return val;
1822}
1823
1824static void ioapic_mem_writel(void *opaque, RTGCPHYS addr, uint32_t val)
1825{
1826 IOAPICState *s = (IOAPICState*)opaque;
1827 int index;
1828
1829 addr &= 0xff;
1830 if (addr == 0x00) {
1831 s->ioregsel = val;
1832 return;
1833 } else if (addr == 0x10) {
1834#ifdef DEBUG_IOAPIC
1835 Log(("I/O APIC write: %08x = %08x\n", s->ioregsel, val));
1836#endif
1837 switch (s->ioregsel) {
1838 case 0x00:
1839 s->id = (val >> 24) & 0xff;
1840 return;
1841 case 0x01:
1842 case 0x02:
1843 return;
1844 default:
1845 index = (s->ioregsel - 0x10) >> 1;
1846 if (index >= 0 && index < IOAPIC_NUM_PINS) {
1847 if (s->ioregsel & 1) {
1848 s->ioredtbl[index] &= 0xffffffff;
1849 s->ioredtbl[index] |= (uint64_t)val << 32;
1850 } else {
1851 /* According to IOAPIC spec, vectors should be from 0x10 to 0xfe */
1852 uint8_t vec = val & 0xff;
1853 if ((val & APIC_LVT_MASKED) ||
1854 ((vec >= 0x10) && (vec < 0xff)))
1855 {
1856 s->ioredtbl[index] &= ~0xffffffffULL;
1857 s->ioredtbl[index] |= val;
1858 }
1859 else
1860 {
1861 /*
1862 * Linux 2.6 kernels has pretty strange function
1863 * unlock_ExtINT_logic() which writes
1864 * absolutely bogus (all 0) value into the vector
1865 * with pretty vague explanation why.
1866 * So we just ignore such writes.
1867 */
1868 LogRel(("IOAPIC GUEST BUG: bad vector writing %x(sel=%x) to %d\n", val, s->ioregsel, index));
1869 }
1870 }
1871 ioapic_service(s);
1872 }
1873 }
1874 }
1875}
1876
1877#ifdef IN_RING3
1878
1879static void ioapic_save(SSMHANDLE *f, void *opaque)
1880{
1881 IOAPICState *s = (IOAPICState*)opaque;
1882 int i;
1883
1884 SSMR3PutU8(f, s->id);
1885 SSMR3PutU8(f, s->ioregsel);
1886 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
1887 SSMR3PutU64(f, s->ioredtbl[i]);
1888 }
1889}
1890
1891static int ioapic_load(SSMHANDLE *f, void *opaque, int version_id)
1892{
1893 IOAPICState *s = (IOAPICState*)opaque;
1894 int i;
1895
1896 if (version_id != 1)
1897 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1898
1899 SSMR3GetU8(f, &s->id);
1900 SSMR3GetU8(f, &s->ioregsel);
1901 for (i = 0; i < IOAPIC_NUM_PINS; i++) {
1902 SSMR3GetU64(f, &s->ioredtbl[i]);
1903 }
1904 return 0;
1905}
1906
1907static void ioapic_reset(void *opaque)
1908{
1909 IOAPICState *s = (IOAPICState*)opaque;
1910 PPDMDEVINSR3 pDevIns = s->pDevInsR3;
1911 PCPDMIOAPICHLPR3 pIoApicHlp = s->pIoApicHlpR3;
1912 int i;
1913
1914 memset(s, 0, sizeof(*s));
1915 for(i = 0; i < IOAPIC_NUM_PINS; i++)
1916 s->ioredtbl[i] = 1 << 16; /* mask LVT */
1917
1918 if (pDevIns)
1919 {
1920 s->pDevInsR3 = pDevIns;
1921 s->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
1922 s->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
1923 }
1924 if (pIoApicHlp)
1925 {
1926 s->pIoApicHlpR3 = pIoApicHlp;
1927 s->pIoApicHlpRC = s->pIoApicHlpR3->pfnGetRCHelpers(pDevIns);
1928 s->pIoApicHlpR0 = s->pIoApicHlpR3->pfnGetR0Helpers(pDevIns);
1929 }
1930}
1931
1932#endif /* IN_RING3 */
1933
1934/* LAPIC */
1935PDMBOTHCBDECL(int) apicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
1936{
1937 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1938 APICState *s = getLapic(dev);
1939
1940 Log(("CPU%d: apicMMIORead at %llx\n", s->phys_id, (uint64_t)GCPhysAddr));
1941
1942 /** @todo: add LAPIC range validity checks (different LAPICs can theoretically have
1943 different physical addresses, see #3092) */
1944
1945 STAM_COUNTER_INC(&CTXSUFF(dev->StatMMIORead));
1946 switch (cb)
1947 {
1948 case 1:
1949 *(uint8_t *)pv = 0;
1950 break;
1951
1952 case 2:
1953 *(uint16_t *)pv = 0;
1954 break;
1955
1956 case 4:
1957 {
1958#if 0 /** @note experimental */
1959#ifndef IN_RING3
1960 uint32_t index = (GCPhysAddr >> 4) & 0xff;
1961
1962 if ( index == 0x08 /* TPR */
1963 && ++s->cTPRPatchAttempts < APIC_MAX_PATCH_ATTEMPTS)
1964 {
1965#ifdef IN_RC
1966 pDevIns->pDevHlpGC->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, &s->tpr);
1967#else
1968 RTGCPTR pDevInsGC = PDMINS2DATA_GCPTR(pDevIns);
1969 pDevIns->pHlpR0->pfnPATMSetMMIOPatchInfo(pDevIns, GCPhysAddr, pDevIns + RT_OFFSETOF(APICState, tpr));
1970#endif
1971 return VINF_PATM_HC_MMIO_PATCH_READ;
1972 }
1973#endif
1974#endif /* experimental */
1975 APIC_LOCK(dev, VINF_IOM_HC_MMIO_READ);
1976 *(uint32_t *)pv = apic_mem_readl(dev, s, GCPhysAddr);
1977 APIC_UNLOCK(dev);
1978 break;
1979 }
1980 default:
1981 AssertReleaseMsgFailed(("cb=%d\n", cb)); /* for now we assume simple accesses. */
1982 return VERR_INTERNAL_ERROR;
1983 }
1984 return VINF_SUCCESS;
1985}
1986
1987PDMBOTHCBDECL(int) apicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
1988{
1989 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
1990 APICState *s = getLapic(dev);
1991
1992 Log(("CPU%d: apicMMIOWrite at %llx\n", s->phys_id, (uint64_t)GCPhysAddr));
1993
1994 /** @todo: add LAPIC range validity checks (multiple LAPICs can theoretically have
1995 different physical addresses, see #3092) */
1996
1997 STAM_COUNTER_INC(&CTXSUFF(dev->StatMMIOWrite));
1998 switch (cb)
1999 {
2000 case 1:
2001 case 2:
2002 /* ignore */
2003 break;
2004
2005 case 4:
2006 {
2007 int rc;
2008 APIC_LOCK(dev, VINF_IOM_HC_MMIO_WRITE);
2009 rc = apic_mem_writel(dev, s, GCPhysAddr, *(uint32_t *)pv);
2010 APIC_UNLOCK(dev);
2011 return rc;
2012 }
2013
2014 default:
2015 AssertReleaseMsgFailed(("cb=%d\n", cb)); /* for now we assume simple accesses. */
2016 return VERR_INTERNAL_ERROR;
2017 }
2018 return VINF_SUCCESS;
2019}
2020
2021#ifdef IN_RING3
2022
2023/* Print a 8-dword LAPIC bit map (256 bits). */
2024static void lapicDumpVec(APICDeviceInfo *dev, APICState *lapic, PCDBGFINFOHLP pHlp, unsigned start)
2025{
2026 unsigned i;
2027 uint32_t val;
2028
2029 for (i = 0; i < 8; ++i)
2030 {
2031 val = apic_mem_readl(dev, lapic, start + (i << 4));
2032 pHlp->pfnPrintf(pHlp, "%08X", val);
2033 }
2034 pHlp->pfnPrintf(pHlp, "\n");
2035}
2036
2037/* Print basic LAPIC state. */
2038static DECLCALLBACK(void) lapicInfoBasic(APICDeviceInfo *dev, APICState *lapic, PCDBGFINFOHLP pHlp)
2039{
2040 uint32_t val;
2041 unsigned max_lvt;
2042
2043 pHlp->pfnPrintf(pHlp, "Local APIC at %08X:\n", lapic->apicbase);
2044 val = apic_mem_readl(dev, lapic, 0x20);
2045 pHlp->pfnPrintf(pHlp, " LAPIC ID : %08X\n", val);
2046 pHlp->pfnPrintf(pHlp, " APIC ID = %02X\n", (val >> 24) & 0xff);
2047 val = apic_mem_readl(dev, lapic, 0x30);
2048 max_lvt = (val >> 16) & 0xff;
2049 pHlp->pfnPrintf(pHlp, " APIC VER : %08X\n", val);
2050 pHlp->pfnPrintf(pHlp, " version = %02X\n", val & 0xff);
2051 pHlp->pfnPrintf(pHlp, " lvts = %d\n", ((val >> 16) & 0xff) + 1);
2052 val = apic_mem_readl(dev, lapic, 0x80);
2053 pHlp->pfnPrintf(pHlp, " TPR : %08X\n", val);
2054 pHlp->pfnPrintf(pHlp, " task pri = %d/%d\n", (val >> 4) & 0xf, val & 0xf);
2055 val = apic_mem_readl(dev, lapic, 0xA0);
2056 pHlp->pfnPrintf(pHlp, " PPR : %08X\n", val);
2057 pHlp->pfnPrintf(pHlp, " cpu pri = %d/%d\n", (val >> 4) & 0xf, val & 0xf);
2058 val = apic_mem_readl(dev, lapic, 0xD0);
2059 pHlp->pfnPrintf(pHlp, " LDR : %08X\n", val);
2060 pHlp->pfnPrintf(pHlp, " log id = %02X\n", (val >> 24) & 0xff);
2061 val = apic_mem_readl(dev, lapic, 0xE0);
2062 pHlp->pfnPrintf(pHlp, " DFR : %08X\n", val);
2063 val = apic_mem_readl(dev, lapic, 0xF0);
2064 pHlp->pfnPrintf(pHlp, " SVR : %08X\n", val);
2065 pHlp->pfnPrintf(pHlp, " focus = %s\n", val & (1 << 9) ? "check off" : "check on");
2066 pHlp->pfnPrintf(pHlp, " lapic = %s\n", val & (1 << 8) ? "ENABLED" : "DISABLED");
2067 pHlp->pfnPrintf(pHlp, " vector = %02X\n", val & 0xff);
2068 pHlp->pfnPrintf(pHlp, " ISR : ");
2069 lapicDumpVec(dev, lapic, pHlp, 0x100);
2070 val = get_highest_priority_int(lapic->isr);
2071 pHlp->pfnPrintf(pHlp, " highest = %02X\n", val == ~0U ? 0 : val);
2072 pHlp->pfnPrintf(pHlp, " IRR : ");
2073 lapicDumpVec(dev, lapic, pHlp, 0x200);
2074 val = get_highest_priority_int(lapic->irr);
2075 pHlp->pfnPrintf(pHlp, " highest = %02X\n", val == ~0U ? 0 : val);
2076 val = apic_mem_readl(dev, lapic, 0x320);
2077}
2078
2079/* Print the more interesting LAPIC LVT entries. */
2080static DECLCALLBACK(void) lapicInfoLVT(APICDeviceInfo *dev, APICState *lapic, PCDBGFINFOHLP pHlp)
2081{
2082 uint32_t val;
2083 static const char *dmodes[] = { "Fixed ", "Reserved", "SMI", "Reserved",
2084 "NMI", "INIT", "Reserved", "ExtINT" };
2085
2086 val = apic_mem_readl(dev, lapic, 0x320);
2087 pHlp->pfnPrintf(pHlp, " LVT Timer : %08X\n", val);
2088 pHlp->pfnPrintf(pHlp, " mode = %s\n", val & (1 << 17) ? "periodic" : "one-shot");
2089 pHlp->pfnPrintf(pHlp, " mask = %d\n", (val >> 16) & 1);
2090 pHlp->pfnPrintf(pHlp, " status = %s\n", val & (1 << 12) ? "pending" : "idle");
2091 pHlp->pfnPrintf(pHlp, " vector = %02X\n", val & 0xff);
2092 val = apic_mem_readl(dev, lapic, 0x350);
2093 pHlp->pfnPrintf(pHlp, " LVT LINT0 : %08X\n", val);
2094 pHlp->pfnPrintf(pHlp, " mask = %d\n", (val >> 16) & 1);
2095 pHlp->pfnPrintf(pHlp, " trigger = %s\n", val & (1 << 15) ? "level" : "edge");
2096 pHlp->pfnPrintf(pHlp, " rem irr = %d\n", (val >> 14) & 1);
2097 pHlp->pfnPrintf(pHlp, " polarty = %d\n", (val >> 13) & 1);
2098 pHlp->pfnPrintf(pHlp, " status = %s\n", val & (1 << 12) ? "pending" : "idle");
2099 pHlp->pfnPrintf(pHlp, " delivry = %s\n", dmodes[(val >> 8) & 7]);
2100 pHlp->pfnPrintf(pHlp, " vector = %02X\n", val & 0xff);
2101 val = apic_mem_readl(dev, lapic, 0x360);
2102 pHlp->pfnPrintf(pHlp, " LVT LINT1 : %08X\n", val);
2103 pHlp->pfnPrintf(pHlp, " mask = %d\n", (val >> 16) & 1);
2104 pHlp->pfnPrintf(pHlp, " trigger = %s\n", val & (1 << 15) ? "level" : "edge");
2105 pHlp->pfnPrintf(pHlp, " rem irr = %d\n", (val >> 14) & 1);
2106 pHlp->pfnPrintf(pHlp, " polarty = %d\n", (val >> 13) & 1);
2107 pHlp->pfnPrintf(pHlp, " status = %s\n", val & (1 << 12) ? "pending" : "idle");
2108 pHlp->pfnPrintf(pHlp, " delivry = %s\n", dmodes[(val >> 8) & 7]);
2109 pHlp->pfnPrintf(pHlp, " vector = %02X\n", val & 0xff);
2110}
2111
2112/* Print LAPIC timer state. */
2113static DECLCALLBACK(void) lapicInfoTimer(APICDeviceInfo *dev, APICState *lapic, PCDBGFINFOHLP pHlp)
2114{
2115 uint32_t val;
2116 unsigned divider;
2117
2118 pHlp->pfnPrintf(pHlp, "Local APIC timer:\n");
2119 val = apic_mem_readl(dev, lapic, 0x380);
2120 pHlp->pfnPrintf(pHlp, " Initial count : %08X\n", val);
2121 val = apic_mem_readl(dev, lapic, 0x390);
2122 pHlp->pfnPrintf(pHlp, " Current count : %08X\n", val);
2123 val = apic_mem_readl(dev, lapic, 0x3E0);
2124 pHlp->pfnPrintf(pHlp, " Divide config : %08X\n", val);
2125 divider = ((val >> 1) & 0x04) | (val & 0x03);
2126 pHlp->pfnPrintf(pHlp, " divider = %d\n", divider == 7 ? 1 : 2 << divider);
2127}
2128
2129/**
2130 * Info handler, device version. Dumps Local APIC(s) state according to given argument.
2131 *
2132 * @param pDevIns Device instance which registered the info.
2133 * @param pHlp Callback functions for doing output.
2134 * @param pszArgs Argument string. Optional.
2135 */
2136static DECLCALLBACK(void) lapicInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
2137{
2138 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2139 APICState *lapic;
2140
2141 lapic = getLapic(dev);
2142
2143 if (pszArgs == NULL || !strcmp(pszArgs, "basic"))
2144 {
2145 lapicInfoBasic(dev, lapic, pHlp);
2146 }
2147 else if (!strcmp(pszArgs, "lvt"))
2148 {
2149 lapicInfoLVT(dev, lapic, pHlp);
2150 }
2151 else if (!strcmp(pszArgs, "timer"))
2152 {
2153 lapicInfoTimer(dev, lapic, pHlp);
2154 }
2155 else
2156 {
2157 pHlp->pfnPrintf(pHlp, "Invalid argument. Recognized arguments are 'basic', 'lvt', 'timer'.\n");
2158 }
2159}
2160
2161/**
2162 * @copydoc FNSSMDEVLIVEEXEC
2163 */
2164static DECLCALLBACK(int) apicLiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass)
2165{
2166 APICDeviceInfo *pThis = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2167
2168 SSMR3PutU32( pSSM, pThis->cCpus);
2169 SSMR3PutBool(pSSM, pThis->fIoApic);
2170 SSMR3PutU32( pSSM, pThis->enmVersion);
2171 AssertCompile(PDMAPICVERSION_APIC == 2);
2172
2173 return VINF_SSM_DONT_CALL_AGAIN;
2174}
2175
2176/**
2177 * @copydoc FNSSMDEVSAVEEXEC
2178 */
2179static DECLCALLBACK(int) apicSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2180{
2181 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2182
2183 /* config */
2184 apicLiveExec(pDevIns, pSSM, SSM_PASS_FINAL);
2185
2186 /* save all APICs data, @todo: is it correct? */
2187 foreach_apic(dev, 0xffffffff, apic_save(pSSM, apic));
2188
2189 return VINF_SUCCESS;
2190}
2191
2192/**
2193 * @copydoc FNSSMDEVLOADEXEC
2194 */
2195static DECLCALLBACK(int) apicLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
2196{
2197 APICDeviceInfo *pThis = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2198
2199 if ( uVersion != APIC_SAVED_STATE_VERSION
2200 && uVersion != APIC_SAVED_STATE_VERSION_VBOX_30
2201 && uVersion != APIC_SAVED_STATE_VERSION_ANCIENT)
2202 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
2203
2204 /* config */
2205 if (uVersion > APIC_SAVED_STATE_VERSION_VBOX_30) {
2206 uint32_t cCpus;
2207 int rc = SSMR3GetU32(pSSM, &cCpus); AssertRCReturn(rc, rc);
2208 if (cCpus != pThis->cCpus)
2209 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - cCpus: saved=%#x config=%#x"), cCpus, pThis->cCpus);
2210 bool fIoApic;
2211 rc = SSMR3GetBool(pSSM, &fIoApic); AssertRCReturn(rc, rc);
2212 if (fIoApic != pThis->fIoApic)
2213 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - fIoApic: saved=%RTbool config=%RTbool"), fIoApic, pThis->fIoApic);
2214 uint32_t uApicVersion;
2215 rc = SSMR3GetU32(pSSM, &uApicVersion); AssertRCReturn(rc, rc);
2216 if (uApicVersion != (uint32_t)pThis->enmVersion)
2217 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - uApicVersion: saved=%#x config=%#x"), uApicVersion, pThis->enmVersion);
2218 }
2219
2220 if (uPass != SSM_PASS_FINAL)
2221 return VINF_SUCCESS;
2222
2223 /* load all APICs data */ /** @todo: is it correct? */
2224 APIC_LOCK(pThis, VERR_INTERNAL_ERROR_3);
2225 foreach_apic(pThis, 0xffffffff,
2226 if (apic_load(pSSM, apic, uVersion)) {
2227 AssertFailed();
2228 APIC_UNLOCK(pThis);
2229 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
2230 }
2231 );
2232 APIC_UNLOCK(pThis);
2233 return VINF_SUCCESS;
2234}
2235
2236/**
2237 * @copydoc FNPDMDEVRESET
2238 */
2239static DECLCALLBACK(void) apicReset(PPDMDEVINS pDevIns)
2240{
2241 APICDeviceInfo *dev = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2242 unsigned i;
2243
2244 APIC_LOCK_VOID(dev, VERR_INTERNAL_ERROR);
2245
2246 /* Reset all APICs. */
2247 for (i = 0; i < dev->cCpus; i++) {
2248 APICState *pApic = &dev->CTX_SUFF(paLapics)[i];
2249 TMTimerStop(pApic->CTX_SUFF(pTimer));
2250
2251 /* Clear LAPIC state as if an INIT IPI was sent. */
2252 apic_init_ipi(dev, pApic);
2253 /* The IDs are not touched by apic_init_ipi() and must be reset now. */
2254 pApic->arb_id = pApic->id = i;
2255 Assert(pApic->id == pApic->phys_id); /* The two should match again. */
2256 /* Reset should re-enable the APIC, see comment in msi.h */
2257 pApic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2258 if (pApic->phys_id == 0)
2259 pApic->apicbase |= MSR_IA32_APICBASE_BSP;
2260
2261 /* Clear any pending APIC interrupt action flag. */
2262 cpuClearInterrupt(dev, pApic);
2263 }
2264 /** @todo r=bird: Why is this done everytime, while the constructor first
2265 * checks the CPUID? Who is right? */
2266 dev->pApicHlpR3->pfnChangeFeature(dev->pDevInsR3, dev->enmVersion);
2267
2268 APIC_UNLOCK(dev);
2269}
2270
2271/**
2272 * @copydoc FNPDMDEVRELOCATE
2273 */
2274static DECLCALLBACK(void) apicRelocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
2275{
2276 APICDeviceInfo *pThis = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2277 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2278 pThis->pApicHlpRC = pThis->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2279 pThis->paLapicsRC = MMHyperR3ToRC(PDMDevHlpGetVM(pDevIns), pThis->paLapicsR3);
2280 pThis->pCritSectRC = pThis->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2281 for (uint32_t i = 0; i < pThis->cCpus; i++)
2282 pThis->paLapicsR3[i].pTimerRC = TMTimerRCPtr(pThis->paLapicsR3[i].pTimerR3);
2283}
2284
2285DECLINLINE(void) initApicData(APICState* apic, uint8_t id)
2286{
2287 int i;
2288 memset(apic, 0, sizeof(*apic));
2289
2290 /* See comment in msi.h for LAPIC base info */
2291 apic->apicbase = VBOX_MSI_ADDR_BASE | MSR_IA32_APICBASE_ENABLE;
2292 /* Mark first CPU as BSP */
2293 if (id == 0)
2294 apic->apicbase |= MSR_IA32_APICBASE_BSP;
2295 for (i = 0; i < APIC_LVT_NB; i++)
2296 apic->lvt[i] = 1 << 16; /* mask LVT */
2297 apic->spurious_vec = 0xff;
2298 apic->phys_id = apic->id = id;
2299}
2300
2301/**
2302 * @copydoc FNPDMDEVCONSTRUCT
2303 */
2304static DECLCALLBACK(int) apicConstruct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2305{
2306 PDMAPICREG ApicReg;
2307 int rc;
2308 uint32_t i;
2309 bool fIoApic;
2310 bool fGCEnabled;
2311 bool fR0Enabled;
2312 APICDeviceInfo *pThis = PDMINS_2_DATA(pDevIns, APICDeviceInfo *);
2313 uint32_t cCpus;
2314
2315 /*
2316 * Only single device instance.
2317 */
2318 Assert(iInstance == 0);
2319
2320 /*
2321 * Validate configuration.
2322 */
2323 if (!CFGMR3AreValuesValid(pCfg,
2324 "IOAPIC\0"
2325 "GCEnabled\0"
2326 "R0Enabled\0"
2327 "NumCPUs\0"))
2328 return VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES;
2329
2330 rc = CFGMR3QueryBoolDef(pCfg, "IOAPIC", &fIoApic, true);
2331 if (RT_FAILURE(rc))
2332 return PDMDEV_SET_ERROR(pDevIns, rc,
2333 N_("Configuration error: Failed to read \"IOAPIC\""));
2334
2335 rc = CFGMR3QueryBoolDef(pCfg, "GCEnabled", &fGCEnabled, true);
2336 if (RT_FAILURE(rc))
2337 return PDMDEV_SET_ERROR(pDevIns, rc,
2338 N_("Configuration error: Failed to query boolean value \"GCEnabled\""));
2339
2340 rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &fR0Enabled, true);
2341 if (RT_FAILURE(rc))
2342 return PDMDEV_SET_ERROR(pDevIns, rc,
2343 N_("Configuration error: Failed to query boolean value \"R0Enabled\""));
2344
2345 rc = CFGMR3QueryU32Def(pCfg, "NumCPUs", &cCpus, 1);
2346 if (RT_FAILURE(rc))
2347 return PDMDEV_SET_ERROR(pDevIns, rc,
2348 N_("Configuration error: Failed to query integer value \"NumCPUs\""));
2349
2350 Log(("APIC: cCpus=%d fR0Enabled=%RTbool fGCEnabled=%RTbool fIoApic=%RTbool\n", cCpus, fR0Enabled, fGCEnabled, fIoApic));
2351
2352 /** @todo Current implementation is limited to 32 CPUs due to the use of 32
2353 * bits bitmasks. */
2354 if (cCpus > 32)
2355 return PDMDEV_SET_ERROR(pDevIns, rc,
2356 N_("Configuration error: Invalid value for \"NumCPUs\""));
2357
2358 /*
2359 * Init the data.
2360 */
2361 pThis->pDevInsR3 = pDevIns;
2362 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
2363 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2364 pThis->cCpus = cCpus;
2365 pThis->fIoApic = fIoApic;
2366 /* Use PDMAPICVERSION_X2APIC to activate x2APIC mode */
2367 pThis->enmVersion = PDMAPICVERSION_APIC;
2368
2369 PVM pVM = PDMDevHlpGetVM(pDevIns);
2370 /*
2371 * We are not freeing this memory, as it's automatically released when guest exits.
2372 */
2373 rc = MMHyperAlloc(pVM, cCpus * sizeof(APICState), 1, MM_TAG_PDM_DEVICE_USER, (void **)&pThis->paLapicsR3);
2374 if (RT_FAILURE(rc))
2375 return VERR_NO_MEMORY;
2376 pThis->paLapicsR0 = MMHyperR3ToR0(pVM, pThis->paLapicsR3);
2377 pThis->paLapicsRC = MMHyperR3ToRC(pVM, pThis->paLapicsR3);
2378
2379 for (i = 0; i < cCpus; i++)
2380 initApicData(&pThis->paLapicsR3[i], i);
2381
2382 /*
2383 * Register the APIC.
2384 */
2385 ApicReg.u32Version = PDM_APICREG_VERSION;
2386 ApicReg.pfnGetInterruptR3 = apicGetInterrupt;
2387 ApicReg.pfnHasPendingIrqR3 = apicHasPendingIrq;
2388 ApicReg.pfnSetBaseR3 = apicSetBase;
2389 ApicReg.pfnGetBaseR3 = apicGetBase;
2390 ApicReg.pfnSetTPRR3 = apicSetTPR;
2391 ApicReg.pfnGetTPRR3 = apicGetTPR;
2392 ApicReg.pfnWriteMSRR3 = apicWriteMSR;
2393 ApicReg.pfnReadMSRR3 = apicReadMSR;
2394 ApicReg.pfnBusDeliverR3 = apicBusDeliverCallback;
2395 ApicReg.pfnLocalInterruptR3 = apicLocalInterrupt;
2396 if (fGCEnabled) {
2397 ApicReg.pszGetInterruptRC = "apicGetInterrupt";
2398 ApicReg.pszHasPendingIrqRC = "apicHasPendingIrq";
2399 ApicReg.pszSetBaseRC = "apicSetBase";
2400 ApicReg.pszGetBaseRC = "apicGetBase";
2401 ApicReg.pszSetTPRRC = "apicSetTPR";
2402 ApicReg.pszGetTPRRC = "apicGetTPR";
2403 ApicReg.pszWriteMSRRC = "apicWriteMSR";
2404 ApicReg.pszReadMSRRC = "apicReadMSR";
2405 ApicReg.pszBusDeliverRC = "apicBusDeliverCallback";
2406 ApicReg.pszLocalInterruptRC = "apicLocalInterrupt";
2407 } else {
2408 ApicReg.pszGetInterruptRC = NULL;
2409 ApicReg.pszHasPendingIrqRC = NULL;
2410 ApicReg.pszSetBaseRC = NULL;
2411 ApicReg.pszGetBaseRC = NULL;
2412 ApicReg.pszSetTPRRC = NULL;
2413 ApicReg.pszGetTPRRC = NULL;
2414 ApicReg.pszWriteMSRRC = NULL;
2415 ApicReg.pszReadMSRRC = NULL;
2416 ApicReg.pszBusDeliverRC = NULL;
2417 ApicReg.pszLocalInterruptRC = NULL;
2418 }
2419 if (fR0Enabled) {
2420 ApicReg.pszGetInterruptR0 = "apicGetInterrupt";
2421 ApicReg.pszHasPendingIrqR0 = "apicHasPendingIrq";
2422 ApicReg.pszSetBaseR0 = "apicSetBase";
2423 ApicReg.pszGetBaseR0 = "apicGetBase";
2424 ApicReg.pszSetTPRR0 = "apicSetTPR";
2425 ApicReg.pszGetTPRR0 = "apicGetTPR";
2426 ApicReg.pszWriteMSRR0 = "apicWriteMSR";
2427 ApicReg.pszReadMSRR0 = "apicReadMSR";
2428 ApicReg.pszBusDeliverR0 = "apicBusDeliverCallback";
2429 ApicReg.pszLocalInterruptR0 = "apicLocalInterrupt";
2430 } else {
2431 ApicReg.pszGetInterruptR0 = NULL;
2432 ApicReg.pszHasPendingIrqR0 = NULL;
2433 ApicReg.pszSetBaseR0 = NULL;
2434 ApicReg.pszGetBaseR0 = NULL;
2435 ApicReg.pszSetTPRR0 = NULL;
2436 ApicReg.pszGetTPRR0 = NULL;
2437 ApicReg.pszWriteMSRR0 = NULL;
2438 ApicReg.pszReadMSRR0 = NULL;
2439 ApicReg.pszBusDeliverR0 = NULL;
2440 ApicReg.pszLocalInterruptR0 = NULL;
2441 }
2442
2443 rc = PDMDevHlpAPICRegister(pDevIns, &ApicReg, &pThis->pApicHlpR3);
2444 AssertLogRelRCReturn(rc, rc);
2445 pThis->pCritSectR3 = pThis->pApicHlpR3->pfnGetR3CritSect(pDevIns);
2446
2447 /*
2448 * The the CPUID feature bit.
2449 */
2450 /** @todo r=bird: See remark in the apicReset. */
2451 uint32_t u32Eax, u32Ebx, u32Ecx, u32Edx;
2452 PDMDevHlpGetCpuId(pDevIns, 0, &u32Eax, &u32Ebx, &u32Ecx, &u32Edx);
2453 if (u32Eax >= 1) {
2454 if ( fIoApic /* If IOAPIC is enabled, enable Local APIC in any case */
2455 || ( u32Ebx == X86_CPUID_VENDOR_INTEL_EBX
2456 && u32Ecx == X86_CPUID_VENDOR_INTEL_ECX
2457 && u32Edx == X86_CPUID_VENDOR_INTEL_EDX /* GenuineIntel */)
2458 || ( u32Ebx == X86_CPUID_VENDOR_AMD_EBX
2459 && u32Ecx == X86_CPUID_VENDOR_AMD_ECX
2460 && u32Edx == X86_CPUID_VENDOR_AMD_EDX /* AuthenticAMD */)) {
2461 LogRel(("Activating Local APIC\n"));
2462 pThis->pApicHlpR3->pfnChangeFeature(pDevIns, pThis->enmVersion);
2463 }
2464 }
2465
2466 /*
2467 * Register the MMIO range.
2468 * @todo: shall reregister, if base changes.
2469 */
2470 uint32_t ApicBase = pThis->paLapicsR3[0].apicbase & ~0xfff;
2471 rc = PDMDevHlpMMIORegister(pDevIns, ApicBase, 0x1000, pThis,
2472 apicMMIOWrite, apicMMIORead, NULL, "APIC Memory");
2473 if (RT_FAILURE(rc))
2474 return rc;
2475
2476 if (fGCEnabled) {
2477 pThis->pApicHlpRC = pThis->pApicHlpR3->pfnGetRCHelpers(pDevIns);
2478 pThis->pCritSectRC = pThis->pApicHlpR3->pfnGetRCCritSect(pDevIns);
2479
2480 rc = PDMDevHlpMMIORegisterRC(pDevIns, ApicBase, 0x1000, 0,
2481 "apicMMIOWrite", "apicMMIORead", NULL);
2482 if (RT_FAILURE(rc))
2483 return rc;
2484 }
2485
2486 if (fR0Enabled) {
2487 pThis->pApicHlpR0 = pThis->pApicHlpR3->pfnGetR0Helpers(pDevIns);
2488 pThis->pCritSectR0 = pThis->pApicHlpR3->pfnGetR0CritSect(pDevIns);
2489
2490 rc = PDMDevHlpMMIORegisterR0(pDevIns, ApicBase, 0x1000, 0,
2491 "apicMMIOWrite", "apicMMIORead", NULL);
2492 if (RT_FAILURE(rc))
2493 return rc;
2494 }
2495
2496 /*
2497 * Create the APIC timers.
2498 */
2499 for (i = 0; i < cCpus; i++) {
2500 APICState *pApic = &pThis->paLapicsR3[i];
2501 pApic->pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_USER, "APIC Timer #%u", i);
2502 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, apicTimerCallback, pApic,
2503 TMTIMER_FLAGS_NO_CRIT_SECT, pApic->pszDesc, &pApic->pTimerR3);
2504 if (RT_FAILURE(rc))
2505 return rc;
2506 pApic->pTimerR0 = TMTimerR0Ptr(pApic->pTimerR3);
2507 pApic->pTimerRC = TMTimerRCPtr(pApic->pTimerR3);
2508 TMR3TimerSetCritSect(pApic->pTimerR3, pThis->pCritSectR3);
2509 }
2510
2511 /*
2512 * Saved state.
2513 */
2514 rc = PDMDevHlpSSMRegister3(pDevIns, APIC_SAVED_STATE_VERSION, sizeof(*pThis),
2515 apicLiveExec, apicSaveExec, apicLoadExec);
2516 if (RT_FAILURE(rc))
2517 return rc;
2518
2519 /*
2520 * Register debugger info callback.
2521 */
2522 PDMDevHlpDBGFInfoRegister(pDevIns, "lapic", "Display Local APIC state for current CPU. "
2523 "Recognizes 'basic', 'lvt', 'timer' as arguments, defaulting to 'basic'.", lapicInfo);
2524
2525#ifdef VBOX_WITH_STATISTICS
2526 /*
2527 * Statistics.
2528 */
2529 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatMMIOReadGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in GC.");
2530 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatMMIOReadHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOReadHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO reads in HC.");
2531 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatMMIOWriteGC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteGC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in GC.");
2532 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatMMIOWriteHC, STAMTYPE_COUNTER, "/Devices/APIC/MMIOWriteHC", STAMUNIT_OCCURENCES, "Number of APIC MMIO writes in HC.");
2533 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatClearedActiveIrq,STAMTYPE_COUNTER, "/Devices/APIC/MaskedActiveIRQ", STAMUNIT_OCCURENCES, "Number of cleared irqs.");
2534 for (i = 0; i < cCpus; i++) {
2535 APICState *pApic = &pThis->paLapicsR3[i];
2536 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCount, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetInitialCount.", "/Devices/APIC/%u/TimerSetInitialCount", i);
2537 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSetRelative calls.", "/Devices/APIC/%u/TimerSetInitialCount/Arm", i);
2538 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetInitialCountDisarm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop calls.", "/Devices/APIC/%u/TimerSetInitialCount/Disasm", i);
2539 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvt, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Calls to apicTimerSetLvt.", "/Devices/APIC/%u/TimerSetLvt", i);
2540 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtClearPeriodic, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Clearing APIC_LVT_TIMER_PERIODIC.", "/Devices/APIC/%u/TimerSetLvt/ClearPeriodic", i);
2541 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtPostponed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerStop postponed.", "/Devices/APIC/%u/TimerSetLvt/Postponed", i);
2542 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet avoided.", "/Devices/APIC/%u/TimerSetLvt/Armed", i);
2543 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArm, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet necessary.", "/Devices/APIC/%u/TimerSetLvt/Arm", i);
2544 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtArmRetries, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "TMTimerSet retries.", "/Devices/APIC/%u/TimerSetLvt/ArmRetries", i);
2545 PDMDevHlpSTAMRegisterF(pDevIns, &pApic->StatTimerSetLvtNoRelevantChange,STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "No relevant flags changed.", "/Devices/APIC/%u/TimerSetLvt/NoRelevantChange", i);
2546 }
2547#endif
2548
2549 return VINF_SUCCESS;
2550}
2551
2552
2553/**
2554 * APIC device registration structure.
2555 */
2556const PDMDEVREG g_DeviceAPIC =
2557{
2558 /* u32Version */
2559 PDM_DEVREG_VERSION,
2560 /* szName */
2561 "apic",
2562 /* szRCMod */
2563 "VBoxDD2GC.gc",
2564 /* szR0Mod */
2565 "VBoxDD2R0.r0",
2566 /* pszDescription */
2567 "Advanced Programmable Interrupt Controller (APIC) Device",
2568 /* fFlags */
2569 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,
2570 /* fClass */
2571 PDM_DEVREG_CLASS_PIC,
2572 /* cMaxInstances */
2573 1,
2574 /* cbInstance */
2575 sizeof(APICState),
2576 /* pfnConstruct */
2577 apicConstruct,
2578 /* pfnDestruct */
2579 NULL,
2580 /* pfnRelocate */
2581 apicRelocate,
2582 /* pfnIOCtl */
2583 NULL,
2584 /* pfnPowerOn */
2585 NULL,
2586 /* pfnReset */
2587 apicReset,
2588 /* pfnSuspend */
2589 NULL,
2590 /* pfnResume */
2591 NULL,
2592 /* pfnAttach */
2593 NULL,
2594 /* pfnDetach */
2595 NULL,
2596 /* pfnQueryInterface. */
2597 NULL,
2598 /* pfnInitComplete */
2599 NULL,
2600 /* pfnPowerOff */
2601 NULL,
2602 /* pfnSoftReset */
2603 NULL,
2604 /* u32VersionEnd */
2605 PDM_DEVREG_VERSION
2606};
2607
2608#endif /* IN_RING3 */
2609
2610
2611/* IOAPIC */
2612
2613PDMBOTHCBDECL(int) ioapicMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
2614{
2615 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2616 IOAPIC_LOCK(s, VINF_IOM_HC_MMIO_READ);
2617
2618 STAM_COUNTER_INC(&CTXSUFF(s->StatMMIORead));
2619 switch (cb) {
2620 case 1:
2621 *(uint8_t *)pv = ioapic_mem_readl(s, GCPhysAddr);
2622 break;
2623
2624 case 2:
2625 *(uint16_t *)pv = ioapic_mem_readl(s, GCPhysAddr);
2626 break;
2627
2628 case 4:
2629 *(uint32_t *)pv = ioapic_mem_readl(s, GCPhysAddr);
2630 break;
2631
2632 default:
2633 AssertReleaseMsgFailed(("cb=%d\n", cb)); /* for now we assume simple accesses. */
2634 IOAPIC_UNLOCK(s);
2635 return VERR_INTERNAL_ERROR;
2636 }
2637 IOAPIC_UNLOCK(s);
2638 return VINF_SUCCESS;
2639}
2640
2641PDMBOTHCBDECL(int) ioapicMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
2642{
2643 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2644
2645 STAM_COUNTER_INC(&CTXSUFF(s->StatMMIOWrite));
2646 switch (cb) {
2647 case 1:
2648 case 2:
2649 case 4:
2650 IOAPIC_LOCK(s, VINF_IOM_HC_MMIO_WRITE);
2651 ioapic_mem_writel(s, GCPhysAddr, *(uint32_t *)pv);
2652 IOAPIC_UNLOCK(s);
2653 break;
2654
2655 default:
2656 AssertReleaseMsgFailed(("cb=%d\n", cb)); /* for now we assume simple accesses. */
2657 return VERR_INTERNAL_ERROR;
2658 }
2659 return VINF_SUCCESS;
2660}
2661
2662PDMBOTHCBDECL(void) ioapicSetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel)
2663{
2664 /* PDM lock is taken here; @todo add assertion */
2665 IOAPICState *pThis = PDMINS_2_DATA(pDevIns, IOAPICState *);
2666 STAM_COUNTER_INC(&pThis->CTXSUFF(StatSetIrq));
2667 LogFlow(("ioapicSetIrq: iIrq=%d iLevel=%d\n", iIrq, iLevel));
2668 ioapic_set_irq(pThis, iIrq, iLevel);
2669}
2670
2671PDMBOTHCBDECL(void) ioapicSendMsi(PPDMDEVINS pDevIns, RTGCPHYS GCAddr, uint32_t uValue)
2672{
2673 IOAPICState *pThis = PDMINS_2_DATA(pDevIns, IOAPICState *);
2674
2675 LogFlow(("ioapicSendMsi: Address=%p uValue=%\n", GCAddr, uValue));
2676
2677 uint8_t dest = (GCAddr & VBOX_MSI_ADDR_DEST_ID_MASK) >> VBOX_MSI_ADDR_DEST_ID_SHIFT;
2678 uint8_t vector_num = (uValue & VBOX_MSI_DATA_VECTOR_MASK) >> VBOX_MSI_DATA_VECTOR_SHIFT;
2679 uint8_t dest_mode = (GCAddr >> VBOX_MSI_ADDR_DEST_MODE_SHIFT) & 0x1;
2680 uint8_t trigger_mode = (uValue >> VBOX_MSI_DATA_TRIGGER_SHIFT) & 0x1;
2681 uint8_t delivery_mode = (uValue >> VBOX_MSI_DATA_DELIVERY_MODE_SHIFT) & 0x7;
2682 /**
2683 * This bit indicates whether the message should be directed to the
2684 * processor with the lowest interrupt priority among
2685 * processors that can receive the interrupt, ignored ATM.
2686 */
2687 uint8_t redir_hint = (GCAddr >> VBOX_MSI_ADDR_REDIRECTION_SHIFT) & 0x1;
2688
2689 int rc = pThis->CTX_SUFF(pIoApicHlp)->pfnApicBusDeliver(pDevIns,
2690 dest,
2691 dest_mode,
2692 delivery_mode,
2693 vector_num,
2694 0 /* polarity, n/a */,
2695 trigger_mode);
2696 /* We must be sure that attempts to reschedule in R3
2697 never get here */
2698 Assert(rc == VINF_SUCCESS);
2699}
2700
2701#ifdef IN_RING3
2702
2703/**
2704 * Info handler, device version. Dumps I/O APIC state.
2705 *
2706 * @param pDevIns Device instance which registered the info.
2707 * @param pHlp Callback functions for doing output.
2708 * @param pszArgs Argument string. Optional and specific to the handler.
2709 */
2710static DECLCALLBACK(void) ioapicInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
2711{
2712 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2713 uint32_t val;
2714 unsigned i;
2715 unsigned max_redir;
2716
2717 pHlp->pfnPrintf(pHlp, "I/O APIC at %08X:\n", 0xfec00000);
2718 val = s->id << 24; /* Would be nice to call ioapic_mem_readl() directly, but that's not so simple. */
2719 pHlp->pfnPrintf(pHlp, " IOAPICID : %08X\n", val);
2720 pHlp->pfnPrintf(pHlp, " APIC ID = %02X\n", (val >> 24) & 0xff);
2721 val = 0x11 | ((IOAPIC_NUM_PINS - 1) << 16);
2722 max_redir = (val >> 16) & 0xff;
2723 pHlp->pfnPrintf(pHlp, " IOAPICVER : %08X\n", val);
2724 pHlp->pfnPrintf(pHlp, " version = %02X\n", val & 0xff);
2725 pHlp->pfnPrintf(pHlp, " redirs = %d\n", ((val >> 16) & 0xff) + 1);
2726 val = 0;
2727 pHlp->pfnPrintf(pHlp, " IOAPICARB : %08X\n", val);
2728 pHlp->pfnPrintf(pHlp, " arb ID = %02X\n", (val >> 24) & 0xff);
2729 Assert(sizeof(s->ioredtbl) / sizeof(s->ioredtbl[0]) > max_redir);
2730 pHlp->pfnPrintf(pHlp, "I/O redirection table\n");
2731 pHlp->pfnPrintf(pHlp, " idx dst_mode dst_addr mask trigger rirr polarity dlvr_st dlvr_mode vector\n");
2732 for (i = 0; i <= max_redir; ++i)
2733 {
2734 static const char *dmodes[] = { "Fixed ", "LowPri", "SMI ", "Resrvd",
2735 "NMI ", "INIT ", "Resrvd", "ExtINT" };
2736
2737 pHlp->pfnPrintf(pHlp, " %02d %s %02X %d %s %d %s %s %s %3d (%016llX)\n",
2738 i,
2739 s->ioredtbl[i] & (1 << 11) ? "log " : "phys", /* dest mode */
2740 (int)(s->ioredtbl[i] >> 56), /* dest addr */
2741 (int)(s->ioredtbl[i] >> 16) & 1, /* mask */
2742 s->ioredtbl[i] & (1 << 15) ? "level" : "edge ", /* trigger */
2743 (int)(s->ioredtbl[i] >> 14) & 1, /* remote IRR */
2744 s->ioredtbl[i] & (1 << 13) ? "activelo" : "activehi", /* polarity */
2745 s->ioredtbl[i] & (1 << 12) ? "pend" : "idle", /* delivery status */
2746 dmodes[(s->ioredtbl[i] >> 8) & 0x07], /* delivery mode */
2747 (int)s->ioredtbl[i] & 0xff, /* vector */
2748 s->ioredtbl[i] /* entire register */
2749 );
2750 }
2751}
2752
2753/**
2754 * @copydoc FNSSMDEVSAVEEXEC
2755 */
2756static DECLCALLBACK(int) ioapicSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2757{
2758 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2759 ioapic_save(pSSM, s);
2760 return VINF_SUCCESS;
2761}
2762
2763/**
2764 * @copydoc FNSSMDEVLOADEXEC
2765 */
2766static DECLCALLBACK(int) ioapicLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
2767{
2768 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2769
2770 if (ioapic_load(pSSM, s, uVersion)) {
2771 AssertFailed();
2772 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
2773 }
2774 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
2775
2776 return VINF_SUCCESS;
2777}
2778
2779/**
2780 * @copydoc FNPDMDEVRESET
2781 */
2782static DECLCALLBACK(void) ioapicReset(PPDMDEVINS pDevIns)
2783{
2784 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2785 s->pIoApicHlpR3->pfnLock(pDevIns, VERR_INTERNAL_ERROR);
2786 ioapic_reset(s);
2787 IOAPIC_UNLOCK(s);
2788}
2789
2790/**
2791 * @copydoc FNPDMDEVRELOCATE
2792 */
2793static DECLCALLBACK(void) ioapicRelocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
2794{
2795 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2796 s->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2797 s->pIoApicHlpRC = s->pIoApicHlpR3->pfnGetRCHelpers(pDevIns);
2798}
2799
2800/**
2801 * @copydoc FNPDMDEVCONSTRUCT
2802 */
2803static DECLCALLBACK(int) ioapicConstruct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2804{
2805 IOAPICState *s = PDMINS_2_DATA(pDevIns, IOAPICState *);
2806 PDMIOAPICREG IoApicReg;
2807 bool fGCEnabled;
2808 bool fR0Enabled;
2809 int rc;
2810
2811 Assert(iInstance == 0);
2812
2813 /*
2814 * Validate and read the configuration.
2815 */
2816 if (!CFGMR3AreValuesValid(pCfg, "GCEnabled\0" "R0Enabled\0"))
2817 return VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES;
2818
2819 rc = CFGMR3QueryBoolDef(pCfg, "GCEnabled", &fGCEnabled, true);
2820 if (RT_FAILURE(rc))
2821 return PDMDEV_SET_ERROR(pDevIns, rc,
2822 N_("Configuration error: Failed to query boolean value \"GCEnabled\""));
2823
2824 rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &fR0Enabled, true);
2825 if (RT_FAILURE(rc))
2826 return PDMDEV_SET_ERROR(pDevIns, rc,
2827 N_("Configuration error: Failed to query boolean value \"R0Enabled\""));
2828 Log(("IOAPIC: fR0Enabled=%RTbool fGCEnabled=%RTbool\n", fR0Enabled, fGCEnabled));
2829
2830 /*
2831 * Initialize the state data.
2832 */
2833
2834 s->pDevInsR3 = pDevIns;
2835 s->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
2836 s->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
2837 ioapic_reset(s);
2838 s->id = 0;
2839
2840 /*
2841 * Register the IOAPIC and get helpers.
2842 */
2843 IoApicReg.u32Version = PDM_IOAPICREG_VERSION;
2844 IoApicReg.pfnSetIrqR3 = ioapicSetIrq;
2845 IoApicReg.pszSetIrqRC = fGCEnabled ? "ioapicSetIrq" : NULL;
2846 IoApicReg.pszSetIrqR0 = fR0Enabled ? "ioapicSetIrq" : NULL;
2847 IoApicReg.pfnSendMsiR3 = ioapicSendMsi;
2848 IoApicReg.pszSendMsiRC = fGCEnabled ? "ioapicSendMsi" : NULL;
2849 IoApicReg.pszSendMsiR0 = fR0Enabled ? "ioapicSendMsi" : NULL;
2850
2851 rc = PDMDevHlpIOAPICRegister(pDevIns, &IoApicReg, &s->pIoApicHlpR3);
2852 if (RT_FAILURE(rc))
2853 {
2854 AssertMsgFailed(("IOAPICRegister -> %Rrc\n", rc));
2855 return rc;
2856 }
2857
2858 /*
2859 * Register MMIO callbacks and saved state.
2860 */
2861 rc = PDMDevHlpMMIORegister(pDevIns, 0xfec00000, 0x1000, s,
2862 ioapicMMIOWrite, ioapicMMIORead, NULL, "I/O APIC Memory");
2863 if (RT_FAILURE(rc))
2864 return rc;
2865
2866 if (fGCEnabled) {
2867 s->pIoApicHlpRC = s->pIoApicHlpR3->pfnGetRCHelpers(pDevIns);
2868
2869 rc = PDMDevHlpMMIORegisterRC(pDevIns, 0xfec00000, 0x1000, 0,
2870 "ioapicMMIOWrite", "ioapicMMIORead", NULL);
2871 if (RT_FAILURE(rc))
2872 return rc;
2873 }
2874
2875 if (fR0Enabled) {
2876 s->pIoApicHlpR0 = s->pIoApicHlpR3->pfnGetR0Helpers(pDevIns);
2877
2878 rc = PDMDevHlpMMIORegisterR0(pDevIns, 0xfec00000, 0x1000, 0,
2879 "ioapicMMIOWrite", "ioapicMMIORead", NULL);
2880 if (RT_FAILURE(rc))
2881 return rc;
2882 }
2883
2884 rc = PDMDevHlpSSMRegister(pDevIns, 1 /* version */, sizeof(*s), ioapicSaveExec, ioapicLoadExec);
2885 if (RT_FAILURE(rc))
2886 return rc;
2887
2888 /*
2889 * Register debugger info callback.
2890 */
2891 PDMDevHlpDBGFInfoRegister(pDevIns, "ioapic", "Display I/O APIC state.", ioapicInfo);
2892
2893#ifdef VBOX_WITH_STATISTICS
2894 /*
2895 * Statistics.
2896 */
2897 PDMDevHlpSTAMRegister(pDevIns, &s->StatMMIOReadGC, STAMTYPE_COUNTER, "/Devices/IOAPIC/MMIOReadGC", STAMUNIT_OCCURENCES, "Number of IOAPIC MMIO reads in GC.");
2898 PDMDevHlpSTAMRegister(pDevIns, &s->StatMMIOReadHC, STAMTYPE_COUNTER, "/Devices/IOAPIC/MMIOReadHC", STAMUNIT_OCCURENCES, "Number of IOAPIC MMIO reads in HC.");
2899 PDMDevHlpSTAMRegister(pDevIns, &s->StatMMIOWriteGC, STAMTYPE_COUNTER, "/Devices/IOAPIC/MMIOWriteGC", STAMUNIT_OCCURENCES, "Number of IOAPIC MMIO writes in GC.");
2900 PDMDevHlpSTAMRegister(pDevIns, &s->StatMMIOWriteHC, STAMTYPE_COUNTER, "/Devices/IOAPIC/MMIOWriteHC", STAMUNIT_OCCURENCES, "Number of IOAPIC MMIO writes in HC.");
2901 PDMDevHlpSTAMRegister(pDevIns, &s->StatSetIrqGC, STAMTYPE_COUNTER, "/Devices/IOAPIC/SetIrqGC", STAMUNIT_OCCURENCES, "Number of IOAPIC SetIrq calls in GC.");
2902 PDMDevHlpSTAMRegister(pDevIns, &s->StatSetIrqHC, STAMTYPE_COUNTER, "/Devices/IOAPIC/SetIrqHC", STAMUNIT_OCCURENCES, "Number of IOAPIC SetIrq calls in HC.");
2903#endif
2904
2905 return VINF_SUCCESS;
2906}
2907
2908/**
2909 * IO APIC device registration structure.
2910 */
2911const PDMDEVREG g_DeviceIOAPIC =
2912{
2913 /* u32Version */
2914 PDM_DEVREG_VERSION,
2915 /* szName */
2916 "ioapic",
2917 /* szRCMod */
2918 "VBoxDD2GC.gc",
2919 /* szR0Mod */
2920 "VBoxDD2R0.r0",
2921 /* pszDescription */
2922 "I/O Advanced Programmable Interrupt Controller (IO-APIC) Device",
2923 /* fFlags */
2924 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,
2925 /* fClass */
2926 PDM_DEVREG_CLASS_PIC,
2927 /* cMaxInstances */
2928 1,
2929 /* cbInstance */
2930 sizeof(IOAPICState),
2931 /* pfnConstruct */
2932 ioapicConstruct,
2933 /* pfnDestruct */
2934 NULL,
2935 /* pfnRelocate */
2936 ioapicRelocate,
2937 /* pfnIOCtl */
2938 NULL,
2939 /* pfnPowerOn */
2940 NULL,
2941 /* pfnReset */
2942 ioapicReset,
2943 /* pfnSuspend */
2944 NULL,
2945 /* pfnResume */
2946 NULL,
2947 /* pfnAttach */
2948 NULL,
2949 /* pfnDetach */
2950 NULL,
2951 /* pfnQueryInterface. */
2952 NULL,
2953 /* pfnInitComplete */
2954 NULL,
2955 /* pfnPowerOff */
2956 NULL,
2957 /* pfnSoftReset */
2958 NULL,
2959 /* u32VersionEnd */
2960 PDM_DEVREG_VERSION
2961};
2962
2963#endif /* IN_RING3 */
2964#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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