1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! IO-APIC emulator.
//!
//! Currently this supports IO-APIC version 0x11, from the PIIX4 era. This
//! version does not support an EOI register (unlike version 0x20 and newer).

use self::spec::IndexRegister;
use self::spec::IoApicId;
use self::spec::IoApicVersion;
use self::spec::RedirectionEntry;
use self::spec::IOAPIC_DEVICE_MMIO_REGION_SIZE;
use self::spec::IO_APIC_VERSION;
use self::spec::REDIRECTION_WRITE_MASK;
use crate::ioapic::spec::Register;
use crate::ioapic::spec::IOAPIC_DEVICE_MMIO_REGION_MASK;
use chipset_device::interrupt::HandleEoi;
use chipset_device::interrupt::LineInterruptTarget;
use chipset_device::io::IoError;
use chipset_device::io::IoResult;
use chipset_device::mmio::MmioIntercept;
use chipset_device::ChipsetDevice;
use inspect::Inspect;
use inspect::InspectMut;
use inspect_counters::Counter;
use std::fmt;
use std::fmt::Debug;
use std::ops::RangeInclusive;
use vmcore::device_state::ChangeDeviceState;
use x86defs::apic::DeliveryMode;
use x86defs::msi::MsiAddress;
use x86defs::msi::MsiData;

pub const IOAPIC_DEVICE_MMIO_REGION_BASE_ADDRESS: u64 = 0xfec00000;

mod spec {
    use bitfield_struct::bitfield;
    use inspect::Inspect;
    use open_enum::open_enum;

    /// The version reported by the Intel 82093AA.
    pub const IO_APIC_VERSION: u8 = 0x11;

    open_enum! {
        pub enum Register: u64 {
            INDEX = 0,
            DATA = 0x10,
        }
    }

    open_enum! {
        #[derive(Inspect)]
        #[inspect(debug)]
        pub enum IndexRegister: u8 {
            ID = 0,
            VERSION = 1,
            ARBITRATION_ID = 2,
            REDIRECTION_TABLE_START = 0x10,
        }
    }

    pub const IOAPIC_DEVICE_MMIO_REGION_SIZE: u64 = 0x20;
    pub const IOAPIC_DEVICE_MMIO_REGION_MASK: u64 = IOAPIC_DEVICE_MMIO_REGION_SIZE - 1;

    #[derive(Inspect)]
    #[bitfield(u64)]
    #[rustfmt::skip]
    pub struct RedirectionEntry {
        #[bits(8)] pub vector: u8,
        #[bits(3)] pub delivery_mode: u8,
        #[bits(1)] pub destination_mode_logical: bool,
        #[bits(1)] pub delivery_status: bool,
        #[bits(1)] pub active_low: bool,
        #[bits(1)] pub remote_irr: bool,
        #[bits(1)] pub trigger_mode_level: bool,
        #[bits(1)] pub masked: bool,
        #[bits(15)] _unused: u32,
        #[bits(16)] _unused2: u32,
        #[bits(8)] pub extended_destination: u8,
        #[bits(8)] pub destination: u8,
    }

    /// The bits of the redirection entry that can be set by the guest.
    pub const REDIRECTION_WRITE_MASK: u64 = RedirectionEntry::new()
        .with_vector(0xff)
        .with_delivery_mode(0x7)
        .with_destination_mode_logical(true)
        .with_active_low(true)
        .with_trigger_mode_level(true)
        .with_masked(true)
        .with_destination(0xff)
        .with_extended_destination(0xff)
        .0;

    #[bitfield(u32)]
    pub struct IoApicId {
        #[bits(24)]
        _reserved: u32,
        #[bits(4)]
        pub id: u8,
        #[bits(4)]
        _reserved2: u32,
    }

    #[bitfield(u32)]
    pub struct IoApicVersion {
        pub version: u8,
        _reserved: u8,
        pub max_entry: u8,
        _reserved2: u8,
    }
}

impl RedirectionEntry {
    fn init() -> Self {
        Self::new()
            .with_destination_mode_logical(true)
            .with_masked(true)
    }

