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

use core::mem::size_of;
use core::ptr;
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::util::Once;
use crate::MAX_CPUS;

pub const INVALID_ID: u8 = 0xff;

/// Mapping core id to initial lapic id, used for lapic initialization...
pub static LAPIC_IDS: Once<[u8; MAX_CPUS]> = Once::new();

/// 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::<ApicTable>();
    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 mut lapic_ids = [INVALID_ID; MAX_CPUS];
    let mut ioapic = None;

    // Load the interrupt controller config from the system tables
    for entry in madt.iter() {
        match entry {
            Entry::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:?}");
                }
            }
            Entry::IOApic(entry) => {
                if entry.global_int_base < IoApic::SLOT_MAX as _ && ioapic.is_none() {
                    ioapic = Some(entry);
                } else {
                    serial!("ignore {entry:?}");
                }
            }
            Entry::IntSource(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);
                }
            }
            Entry::LApicAddr(entry) => {
                LAPIC.base.store(entry.lapic_addr as _, Release);
            }
            Entry::Unknown(entry) => serial!("ignore {entry:?}"),
        }
    }

    serial!("lapics: {lapic_ids:?}");
    LAPIC_IDS.set(lapic_ids).unwrap();

    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)]
struct ApicTable {
    header: SysDescTable,
    lapic_address: u32,
    flags: ApicFlags,
}

impl AcpiTable for ApicTable {}

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

impl ApicTable {
    fn iter(&self) -> AcpiTableIter {
        let start = ptr::from_ref(self).cast::<u8>();
        AcpiTableIter {
            start: unsafe { start.add(size_of::<Self>()) },
            end: unsafe { start.add(self.header.length as usize) },
        }
    }
}

/// Iterates through the MADS table.
struct AcpiTableIter {
    start: *const u8,
    end: *const u8,
}

impl Iterator for AcpiTableIter {
    type Item = Entry;

    fn next(&mut self) -> Option<Self::Item> {
        if self.start < self.end {
            unsafe {
                let entry = &*self.start.cast::<Header>();
                let start = self.start.add(2);
                self.start = self.start.add(entry.len as usize);

                Some(match entry.ty {
                    0 => Entry::LApic(*start.cast()),
                    1 => Entry::IOApic(*start.cast()),
                    2 => Entry::IntSource(*start.cast()),
                    5 => Entry::LApicAddr(*start.cast()),
                    ty => Entry::Unknown(ty),
                })
            }
        } else {
            None
        }
    }
}

/// All entries share the same header
#[repr(C, packed)]
struct Header {
    ty: u8,
    len: u8,
}

/// Entries of the Multiple APIC Definition Structure (MADS) table.
#[derive(Debug)]
enum Entry {
    LApic(LApicEntry),
    IOApic(IOApicEntry),
    IntSource(IntSourceEntry),
    LApicAddr(LApicAddrEntry),
    Unknown(u8),
}

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

#[bitfield(u32)]
pub struct LApicFlags {
    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 IntSourceEntry {
    pub bus: u8,
    pub source: u8,
    pub global_int: u32,
    pub flags: u16,
}

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