strat9_kernel/s9vm/apic.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : pure model of the guest local APIC (xAPIC / x2APIC).
24//!
25//! This module models the minimal architectural state of a local APIC: MMIO
26//! registers (4 KiB page), x2APIC registers (MSRs), IRR/ISR, priority (TPR/PPR),
27//! EOI and IPI. It **touches no hardware**: the kernel layer reads/writes
28//! the registers to emulate guest accesses and decide injections.
29//!
30//! The encodings come from the Intel documentation (SDM vol. 3A, chapter
31//! "Advanced Programmable Interrupt Controller"). No constant specific to
32//! a particular hypervisor is used.
33//!
34//! ## Injection policy
35//!
36//! The model is deliberately kept separate from the control block's interrupt
37//! windows: it answers "which interrupt is deliverable?" via
38//! [`LocalApic::pending_vector`], and the caller decides when (RFLAGS.IF,
39//! interrupt window, etc.). Architectural priority is honored:
40//! the smallest priority class strictly greater than the PPR, then the
41//! smallest vector of that class.
42//!
43//! ## Local vector timer
44//!
45//! The local APIC timer is modeled with the architectural registers: the LVT
46//! timer entry (`0x320`, vector/mask/mode), the initial count (`0x380`), the
47//! read-only current count (`0x390`) and the divide configuration (`0x3E0`).
48//! Counts are expressed in **APIC timer units**: one unit is one tick of the
49//! APIC bus clock after the divide configuration has been applied. The model
50//! is pure, so it cannot read the bus clock. Two helpers exist:
51//!
52//! - [`LocalApic::advance`] is the raw model helper: the caller passes elapsed
53//! time already expressed in APIC timer input units (bus ticks before the
54//! divide) and the model TSC advances by the same value;
55//! - [`LocalApic::advance_tsc`] is the host-facing helper: the caller passes
56//! host TSC cycles and the TSC frequency, and the model converts them to
57//! APIC input ticks with the configured nominal bus frequency
58//! ([`DEFAULT_APIC_BUS_HZ`], overridable with
59//! [`LocalApic::set_apic_bus_hz`]) before applying the divide. The model TSC
60//! used by TSC-deadline mode always advances by the raw TSC cycles.
61//!
62//! Conversion formula: `bus_ticks = tsc_cycles * bus_hz / tsc_hz`, computed
63//! with a remainder carried across calls so that a slow bus clock does not
64//! lose ticks; the count-based timer then divides `bus_ticks` by the
65//! architectural divide value. Arithmetic saturates, and a zero `tsc_hz` or a
66//! zero bus frequency disables the count conversion instead of dividing by
67//! zero.
68//!
69//! The real APIC bus clock is not discoverable from the model, so the guest
70//! timer period remains **approximate**: it is correct to the extent that the
71//! nominal bus frequency matches the host. This limitation is what
72//! [`DEFAULT_APIC_BUS_HZ`] documents; a caller that knows the host bus clock
73//! must configure it explicitly.
74//!
75//! Supported modes:
76//!
77//! - one-shot: expires once, raises the LVT vector, then stays stopped;
78//! - periodic: reloads the initial count at every expiry and raises the
79//! LVT vector again;
80//! - TSC-deadline: the `IA32_TSC_DEADLINE` MSR (`0x6E0`) sets an absolute
81//! deadline in model-TSC units. The model TSC is advanced by
82//! [`LocalApic::advance`] and can be aligned once with
83//! [`LocalApic::set_tsc`] if the caller knows the guest TSC epoch.
84//!
85//! A masked LVT entry keeps counting (and keeps reloading in periodic mode)
86//! but does not raise a vector. Writing an initial count of zero disables the
87//! timer. All arithmetic saturates; the divide configuration is decoded with
88//! the architectural encoding and never divides by zero.
89
90/// Size of the local APIC MMIO page.
91pub const PAGE_SIZE: usize = 0x1000;
92
93/// Offsets of the xAPIC MMIO registers.
94pub mod reg {
95 pub const ID: usize = 0x020;
96 pub const VERSION: usize = 0x030;
97 pub const TPR: usize = 0x080;
98 pub const PPR: usize = 0x0A0;
99 pub const EOI: usize = 0x0B0;
100 pub const LDR: usize = 0x0D0;
101 pub const DFR: usize = 0x0E0;
102 pub const SVR: usize = 0x0F0;
103 pub const ISR: usize = 0x100;
104 pub const TMR: usize = 0x180;
105 pub const IRR: usize = 0x200;
106 pub const ESR: usize = 0x280;
107 pub const ICR_LOW: usize = 0x300;
108 pub const ICR_HIGH: usize = 0x310;
109 pub const LVT_TIMER: usize = 0x320;
110 pub const LVT_THERMAL: usize = 0x330;
111 pub const LVT_PERF: usize = 0x340;
112 pub const LVT_LINT0: usize = 0x350;
113 pub const LVT_LINT1: usize = 0x360;
114 pub const LVT_ERROR: usize = 0x370;
115 pub const INITIAL_COUNT: usize = 0x380;
116 pub const CURRENT_COUNT: usize = 0x390;
117 pub const DIVIDE_CONFIG: usize = 0x3E0;
118 pub const SELF_IPI: usize = 0x3F0;
119}
120
121/// x2APIC registers exposed by `RDMSR`/`WRMSR`.
122pub mod x2apic {
123 pub const ID: u32 = 0x802;
124 pub const VERSION: u32 = 0x803;
125 pub const TPR: u32 = 0x808;
126 pub const PPR: u32 = 0x80A;
127 pub const EOI: u32 = 0x80B;
128 pub const LDR: u32 = 0x80D;
129 pub const DFR: u32 = 0x80E;
130 pub const SVR: u32 = 0x80F;
131 pub const ISR: u32 = 0x810;
132 pub const IRR: u32 = 0x820;
133 pub const ESR: u32 = 0x828;
134 pub const ICR: u32 = 0x830;
135 pub const LVT_TIMER: u32 = 0x832;
136 pub const INITIAL_COUNT: u32 = 0x838;
137 pub const CURRENT_COUNT: u32 = 0x839;
138 pub const DIVIDE_CONFIG: u32 = 0x83E;
139 pub const SELF_IPI: u32 = 0x83F;
140}
141
142/// Advertised hardware version (integrated xAPIC family, 6 LVTs).
143pub const VERSION_VALUE: u32 = 0x0005_0014;
144/// Spurious register: enabled, vector 0xFF.
145pub const SVR_DEFAULT: u32 = 0x0000_01FF;
146/// Vector of the spurious register.
147pub const SPURIOUS_VECTOR: u8 = 0xFF;
148/// Enable bit of the spurious register.
149pub const SVR_ENABLE: u32 = 1 << 8;
150/// `IA32_TSC_DEADLINE` MSR used by the LVT TSC-deadline timer mode.
151pub const TSC_DEADLINE_MSR: u32 = 0x6E0;
152
153/// Default nominal APIC timer bus frequency, in hertz.
154///
155/// The architectural APIC bus clock is not discoverable from the pure model,
156/// so s9vm uses a documented nominal policy: 100 MHz, the common PC-chipset
157/// APIC bus frequency. The guest timer period is exact only to the extent that
158/// this nominal value matches the host; a caller that knows the real bus clock
159/// overrides it with [`LocalApic::set_apic_bus_hz`].
160pub const DEFAULT_APIC_BUS_HZ: u64 = 100_000_000;
161
162/// LVT timer mask bit (bit 16 of the LVT timer entry).
163pub const LVT_MASK: u32 = 1 << 16;
164/// LVT timer mode field (bits 18:17).
165pub const LVT_MODE_SHIFT: u32 = 17;
166/// LVT timer mode field mask.
167pub const LVT_MODE_MASK: u32 = 0x3 << LVT_MODE_SHIFT;
168
169/// Operating mode of the local vector timer.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum TimerMode {
172 /// One-shot: the count expires once and the timer stops.
173 OneShot,
174 /// Periodic: the initial count is reloaded at every expiry.
175 Periodic,
176 /// TSC-deadline: an absolute model-TSC deadline drives the expiry.
177 TscDeadline,
178 /// Reserved encoding: the timer does not count and raises nothing.
179 Reserved,
180}
181
182/// Delivery mode in the ICR register (bits 10:8).
183pub mod delivery {
184 pub const FIXED: u32 = 0;
185 pub const LOWEST: u32 = 1;
186 pub const SMI: u32 = 2;
187 pub const NMI: u32 = 4;
188 pub const INIT: u32 = 5;
189 pub const STARTUP: u32 = 6;
190}
191
192/// Shorthand destination in the ICR register (bits 19:18).
193pub mod shorthand {
194 pub const NO_SHORTHAND: u32 = 0;
195 pub const SELF: u32 = 1;
196 pub const ALL_INCLUDING_SELF: u32 = 2;
197 pub const ALL_EXCLUDING_SELF: u32 = 3;
198}
199
200/// Complete state of a guest local APIC.
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub struct LocalApic {
203 /// APIC identifier (ID register, 8 significant bits in field 31:24).
204 id: u32,
205 /// Task priority (TPR), bits 7:0 significant.
206 tpr: u8,
207 /// Spurious register (SVR).
208 svr: u32,
209 /// Error status register.
210 esr: u32,
211 /// In-Service registers (8 x 32 bits = 256 vectors).
212 isr: [u32; 8],
213 /// In-Request registers (8 x 32 bits = 256 vectors).
214 irr: [u32; 8],
215 /// LVT: timer, thermal, perf, LINT0, LINT1, error.
216 lvt: [u32; 6],
217 /// ICR low/high.
218 icr_low: u32,
219 icr_high: u32,
220 /// Initial and current timer count.
221 initial_count: u32,
222 current_count: u32,
223 /// Timer divider.
224 divide_config: u32,
225 /// True while a one-shot/periodic count is running.
226 timer_armed: bool,
227 /// Sub-tick remainder of the divide scaling, in APIC timer input units.
228 timer_fraction: u64,
229 /// Nominal APIC timer bus frequency used by [`LocalApic::advance_tsc`].
230 apic_bus_hz: u64,
231 /// Remainder of the TSC-to-bus-tick conversion, in TSC cycles.
232 tsc_fraction: u64,
233 /// Monotonic model TSC, advanced by [`LocalApic::advance`].
234 tsc: u64,
235 /// Absolute TSC-deadline value written to `IA32_TSC_DEADLINE`.
236 tsc_deadline: u64,
237 /// True while the TSC-deadline timer is armed.
238 tsc_deadline_armed: bool,
239}
240
241impl LocalApic {
242 /// Creates a local APIC for `apic_id`, LVTs masked, SVR enabled.
243 pub const fn new(apic_id: u32) -> Self {
244 Self {
245 id: (apic_id & 0xFF) << 24,
246 tpr: 0,
247 svr: SVR_DEFAULT,
248 esr: 0,
249 isr: [0; 8],
250 irr: [0; 8],
251 lvt: [0x0001_0000; 6],
252 icr_low: 0,
253 icr_high: 0,
254 initial_count: 0,
255 current_count: 0,
256 divide_config: 0,
257 timer_armed: false,
258 timer_fraction: 0,
259 apic_bus_hz: DEFAULT_APIC_BUS_HZ,
260 tsc_fraction: 0,
261 tsc: 0,
262 tsc_deadline: 0,
263 tsc_deadline_armed: false,
264 }
265 }
266
267 /// APIC identifier (8-bit value, not shifted).
268 pub const fn apic_id(&self) -> u32 {
269 self.id >> 24
270 }
271
272 /// Current task priority.
273 pub const fn tpr(&self) -> u8 {
274 self.tpr
275 }
276
277 /// Processor priority (TPR and ISR combined), on 8 bits.
278 pub fn ppr(&self) -> u8 {
279 let mut ppr = self.tpr;
280 for index in (0..8).rev() {
281 if self.isr[index] != 0 {
282 // The PPR is a class priority: the low nibble of the
283 // highest in-service vector is ignored.
284 ppr = ppr.max(highest_vector(index, self.isr[index]) & 0xF0);
285 break;
286 }
287 }
288 ppr
289 }
290
291 /// True if the spurious register enables interrupts.
292 pub const fn enabled(&self) -> bool {
293 self.svr & SVR_ENABLE != 0
294 }
295
296 /// True if at least one vector is pending.
297 pub fn has_pending(&self) -> bool {
298 self.irr.iter().any(|word| *word != 0)
299 }
300
301 /// Injects a vector into the IRR (idempotent).
302 pub fn inject(&mut self, vector: u8) {
303 self.irr[(vector as usize) >> 5] |= 1 << (vector & 31);
304 }
305
306 /// Highest-priority deliverable vector, without modifying the state.
307 pub fn pending_vector(&self) -> Option<u8> {
308 if !self.enabled() {
309 return None;
310 }
311 let ppr = self.ppr();
312 let ppr_class = priority_class(u32::from(ppr));
313 let mut best: Option<u8> = None;
314 for index in 0..8u8 {
315 let mut word = self.irr[index as usize];
316 while word != 0 {
317 let bit = word.trailing_zeros() as u8;
318 let vector = index * 32 + bit;
319 word &= word - 1;
320 if vector < 16 {
321 continue;
322 }
323 let class = priority_class(u32::from(vector));
324 // Priority strictly greater than the PPR: the class must be
325 // greater (vectors of the same class are blocked,
326 // as required by the architecture).
327 if class > ppr_class {
328 best = Some(match best {
329 Some(current) => current.min(vector),
330 None => vector,
331 });
332 }
333 }
334 }
335 best
336 }
337
338 /// Moves the deliverable vector from the IRR to the ISR and returns it.
339 pub fn service(&mut self) -> Option<u8> {
340 let vector = self.pending_vector()?;
341 self.irr[(vector as usize) >> 5] &= !(1 << (vector & 31));
342 self.isr[(vector as usize) >> 5] |= 1 << (vector & 31);
343 Some(vector)
344 }
345
346 /// Records an EOI: removes the highest-priority vector from the ISR.
347 pub fn eoi(&mut self) {
348 for index in (0..8).rev() {
349 let word = self.isr[index];
350 if word != 0 {
351 let bit = 31 - word.leading_zeros() as usize;
352 self.isr[index] &= !(1u32 << bit);
353 return;
354 }
355 }
356 }
357
358 /// True if a vector is in service.
359 pub fn in_service(&self) -> bool {
360 self.isr.iter().any(|word| *word != 0)
361 }
362
363 /// Vector programmed in the LVT timer entry.
364 pub const fn timer_vector(&self) -> u8 {
365 (self.lvt[0] & 0xFF) as u8
366 }
367
368 /// True if the LVT timer entry is masked.
369 pub const fn timer_masked(&self) -> bool {
370 self.lvt[0] & LVT_MASK != 0
371 }
372
373 /// Operating mode of the timer, decoded from the LVT entry.
374 pub const fn timer_mode(&self) -> TimerMode {
375 match (self.lvt[0] & LVT_MODE_MASK) >> LVT_MODE_SHIFT {
376 0 => TimerMode::OneShot,
377 1 => TimerMode::Periodic,
378 2 => TimerMode::TscDeadline,
379 _ => TimerMode::Reserved,
380 }
381 }
382
383 /// Current divide value decoded from the divide configuration register.
384 pub const fn timer_divide(&self) -> u32 {
385 divide_value(self.divide_config)
386 }
387
388 /// True while either count-based or TSC-deadline timer is running.
389 pub const fn timer_armed(&self) -> bool {
390 self.timer_armed || self.tsc_deadline_armed
391 }
392
393 /// Current timer count (`0` once a one-shot timer has expired).
394 pub const fn current_count(&self) -> u32 {
395 self.current_count
396 }
397
398 /// Last value written to the initial-count register.
399 pub const fn initial_count(&self) -> u32 {
400 self.initial_count
401 }
402
403 /// Absolute TSC-deadline value last written to `IA32_TSC_DEADLINE`.
404 pub const fn tsc_deadline(&self) -> u64 {
405 self.tsc_deadline
406 }
407
408 /// Programs the timer with `initial_count` (`0` disables it).
409 ///
410 /// In one-shot and periodic modes this loads the current count and starts
411 /// counting. In TSC-deadline and reserved modes the register is stored but
412 /// the count-based timer stays stopped, matching the architectural rule
413 /// that the initial count is ignored in TSC-deadline mode.
414 pub fn arm(&mut self, initial_count: u32) {
415 self.initial_count = initial_count;
416 self.timer_fraction = 0;
417 match self.timer_mode() {
418 TimerMode::OneShot | TimerMode::Periodic => {
419 self.current_count = initial_count;
420 self.timer_armed = initial_count != 0;
421 }
422 TimerMode::TscDeadline | TimerMode::Reserved => {
423 self.current_count = 0;
424 self.timer_armed = false;
425 }
426 }
427 }
428
429 /// Writes the `IA32_TSC_DEADLINE` MSR.
430 ///
431 /// A zero value disables the deadline. The value is absolute in model-TSC
432 /// units; a deadline already in the past raises the LVT vector immediately
433 /// (unless masked). Writes are ignored for the timer state unless the LVT
434 /// entry is in TSC-deadline mode.
435 pub fn set_tsc_deadline(&mut self, deadline: u64) {
436 self.tsc_deadline = deadline;
437 self.tsc_deadline_armed = false;
438 if deadline == 0 || self.timer_mode() != TimerMode::TscDeadline {
439 return;
440 }
441 self.tsc_deadline_armed = true;
442 if self.tsc >= deadline {
443 self.expire_tsc_deadline();
444 }
445 }
446
447 /// Aligns the model TSC with a caller-known absolute value.
448 ///
449 /// The model starts at zero and is normally advanced by
450 /// [`Self::advance`]; this hook lets a caller that knows the guest TSC
451 /// epoch seed it once, so absolute `IA32_TSC_DEADLINE` values can be
452 /// interpreted.
453 pub fn set_tsc(&mut self, tsc: u64) {
454 self.tsc = tsc;
455 if self.tsc_deadline_armed && self.tsc >= self.tsc_deadline {
456 self.expire_tsc_deadline();
457 }
458 }
459
460 /// Advances the timer by `cycles` APIC timer input units.
461 ///
462 /// The caller passes the elapsed time already expressed in APIC timer
463 /// input units (bus ticks before the divide). Count-based modes divide it
464 /// by the configured divide value and decrement the current count;
465 /// TSC-deadline mode compares the model TSC with the programmed deadline.
466 /// Expiry raises the LVT vector through the IRR, except when the LVT entry
467 /// is masked.
468 ///
469 /// This is the raw model helper, kept for tests and for callers that
470 /// already work in bus ticks. A caller holding host TSC cycles and a TSC
471 /// frequency must use [`Self::advance_tsc`], which performs the
472 /// conversion.
473 pub fn advance(&mut self, cycles: u64) {
474 self.tsc = self.tsc.saturating_add(cycles);
475 if self.tsc_deadline_armed && self.tsc >= self.tsc_deadline {
476 self.expire_tsc_deadline();
477 }
478 if !self.timer_armed {
479 return;
480 }
481 match self.timer_mode() {
482 TimerMode::OneShot | TimerMode::Periodic => self.advance_count(cycles),
483 TimerMode::TscDeadline | TimerMode::Reserved => self.timer_armed = false,
484 }
485 }
486
487 /// Nominal APIC timer bus frequency, in hertz.
488 pub const fn apic_bus_hz(&self) -> u64 {
489 self.apic_bus_hz
490 }
491
492 /// Changes the nominal APIC timer bus frequency.
493 ///
494 /// The conversion remainder is reset because its unit depends on the bus
495 /// frequency. A zero value disables the count-based conversion of
496 /// [`Self::advance_tsc`] (the model TSC still advances).
497 pub fn set_apic_bus_hz(&mut self, bus_hz: u64) {
498 self.apic_bus_hz = bus_hz;
499 self.tsc_fraction = 0;
500 }
501
502 /// Advances the model by host TSC `cycles`, converting to APIC ticks.
503 ///
504 /// `tsc_hz` is the host TSC frequency in hertz. The count-based timer is
505 /// decremented by:
506 ///
507 /// `bus_ticks = (cycles * apic_bus_hz + remainder) / tsc_hz`
508 ///
509 /// where `remainder` is carried across calls so that the average
510 /// conversion rate stays exact even when a call spans less than one bus
511 /// tick. The model TSC used by TSC-deadline mode advances by the raw
512 /// `cycles`, without conversion: a deadline is an absolute TSC value.
513 ///
514 /// A zero `tsc_hz` or a zero bus frequency disables the count conversion
515 /// (the model TSC still advances and deadlines are still detected), so a
516 /// caller without a detected frequency degrades gracefully instead of
517 /// dividing by zero. Arithmetic saturates.
518 pub fn advance_tsc(&mut self, cycles: u64, tsc_hz: u64) {
519 self.tsc = self.tsc.saturating_add(cycles);
520 if self.tsc_deadline_armed && self.tsc >= self.tsc_deadline {
521 self.expire_tsc_deadline();
522 }
523 if !self.timer_armed {
524 return;
525 }
526 match self.timer_mode() {
527 TimerMode::OneShot | TimerMode::Periodic => {
528 if tsc_hz == 0 || self.apic_bus_hz == 0 {
529 return;
530 }
531 let numerator = u128::from(cycles)
532 .saturating_mul(u128::from(self.apic_bus_hz))
533 .saturating_add(u128::from(self.tsc_fraction));
534 let bus_ticks = numerator / u128::from(tsc_hz);
535 self.tsc_fraction = (numerator % u128::from(tsc_hz)) as u64;
536 let bus_ticks = if bus_ticks > u128::from(u64::MAX) {
537 u64::MAX
538 } else {
539 bus_ticks as u64
540 };
541 self.advance_count(bus_ticks);
542 }
543 TimerMode::TscDeadline | TimerMode::Reserved => {}
544 }
545 }
546
547 /// Decrements the count-based timer by the divided elapsed cycles.
548 fn advance_count(&mut self, cycles: u64) {
549 let divide = u64::from(self.timer_divide());
550 let total = cycles.saturating_add(self.timer_fraction);
551 let ticks = total / divide;
552 self.timer_fraction = total % divide;
553 if ticks == 0 {
554 return;
555 }
556
557 match self.timer_mode() {
558 TimerMode::OneShot => {
559 let current = u64::from(self.current_count);
560 if ticks >= current {
561 self.current_count = 0;
562 self.timer_armed = false;
563 self.raise_timer_vector();
564 } else {
565 self.current_count = (current - ticks) as u32;
566 }
567 }
568 TimerMode::Periodic => {
569 let reload = self.initial_count;
570 if reload == 0 {
571 self.current_count = 0;
572 self.timer_armed = false;
573 return;
574 }
575 let current = u64::from(self.current_count);
576 if ticks < current {
577 self.current_count = (current - ticks) as u32;
578 return;
579 }
580 // One expiry at `current`, then one every `reload` ticks.
581 let after_first = ticks - current;
582 let remainder = after_first % u64::from(reload);
583 self.current_count = reload - remainder as u32;
584 self.timer_armed = true;
585 self.raise_timer_vector();
586 }
587 TimerMode::TscDeadline | TimerMode::Reserved => self.timer_armed = false,
588 }
589 }
590
591 /// Raises the LVT vector unless the entry is masked.
592 fn raise_timer_vector(&mut self) {
593 if !self.timer_masked() {
594 let vector = self.timer_vector();
595 self.inject(vector);
596 }
597 }
598
599 /// Completes a TSC-deadline expiry.
600 fn expire_tsc_deadline(&mut self) {
601 self.tsc_deadline_armed = false;
602 self.raise_timer_vector();
603 }
604
605 /// Applies a write to the LVT timer entry, keeping the timer state
606 /// consistent with the newly selected mode.
607 fn write_lvt_timer(&mut self, value: u32) {
608 self.lvt[0] = value;
609 match self.timer_mode() {
610 TimerMode::TscDeadline => {
611 self.timer_armed = false;
612 // A deadline written before the mode was selected still
613 // applies once the entry is switched to TSC-deadline mode.
614 if self.tsc_deadline != 0 {
615 self.tsc_deadline_armed = true;
616 if self.tsc >= self.tsc_deadline {
617 self.expire_tsc_deadline();
618 }
619 }
620 }
621 TimerMode::OneShot | TimerMode::Periodic => self.tsc_deadline_armed = false,
622 TimerMode::Reserved => {
623 self.timer_armed = false;
624 self.tsc_deadline_armed = false;
625 }
626 }
627 }
628
629 /// Reads an MMIO register (address relative to the APIC page).
630 ///
631 /// Unimplemented offsets return 0 (guest access tolerated).
632 pub fn mmio_read(&self, offset: usize) -> u32 {
633 if let Some(index) = isr_index(offset, reg::ISR) {
634 return self.isr[index];
635 }
636 if let Some(index) = isr_index(offset, reg::IRR) {
637 return self.irr[index];
638 }
639 match offset {
640 reg::ID => self.id,
641 reg::VERSION => VERSION_VALUE,
642 reg::TPR => u32::from(self.tpr),
643 reg::PPR => u32::from(self.ppr()),
644 reg::SVR => self.svr,
645 reg::ESR => self.esr,
646 reg::ICR_LOW => self.icr_low,
647 reg::ICR_HIGH => self.icr_high,
648 reg::INITIAL_COUNT => self.initial_count,
649 reg::CURRENT_COUNT => self.current_count,
650 reg::DIVIDE_CONFIG => self.divide_config,
651 reg::LVT_TIMER => self.lvt[0],
652 reg::LVT_THERMAL => self.lvt[1],
653 reg::LVT_PERF => self.lvt[2],
654 reg::LVT_LINT0 => self.lvt[3],
655 reg::LVT_LINT1 => self.lvt[4],
656 reg::LVT_ERROR => self.lvt[5],
657 _ => 0,
658 }
659 }
660
661 /// Writes an MMIO register. Unimplemented offsets are ignored.
662 pub fn mmio_write(&mut self, offset: usize, value: u32) {
663 match offset {
664 reg::TPR => self.tpr = (value & 0xFF) as u8,
665 reg::EOI => self.eoi(),
666 reg::SVR => self.svr = value & 0x0000_01FF,
667 reg::ESR => self.esr = value,
668 reg::ICR_LOW => self.write_icr_low(value),
669 reg::ICR_HIGH => self.icr_high = value & 0xFF00_0000,
670 reg::INITIAL_COUNT => self.arm(value),
671 reg::DIVIDE_CONFIG => self.divide_config = value & 0xB,
672 reg::LVT_TIMER => self.write_lvt_timer(value),
673 reg::LVT_THERMAL => self.lvt[1] = value,
674 reg::LVT_PERF => self.lvt[2] = value,
675 reg::LVT_LINT0 => self.lvt[3] = value,
676 reg::LVT_LINT1 => self.lvt[4] = value,
677 reg::LVT_ERROR => self.lvt[5] = value,
678 reg::SELF_IPI => self.inject((value & 0xFF) as u8),
679 _ => {}
680 }
681 }
682
683 /// Handles an ICR-low write: fixed IPI to self or NMI.
684 fn write_icr_low(&mut self, value: u32) {
685 self.icr_low = value;
686 let delivery_mode = (value >> 8) & 0x7;
687 let destination = (value >> 18) & 0x3;
688 let vector = (value & 0xFF) as u8;
689 match (delivery_mode, destination) {
690 (delivery::FIXED, shorthand::SELF) | (delivery::LOWEST, shorthand::SELF) => {
691 self.inject(vector);
692 }
693 (delivery::NMI, _) | (delivery::INIT, _) | (delivery::STARTUP, _) => {
694 // Handled outside the APIC (dedicated injection / reset): we
695 // accept the write so that the guest can continue.
696 }
697 _ => {
698 // External destination not modeled in P1 (a single guest CPU).
699 }
700 }
701 }
702
703 /// Reads an x2APIC MSR. Returns `None` outside the `0x800..=0x8FF` range.
704 pub fn x2apic_read(&self, msr: u32) -> Option<u64> {
705 if let Some(index) = isr_msr_index(msr, x2apic::ISR) {
706 return Some(u64::from(self.isr[index]));
707 }
708 if let Some(index) = isr_msr_index(msr, x2apic::IRR) {
709 return Some(u64::from(self.irr[index]));
710 }
711 let value: u64 = match msr {
712 x2apic::ID => u64::from(self.id),
713 x2apic::VERSION => u64::from(VERSION_VALUE),
714 x2apic::TPR => u64::from(self.tpr),
715 x2apic::PPR => u64::from(self.ppr()),
716 x2apic::EOI => 0,
717 x2apic::LDR => (u64::from(self.apic_id()) << 24) | 0x01_0000,
718 x2apic::DFR => 0x0000_00FF,
719 x2apic::SVR => u64::from(self.svr),
720 x2apic::ESR => u64::from(self.esr),
721 x2apic::ICR => ((self.icr_high as u64) << 32) | u64::from(self.icr_low),
722 x2apic::LVT_TIMER => u64::from(self.lvt[0]),
723 x2apic::INITIAL_COUNT => u64::from(self.initial_count),
724 x2apic::CURRENT_COUNT => u64::from(self.current_count),
725 x2apic::DIVIDE_CONFIG => u64::from(self.divide_config),
726 _ => return None,
727 };
728 Some(value)
729 }
730
731 /// Writes an x2APIC MSR. Returns `false` if the MSR is not modeled.
732 pub fn x2apic_write(&mut self, msr: u32, value: u64) -> bool {
733 match msr {
734 x2apic::TPR => self.tpr = (value & 0xFF) as u8,
735 x2apic::EOI => self.eoi(),
736 x2apic::SVR => self.svr = (value as u32) & 0x0000_01FF,
737 x2apic::ESR => self.esr = value as u32,
738 x2apic::ICR => {
739 self.icr_high = (value >> 32) as u32;
740 self.write_icr_low(value as u32);
741 }
742 x2apic::LVT_TIMER => self.write_lvt_timer(value as u32),
743 x2apic::INITIAL_COUNT => self.arm(value as u32),
744 x2apic::DIVIDE_CONFIG => self.divide_config = (value as u32) & 0xB,
745 x2apic::SELF_IPI => self.inject((value & 0xFF) as u8),
746 _ => return false,
747 }
748 true
749 }
750}
751
752/// Highest vector of an ISR/IRR word (`index` = word 0..7).
753fn highest_vector(index: usize, word: u32) -> u8 {
754 (index as u8) * 32 + (31 - word.leading_zeros() as u8)
755}
756
757/// Index of an ISR/IRR register in MMIO (16-byte stride, 8 registers).
758fn isr_index(offset: usize, base: usize) -> Option<usize> {
759 if offset < base || offset >= base + 8 * 16 {
760 return None;
761 }
762 let delta = offset - base;
763 if delta % 16 != 0 {
764 return None;
765 }
766 Some(delta / 16)
767}
768
769/// Index of an ISR/IRR register in x2APIC (8 consecutive MSRs).
770fn isr_msr_index(msr: u32, base: u32) -> Option<usize> {
771 if msr < base || msr >= base + 8 {
772 return None;
773 }
774 Some((msr - base) as usize)
775}
776
777/// Priority class of a vector (bits 7:4).
778pub const fn priority_class(vector: u32) -> u8 {
779 ((vector >> 4) & 0xF) as u8
780}
781
782/// Decodes the divide configuration register into a divisor (never zero).
783///
784/// Architectural encoding (`bits 3, 1, 0`): `000` divides by 2, `001` by 4,
785/// `010` by 8, `011` by 16, `100` by 32, `101` by 64, `110` by 128 and `111`
786/// by 1. Bit 2 is reserved and ignored. Any unexpected value falls back to
787/// the reset encoding (divide by 2), so this function is total.
788pub const fn divide_value(config: u32) -> u32 {
789 match config & 0xB {
790 0 => 2,
791 1 => 4,
792 2 => 8,
793 3 => 16,
794 8 => 32,
795 9 => 64,
796 10 => 128,
797 _ => 1,
798 }
799}