    /// Converts the entry to MSI format.
    fn as_msi(&self) -> Option<(u64, u32)> {
        if self.masked() {
            return None;
        }

        // Copy the redirection entry's bits to the MSI as defined in the Intel
        // ICHx datasheets.
        let address = MsiAddress::new()
            .with_address(x86defs::msi::MSI_ADDRESS)
            .with_destination(self.destination())
            .with_extended_destination(self.extended_destination())
            .with_destination_mode_logical(self.destination_mode_logical())
            .with_redirection_hint(self.delivery_mode() == DeliveryMode::LOWEST_PRIORITY.0);

        let data = MsiData::new()
            .with_assert(true)
            .with_destination_mode_logical(self.destination_mode_logical())
            .with_delivery_mode(self.delivery_mode())
            .with_trigger_mode_level(self.trigger_mode_level())
            .with_vector(self.vector());

        Some((u32::from(address).into(), data.into()))
    }
}

#[derive(Debug, Inspect)]
struct IrqEntry {
    #[inspect(flatten)]
    redirection: RedirectionEntry,
    line_level: bool,
    #[inspect(skip)]
    registered_request: Option<(u64, u32)>,
}

impl IrqEntry {
    fn assert(&mut self, routing: &dyn IoApicRouting, stats: &mut IoApicStats, n: u8) {
        let old_level = std::mem::replace(&mut self.line_level, true);
        self.evaluate(routing, stats, n, !old_level);
    }

    fn deassert(&mut self) {
        self.line_level = false;
        // No need to evaluate; this interrupt definitely doesn't need to be
        // delivered now.
    }

    fn eoi(&mut self, vector: u32, routing: &dyn IoApicRouting, stats: &mut IoApicStats, n: u8) {
        if self.redirection.vector() as u32 == vector {
            // Clear remote IRR to allow further interrupts (if level
            // triggered).
            self.redirection.set_remote_irr(false);
            self.evaluate(routing, stats, n, false);
        }
    }

    fn evaluate(
        &mut self,
        routing: &dyn IoApicRouting,
        stats: &mut IoApicStats,
        n: u8,
        edge: bool,
    ) {
        // Only some delivery modes support level trigger mode.
        let is_level = self.redirection.trigger_mode_level()
            && matches!(
                DeliveryMode(self.redirection.delivery_mode()),
                DeliveryMode::FIXED | DeliveryMode::LOWEST_PRIORITY
            );

        // Masked edge-triggered interrupts are lost. Masked level-triggered
        // interrupts are reevaluated when the interrupt is unmasked.
        if self.redirection.masked()
            || (is_level && (!self.line_level || self.redirection.remote_irr()))
            || (!is_level && !edge)
        {
            return;
        }

        // Remote IRR tracks whether a level-triggered interrupt has been EOIed yet.
        self.redirection.set_remote_irr(is_level);
        stats.interrupts.increment();
        stats.interrupts_per_irq[n as usize].increment();
        routing.assert(n);
    }
}

#[derive(Debug, InspectMut)]
pub struct IoApicDevice {
    // Static configuration
    #[inspect(skip)]
    valid_lines: [RangeInclusive<u32>; 1],

    // Runtime glue
    #[inspect(skip)]
    routing: Box<dyn IoApicRouting>,

    // Runtime book-keeping
    stats: IoApicStats,

    // Volatile state
    #[inspect(with = r#"|x| inspect::iter_by_index(x.iter())"#)]
    irqs: Box<[IrqEntry]>,
    id: u8,
    index: IndexRegister,
}

#[derive(Debug, Inspect)]
struct IoApicStats {
    #[inspect(iter_by_index)]
    interrupts_per_irq: Vec<Counter>,
    interrupts: Counter,
}

/// Trait allowing the IO-APIC device to assert VM interrupts.
pub trait IoApicRouting: Send + Sync {
    /// Asserts virtual interrupt line `irq`.
    fn assert(&self, irq: u8);
    /// Sets the MSI parameters to use when virtual interrupt line `irq` is
    /// asserted.
    fn set_route(&self, irq: u8, request: Option<(u64, u32)>);
}

impl Debug for dyn IoApicRouting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("IoApicRouting")
    }
}

impl IoApicDevice {
    pub fn new(num_entries: u8, routing: Box<dyn IoApicRouting>) -> Self {
        let irqs = (0..num_entries)
            .map(|_| IrqEntry {
                redirection: RedirectionEntry::init(),
                line_level: false,
                registered_request: None,
            })
            .collect();

        IoApicDevice {
            valid_lines: [0..=num_entries as u32 - 1],
            routing,

            id: 0,
            irqs,
            index: IndexRegister::ID,
            stats: IoApicStats {
                interrupts_per_irq: (0..num_entries).map(|_| Counter::new()).collect(),
                interrupts: Counter::new(),
            },
        }
    }

