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
use crate::shell;
use alloc::collections::{
    btree_map::{self, BTreeMap},
    btree_set::{self, BTreeSet},
};
use core::{iter, num::NonZeroU16};
pub use mycelium_pci::*;
use mycelium_util::{fmt, sync::InitOnce};

#[derive(Debug, Default)]
pub struct DeviceRegistry {
    // TODO(eliza): these BTreeMaps could be `[T; 256]`...
    by_class: BTreeMap<Class, BySubclass>,
    by_vendor: BTreeMap<u16, BTreeMap<u16, Devices>>,
    by_bus_group: BTreeMap<u16, BusGroup>,
    len: usize,
}

#[derive(Clone, Debug, Default)]
pub struct Devices(BTreeSet<Address>);

#[derive(Clone, Debug, Default)]
pub struct BySubclass(BTreeMap<Subclass, Devices>);

#[derive(Clone, Debug, Default)]
pub struct BusGroup(BTreeMap<u8, Bus>);

#[derive(Clone, Debug, Default)]
pub struct Bus([Option<BusDevice>; 32]);

type BusDevice = [Option<(Subclass, device::Id)>; 8];

pub static DEVICES: InitOnce<DeviceRegistry> = InitOnce::uninitialized();

type BusDeviceFilter = fn((usize, &Option<BusDevice>)) -> Option<(usize, &BusDevice)>;
type SubclassDeviceFilter = fn(&(&Subclass, &Devices)) -> bool;

pub const LSPCI_CMD: shell::Command = shell::Command::new("lspci")
    .with_help("list PCI devices")
    .with_usage("[ADDRESS]")
    .with_subcommands(&[shell::Command::new("class")
        .with_help(
            "list PCI devices by class. if no class code is provided, lists all devices by class.",
        )
        .with_usage("[CLASS]")
        .with_fn(|ctx| {
            fn log_device(device: Address, subclass: Subclass) {
                let Some(header) = config::ConfigReg::new(device).read_header() else {
                    tracing::error!(target: "pci", "[{device}]: invalid device header!");
                    return;
                };
                let prog_if = subclass.prog_if(header.raw_prog_if());
                match header.id() {
                    device::Id::Known(id) => tracing::info!(
                        target: "pci",
                        vendor = %id.vendor().name(),
                        device = %id.name(),
                        %prog_if,
                        "[{device}]",
                    ),
                    device::Id::Unknown(id) => tracing::warn!(
                        target: "pci",
                        vendor = fmt::hex(id.vendor_id),
                        device = fmt::hex(id.device_id),
                        %prog_if,
                        "[{device}]: unknown ID or vendor"
                    ),
                }
            }

            fn list_classes<'a>(classes: impl IntoIterator<Item = (Class, &'a BySubclass)>) {
                for (class, subclasses) in classes {
                    let _span = tracing::info_span!("class", message = %class.name()).entered();
                    for (subclass, devices) in subclasses {
                        let _span =
                            tracing::info_span!("subclass", message = %subclass.name()).entered();
                        for device in devices {
                            log_device(device, *subclass)
                        }
                    }
                }
            }

            // if no class code was provided, list all classes
            if ctx.command().is_empty() {
                tracing::info!("listing all PCI devices by class");
                list_classes(DEVICES.get().classes());
                return Ok(());
            }

            // otherwise, list devices in the provided class.
            let class = {
                let class_code = ctx
                    .command()
                    .parse::<u8>()
                    .map_err(|_| ctx.invalid_argument("a PCI class must be a valid `u8` value"))?;
                Class::from_id(class_code)
                    .map_err(|_| ctx.invalid_argument("not a valid PCI class"))?
            };
            if let Some(subclasses) = DEVICES.get().class(&class) {
                list_classes(Some((class, subclasses)));
            } else {
                tracing::info!("no {} devices found", class.name());
            }

            Ok(())
        })])
    .with_fn(|ctx| {
        if !ctx.command().is_empty() {
            let _addr = match ctx.command().parse::<Address>() {
                Ok(addr) => addr,
                Err(error) => {
                    tracing::error!(%error, "invalid PCI address");
                    return Err(ctx.invalid_argument("invalid PCI address"));
                }
            };

            return Err(ctx.other_error("looking up individual devices is not yet implemented"));
        }

        tracing::info!("listing all PCI devices by address");
        for (bus_group, group) in DEVICES.get().bus_groups() {
            let _span = tracing::info_span!("bus group", "{bus_group:04x}").entered();
            for (bus_num, bus) in group.buses() {
                let _span = tracing::info_span!("bus", "{bus_num:02x}").entered();
                for (device_num, device) in bus.devices() {
                    let _span = tracing::info_span!("device", "{device_num:02x}").entered();
                    for (fn_num, (subclass, id)) in device
                        .iter()
                        .enumerate()
                        .filter_map(|(fn_num, func)| Some((fn_num, func.as_ref()?)))
                    {
                        match id {
                            device::Id::Known(id) => tracing::info!(
                                target: " pci",
                                class = %subclass.class().name(),
                                device = %subclass.name(),
                                vendor = %id.vendor().name(),
                                device = %id.name(),
                                "[{bus_group:04x}:{bus_num:02x}:{device_num:02x}.{fn_num}]"
                            ),
                            device::Id::Unknown(id) => tracing::warn!(
                                target: " pci",
                                class = %subclass.class().name(),
                                device = %subclass.name(),
                                vendor = fmt::hex(id.vendor_id),
                                device = fmt::hex(id.device_id),
                                "[{bus_group:04x}:{bus_num:02x}:{device_num:02x}.{fn_num}]",
                            ),
                        }
                    }
                }
            }
        }

        Ok(())
    });

