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
//! Configuring the APIC system.

use core::mem::size_of;
use core::sync::atomic::Ordering::Release;

use bitfield_struct::bitfield;

use super::ioapic::{IoApic, IOAPIC};
use super::lapic::LAPIC;
use super::pic;
use crate::arch::acpi::{Acpi, AcpiTable, SysDescTable};
use crate::MAX_CPUS;

pub const INVALID_ID: u8 = 0xff;

/// Mapping core id to initial lapic id, used for lapic initialization...
pub static mut LAPIC_IDS: [u8; MAX_CPUS] = [INVALID_ID; MAX_CPUS];

/// Retrieves the APIC related configurations from the system tables.
pub fn parse_apic_table(acpi: Acpi) -> (u8, usize) {
    let madt = acpi.find(*b"APIC").unwrap().cast::<MulAcpiTable>();
    let flags = madt.flags;
    LAPIC.base.store(madt.lapic_address as _, Release);

    // The APIC operating mode is set to compatible PIC mode - we have to change it.
    if flags.pcat_compat() {
        serial!("disable pic");
        pic::disable();
    }

    let mut lapics = 0;
    let lapic_ids = unsafe { &mut LAPIC_IDS };
    let mut ioapic = None;

    // Load the interrupt controller config from the system tables
    for entry in madt.iter() {
        match entry {
            ApicEntry::LApic(entry) => {
                let flags = entry.flags;
                if flags.enabled() && entry.apic_id != INVALID_ID && lapics < lapic_ids.len() {
                    lapic_ids[lapics] = entry.apic_id;
                    lapics += 1;
                } else {
                    serial!("ignore {entry:?}");
                }
            }
            ApicEntry::IOApic(entry) => {
                if entry.global_int_base < IoApic::SLOT_MAX as _ && ioapic.is_none() {
                    ioapic = Some(entry)
                } else {
                    serial!("ignore {entry:?}");
                }
            }
            ApicEntry::IntSrcOverride(entry) => {
                // We support only one IOAPIC for now!
                if entry.bus == 0 {
                    let global_int = entry.global_int;
                    let source = entry.source as usize;
                    serial!("Override interrupt {source} <- {global_int}");
                    IOAPIC.set_override(source, global_int as _);
                } else {
                    serial!("invalid apic bus {}", entry.bus);
                }
            }
            ApicEntry::LApicAddrOverride(entry) => {
                LAPIC.base.store(entry.lapic_addr as _, Release);
            }
            _ => {
                serial!("ignore {entry:?}")
            }
        }
    }

    serial!("lapics: {lapic_ids:?}");

    let ioapic = ioapic.expect("Not IOAPIC found!");
    let ioapic_addr = ioapic.ioapic_addr as *mut u32;
    serial!("init ioapic {} @ {ioapic_addr:?}", ioapic.ioapic_id);
    IOAPIC.base.store(ioapic_addr, Release);

    (ioapic.ioapic_id, lapics)
}

/// Multiple APIC Definition Structure (MADS) table.
///
/// The MADS describes the different I/O and Local APICs and the interrupt redirections.
#[derive(Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct MulAcpiTable {
    pub header: SysDescTable,
    pub lapic_address: u32,
    pub flags: MulAcpiTableF,
}

impl AcpiTable for MulAcpiTable {}

#[bitfield(u32)]
pub struct MulAcpiTableF {
    /// Do we have to configure and disable the legacy PIC?
    pub pcat_compat: bool,
    #[bits(31)]
    _p: u32,
}

impl MulAcpiTable {
    pub fn iter(&self) -> MulAcpiTableIter {
        let start = self as *const _ as usize;
        MulAcpiTableIter {
            start: start + size_of::<Self>(),
            end: start + self.header.length as usize,
        }
    }
}

/// Iterates through the MADS table.
pub struct MulAcpiTableIter {
    start: usize,
    end: usize,
}

impl Iterator for MulAcpiTableIter {
    type Item = ApicEntry;

    fn next(&mut self) -> Option<Self::Item> {
        if self.start < self.end {
            /// All entries share the same header
            #[repr(C, packed)]
            struct Header {
                ty: u8,
                len: u8,
            }
            let entry = unsafe { &*(self.start as *const Header) };

            let start = (self.start + 2) as *const ();
            self.start += entry.len as usize;

            Some(match entry.ty {
                0 => ApicEntry::LApic(unsafe { *start.cast() }),
                1 => ApicEntry::IOApic(unsafe { *start.cast() }),
                2 => ApicEntry::IntSrcOverride(unsafe { *start.cast() }),
                5 => ApicEntry::LApicAddrOverride(unsafe { *start.cast() }),
                ty => ApicEntry::Unknown(ty),
            })
        } else {
            None
        }
    }
}

/// Entries of the Multiple APIC Definition Structure (MADS) table.
#[derive(Debug)]
pub enum ApicEntry {
    LApic(LApicEntry),
    IOApic(IOApicEntry),
    IntSrcOverride(IntSrcOverrideEntry),
    LApicAddrOverride(LApicAddrOverrideEntry),
    Unknown(u8),
}

#[derive(Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct LApicEntry {
    pub apic_cid: u8,
    pub apic_id: u8,
    pub flags: ApicEntryLApicF,
}

#[bitfield(u32)]
pub struct ApicEntryLApicF {
    pub enabled: bool,
    #[bits(31)]
    __: u32,
}

#[derive(Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct IOApicEntry {
    pub ioapic_id: u8,
    pub _reserved: u8,
    pub ioapic_addr: u32,
    pub global_int_base: u32,
}

#[derive(Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct IntSrcOverrideEntry {
    pub bus: u8,
    pub source: u8,
    pub global_int: u32,
    pub flags: u16,
}

#[derive(Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct LApicAddrOverrideEntry {
    pub _reserved: u16,
    pub lapic_addr: u64,
}