    fn read_redirection_register(&self, index: u8) -> u32 {
        let mut value = self
            .irqs
            .get(index as usize / 2)
            .map_or(0, |irq| irq.redirection.into());
        if index & 1 == 1 {
            value >>= 32;
        }
        value as u32
    }

    fn write_redirection_register(&mut self, index: u8, val: u32) {
        let n = index as usize / 2;
        if let Some(irq) = self.irqs.get_mut(n) {
            let mut val = val as u64;
            let mut redirection = u64::from(irq.redirection);
            if index & 1 == 1 {
                redirection &= 0xffffffff;
                val <<= 32;
            } else {
                redirection &= !0xffffffff;
            }
            redirection |= val & REDIRECTION_WRITE_MASK;
            irq.redirection = redirection.into();

            tracing::debug!(n, entry = ?irq.redirection, "new redirection entry");

            let request = irq.redirection.as_msi();
            if request != irq.registered_request {
                self.routing.set_route(n as u8, request);
                irq.registered_request = request;
            }

            // Reevaluate in case this unmasked a level-triggered interrupt.
            irq.evaluate(self.routing.as_ref(), &mut self.stats, n as u8, false);
        }
    }

    fn read_register(&self, index: IndexRegister) -> u32 {
        match index {
            IndexRegister::ID => IoApicId::new().with_id(self.id).into(),
            IndexRegister::VERSION => IoApicVersion::new()
                .with_version(IO_APIC_VERSION)
                .with_max_entry((self.irqs.len() - 1) as u8)
                .into(),
            IndexRegister::ARBITRATION_ID => 0,
            _ if self.index >= IndexRegister::REDIRECTION_TABLE_START => {
                self.read_redirection_register(index.0 - IndexRegister::REDIRECTION_TABLE_START.0)
            }
            _ => {
                tracelimit::warn_ratelimited!(?index, "unsupported register index read");
                !0
            }
        }
    }

    fn write_register(&mut self, index: IndexRegister, val: u32) {
        match index {
            IndexRegister::ID => self.id = IoApicId::from(val).id(),
            IndexRegister::VERSION | IndexRegister::ARBITRATION_ID => {
                tracing::debug!(?index, val, "ignoring write to read-only register");
            }
            _ if self.index >= IndexRegister::REDIRECTION_TABLE_START => {
                self.write_redirection_register(
                    index.0 - IndexRegister::REDIRECTION_TABLE_START.0,
                    val,
                );
            }
            _ => {
                tracelimit::warn_ratelimited!(?index, "unsupported register index write");
            }
        }
    }
}

impl LineInterruptTarget for IoApicDevice {
    fn set_irq(&mut self, n: u32, high: bool) {
        if let Some(irq) = self.irqs.get_mut(n as usize) {
            if high {
                irq.assert(self.routing.as_ref(), &mut self.stats, n as u8);
            } else {
                irq.deassert();
            }
        }
    }

    fn valid_lines(&self) -> &[RangeInclusive<u32>] {
        &self.valid_lines
    }
}

impl HandleEoi for IoApicDevice {
    /// reSearch query: `IoApicEmulator::NotifyEoi`
    fn handle_eoi(&mut self, irq_to_end: u32) {
        for (index, irq) in self.irqs.iter_mut().enumerate() {
            irq.eoi(
                irq_to_end,
                self.routing.as_ref(),
                &mut self.stats,
                index as u8,
            );
        }
    }
}

impl ChangeDeviceState for IoApicDevice {
    fn start(&mut self) {}

    async fn stop(&mut self) {}

    async fn reset(&mut self) {
        let Self {
            valid_lines: _,
            routing: _,
            irqs,
            id,
            index,
            stats: _,
        } = self;
        *id = 0;
        *index = IndexRegister::ID;
        for (n, irq) in irqs.iter_mut().enumerate() {
            irq.redirection = RedirectionEntry::init();
            self.routing.set_route(n as u8, None);
            irq.registered_request = None;
        }
    }
}

impl ChipsetDevice for IoApicDevice {
    fn supports_mmio(&mut self) -> Option<&mut dyn MmioIntercept> {
        Some(self)
    }