impl DeviceRegistry {
    pub fn insert(&mut self, addr: Address, class: Classes, id: device::Id) -> bool {
        // class->subclass->addr registry
        let mut new = self
            .by_class
            .entry(class.class())
            .or_default()
            .0
            .entry(class.subclass())
            .or_default()
            .0
            .insert(addr);
        // vendor->device->addr registry
        new &= self
            .by_vendor
            .entry(id.vendor_id())
            .or_default()
            .entry(id.device_id())
            .or_default()
            .0
            .insert(addr);
        // address (bus group->bus->device->function) registry
        let Bus(bus) = self
            .by_bus_group
            .entry(addr.group().map(Into::into).unwrap_or(0))
            .or_default()
            .0
            .entry(addr.bus())
            .or_default();
        let bus_device = bus
            .get_mut(addr.device() as usize)
            .expect("invalid address: the device must be 5 bits")
            .get_or_insert_with(|| [None; 8]);
        new &= bus_device
            .get_mut(addr.function() as usize)
            .expect("invalid address: the function must be 3 bits")
            .replace((class.subclass(), id))
            .is_none();
        new
    }

    pub fn class(&self, class: &Class) -> Option<&BySubclass> {
        self.by_class.get(class)
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        let is_empty = self.len() == 0;
        debug_assert_eq!(is_empty, self.by_class.is_empty());
        debug_assert_eq!(is_empty, self.by_vendor.is_empty());
        is_empty
    }

    pub fn classes(&self) -> impl Iterator<Item = (Class, &BySubclass)> + '_ {
        self.by_class.iter().filter_map(|(class, by_subclass)| {
            if !by_subclass.0.is_empty() {
                Some((*class, by_subclass))
            } else {
                None
            }
        })
    }

    pub fn bus_groups(&self) -> btree_map::Iter<'_, u16, BusGroup> {
        self.by_bus_group.iter()
    }

    pub fn iter(&self) -> impl Iterator<Item = (Address, Subclass, device::Id)> + '_ {
        self.bus_groups().flat_map(|(&group_addr, group)| {
            group.buses().flat_map(move |(&bus_addr, bus)| {
                bus.devices().flat_map(move |(device_addr, device)| {
                    device
                        .iter()
                        .enumerate()
                        .filter_map(move |(func_num, func)| {
                            let (subclass, id) = func.as_ref()?;
                            let addr = Address::new()
                                .with_group(NonZeroU16::new(group_addr))
                                .with_bus(bus_addr)
                                .with_device(device_addr as u8)
                                .with_function(func_num as u8);
                            Some((addr, *subclass, *id))
                        })
                })
            })
        })
    }
}

// === impl BySubclass ===

impl BySubclass {
    pub fn subclass(&self, subclass: class::Subclass) -> Option<&Devices> {
        self.0.get(&subclass)
    }

    pub fn iter(
        &self,
    ) -> iter::Filter<btree_map::Iter<'_, Subclass, Devices>, SubclassDeviceFilter> {
        self.0.iter().filter(|&(_, devices)| !devices.is_empty())
    }
}

impl<'a> IntoIterator for &'a BySubclass {
    type Item = (&'a Subclass, &'a Devices);
    type IntoIter = iter::Filter<btree_map::Iter<'a, Subclass, Devices>, SubclassDeviceFilter>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

// === impl Devices ===

impl Devices {
    pub fn iter(&self) -> iter::Copied<btree_set::Iter<'_, Address>> {
        self.0.iter().copied()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl<'a> IntoIterator for &'a Devices {
    type Item = Address;
    type IntoIter = iter::Copied<btree_set::Iter<'a, Address>>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

// === impl BusGroup ===

impl BusGroup {
    pub fn buses(&self) -> btree_map::Iter<'_, u8, Bus> {
        self.0.iter()
    }
}

// === impl Bus ===

impl Bus {
    pub fn devices(
        &self,
    ) -> iter::FilterMap<iter::Enumerate<core::slice::Iter<'_, Option<BusDevice>>>, BusDeviceFilter>
    {
        self.0
            .iter()
            .enumerate()
            .filter_map((|(addr, device)| Some((addr, device.as_ref()?))) as BusDeviceFilter)
    }
}