    fn supports_line_interrupt_target(&mut self) -> Option<&mut dyn LineInterruptTarget> {
        Some(self)
    }

    fn supports_handle_eoi(&mut self) -> Option<&mut dyn HandleEoi> {
        Some(self)
    }
}

mod save_restore {
    use super::spec::IndexRegister;
    use super::spec::RedirectionEntry;
    use super::IoApicDevice;
    use thiserror::Error;
    use vmcore::save_restore::RestoreError;
    use vmcore::save_restore::SaveError;
    use vmcore::save_restore::SaveRestore;

    mod state {
        use mesh::payload::Protobuf;
        use vmcore::save_restore::SavedStateRoot;

        #[derive(Clone, Debug, Default, Protobuf, SavedStateRoot)]
        #[mesh(package = "chipset.ioapic")]
        pub struct SavedState {
            #[mesh(1)]
            pub(super) id: u8,
            #[mesh(2)]
            pub(super) index: u8,
            #[mesh(3)]
            pub(super) redirection_entries: Vec<u64>,
        }
    }

    #[derive(Error, Debug)]
    #[error("wrong number of redirection entries")]
    struct WrongNumberOfRedirectionEntries;

    impl SaveRestore for IoApicDevice {
        type SavedState = state::SavedState;

        fn save(&mut self) -> Result<state::SavedState, SaveError> {
            let Self {
                valid_lines: _,
                routing: _,
                irqs,
                id,
                index,
                stats: _,
            } = &self;

            Ok(state::SavedState {
                redirection_entries: irqs.iter().map(|irq| irq.redirection.into()).collect(),
                index: index.0,
                id: *id,
            })
        }

        fn restore(&mut self, state: state::SavedState) -> Result<(), RestoreError> {
            let state::SavedState {
                redirection_entries,
                id,
                index,
            } = state;
            if redirection_entries.len() != self.irqs.len() {
                return Err(RestoreError::Other(WrongNumberOfRedirectionEntries.into()));
            }
            for (n, (state, irq)) in redirection_entries
                .into_iter()
                .zip(self.irqs.iter_mut())
                .enumerate()
            {
                irq.redirection = RedirectionEntry::from(state);
                let request = irq.redirection.as_msi();
                self.routing.set_route(n as u8, request);
                irq.registered_request = request;
            }
            self.id = id;
            self.index = IndexRegister(index);
            Ok(())
        }
    }
}

impl MmioIntercept for IoApicDevice {
    fn mmio_read(&mut self, address: u64, data: &mut [u8]) -> IoResult {
        assert_eq!(
            address & !IOAPIC_DEVICE_MMIO_REGION_MASK,
            IOAPIC_DEVICE_MMIO_REGION_BASE_ADDRESS
        );

        let v = match Register(address & IOAPIC_DEVICE_MMIO_REGION_MASK) {
            Register::INDEX => self.index.0.into(),
            Register::DATA => self.read_register(self.index),
            _ => return IoResult::Err(IoError::InvalidRegister),
        };

        // Allow any size read.
        let n = data.len().min(size_of_val(&v));
        data.copy_from_slice(&v.to_ne_bytes()[..n]);
        IoResult::Ok
    }

    fn mmio_write(&mut self, address: u64, data: &[u8]) -> IoResult {
        assert_eq!(
            address & !IOAPIC_DEVICE_MMIO_REGION_MASK,
            IOAPIC_DEVICE_MMIO_REGION_BASE_ADDRESS
        );

        match Register(address & IOAPIC_DEVICE_MMIO_REGION_MASK) {
            Register::INDEX => self.index = IndexRegister(data[0]),
            Register::DATA => {
                // Only allow 4-byte writes.
                let Ok(data) = data.try_into() else {
                    return IoResult::Err(IoError::InvalidAccessSize);
                };
                let data = u32::from_ne_bytes(data);
                self.write_register(self.index, data);
            }
            _ => return IoResult::Err(IoError::InvalidRegister),
        }

        IoResult::Ok
    }

    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u64>)] {
        &[(
            "mmio",
            IOAPIC_DEVICE_MMIO_REGION_BASE_ADDRESS
                ..=IOAPIC_DEVICE_MMIO_REGION_BASE_ADDRESS + IOAPIC_DEVICE_MMIO_REGION_SIZE - 1,
        )]
    }
}