1#[cfg(target_arch = "x86_64")]
24use crate::arch::pci as arch_pci;
25pub use crate::arch::pci::{
26 cap_id, class, command, config, device, intel_eth, msi_cap, msi_ctrl, msix_cap, msix_ctrl,
27 net_subclass, sata_progif, storage_subclass, vendor, MSI_ADDR_BASE, MSI_ADDR_DEST_SHIFT,
28};
29use crate::vfs::{self, OpenFlags};
30use alloc::{format, string::String, vec::Vec};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Bar {
34 Io { port: u16 },
35 Memory32 { addr: u32, prefetchable: bool },
36 Memory64 { addr: u64, prefetchable: bool },
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct PciAddress {
41 pub bus: u8,
42 pub device: u8,
43 pub function: u8,
44}
45
46impl PciAddress {
47 pub const fn new(bus: u8, device: u8, function: u8) -> Self {
49 Self {
50 bus,
51 device,
52 function,
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy)]
58pub struct PciDevice {
59 pub address: PciAddress,
60 pub vendor_id: u16,
61 pub device_id: u16,
62 pub class_code: u8,
63 pub subclass: u8,
64 pub prog_if: u8,
65 pub revision: u8,
66 pub header_type: u8,
67 pub interrupt_line: u8,
68 pub interrupt_pin: u8,
69}
70
71#[derive(Debug, Clone, Copy, Default)]
72pub struct ProbeCriteria {
73 pub vendor_id: Option<u16>,
74 pub device_id: Option<u16>,
75 pub class_code: Option<u8>,
76 pub subclass: Option<u8>,
77 pub prog_if: Option<u8>,
78}
79
80impl ProbeCriteria {
81 pub const fn any() -> Self {
83 Self {
84 vendor_id: None,
85 device_id: None,
86 class_code: None,
87 subclass: None,
88 prog_if: None,
89 }
90 }
91
92 fn matches(&self, dev: &PciDevice) -> bool {
94 if self.vendor_id.is_some_and(|v| dev.vendor_id != v) {
95 return false;
96 }
97 if self.device_id.is_some_and(|d| dev.device_id != d) {
98 return false;
99 }
100 if self.class_code.is_some_and(|c| dev.class_code != c) {
101 return false;
102 }
103 if self.subclass.is_some_and(|s| dev.subclass != s) {
104 return false;
105 }
106 if self.prog_if.is_some_and(|p| dev.prog_if != p) {
107 return false;
108 }
109 true
110 }
111}
112
113fn open_read_all(path: &str) -> Option<Vec<u8>> {
115 let fd = vfs::open(path, OpenFlags::READ).ok()?;
116 let mut out = Vec::new();
117 let mut chunk = [0u8; 256];
118 loop {
119 let n = match vfs::read(fd, &mut chunk) {
120 Ok(n) => n,
121 Err(_) => {
122 let _ = vfs::close(fd);
123 return None;
124 }
125 };
126 if n == 0 {
127 break;
128 }
129 out.extend_from_slice(&chunk[..n]);
130 }
131 let _ = vfs::close(fd);
132 Some(out)
133}
134
135fn open_write(path: &str, bytes: &[u8]) -> bool {
137 let fd = match vfs::open(path, OpenFlags::WRITE) {
138 Ok(fd) => fd,
139 Err(_) => return false,
140 };
141 let ok = vfs::write(fd, bytes).is_ok();
142 let _ = vfs::close(fd);
143 ok
144}
145
146fn parse_hex_u8(s: &str) -> Option<u8> {
148 u8::from_str_radix(s.trim_start_matches("0x"), 16).ok()
149}
150
151fn parse_hex_u16(s: &str) -> Option<u16> {
153 u16::from_str_radix(s.trim_start_matches("0x"), 16).ok()
154}
155
156fn parse_inventory_line(line: &str) -> Option<PciDevice> {
158 let mut parts = line.split_whitespace();
159 let bdf = parts.next()?;
160 let ids = parts.next()?;
161 let class_sub = parts.next()?;
162 let prog_if = parts.next()?;
163 let rev = parts.next()?;
164 let irq = parts.next()?;
165
166 let (bus_s, rest) = bdf.split_once(':')?;
167 let (dev_s, fun_s) = rest.split_once('.')?;
168 let bus = parse_hex_u8(bus_s)?;
169 let device = parse_hex_u8(dev_s)?;
170 let function = fun_s.parse::<u8>().ok()?;
171
172 let (ven_s, did_s) = ids.split_once(':')?;
173 let vendor_id = parse_hex_u16(ven_s)?;
174 let device_id = parse_hex_u16(did_s)?;
175
176 let (class_s, sub_s) = class_sub.split_once(':')?;
177 let class_code = parse_hex_u8(class_s)?;
178 let subclass = parse_hex_u8(sub_s)?;
179
180 let prog_if = parse_hex_u8(prog_if)?;
181 let revision = parse_hex_u8(rev)?;
182 let interrupt_line = irq.parse::<u8>().unwrap_or(0);
183
184 Some(PciDevice {
185 address: PciAddress::new(bus, device, function),
186 vendor_id,
187 device_id,
188 class_code,
189 subclass,
190 prog_if,
191 revision,
192 header_type: 0,
193 interrupt_line,
194 interrupt_pin: 0,
195 })
196}
197
198fn all_devices_from_bus_service() -> Vec<PciDevice> {
200 let bytes = match open_read_all("/bus/pci/inventory") {
201 Some(b) => b,
202 None => return Vec::new(),
203 };
204 let text = match core::str::from_utf8(&bytes) {
205 Ok(s) => s,
206 Err(_) => return Vec::new(),
207 };
208 let mut out = Vec::new();
209 for (idx, line) in text.lines().enumerate() {
210 if idx == 0 || line.trim().is_empty() {
211 continue;
212 }
213 if let Some(dev) = parse_inventory_line(line) {
214 out.push(dev);
215 }
216 }
217 out
218}
219
220fn cfg_path(addr: PciAddress, offset: u8, width: u8) -> String {
222 format!(
223 "/bus/pci/cfg/{:02x}:{:02x}.{:x}/{:02x}/{}",
224 addr.bus, addr.device, addr.function, offset, width
225 )
226}
227
228#[cfg(target_arch = "x86_64")]
230fn to_arch_addr(addr: PciAddress) -> arch_pci::PciAddress {
231 arch_pci::PciAddress::new(addr.bus, addr.device, addr.function)
232}
233
234#[cfg(target_arch = "x86_64")]
236fn arch_dev_handle(addr: PciAddress) -> arch_pci::PciDevice {
237 arch_pci::PciDevice {
238 address: to_arch_addr(addr),
239 vendor_id: 0,
240 device_id: 0,
241 class_code: 0,
242 subclass: 0,
243 prog_if: 0,
244 revision: 0,
245 header_type: 0,
246 interrupt_line: 0,
247 interrupt_pin: 0,
248 }
249}
250
251fn cfg_read(addr: PciAddress, offset: u8, width: u8) -> Option<u32> {
253 if let Some(bytes) = open_read_all(&cfg_path(addr, offset, width)) {
254 let text = core::str::from_utf8(&bytes).ok()?.trim();
255 let hex = text.strip_prefix("0x")?;
256 return u32::from_str_radix(hex, 16).ok();
257 }
258
259 #[cfg(target_arch = "x86_64")]
261 {
262 let dev = arch_dev_handle(addr);
263 Some(match width {
264 1 => dev.read_config_u8(offset) as u32,
265 2 => dev.read_config_u16(offset) as u32,
266 4 => dev.read_config_u32(offset),
267 _ => return None,
268 })
269 }
270 #[cfg(target_arch = "riscv64")]
271 {
272 use crate::arch::riscv64::pci;
273 Some(match width {
274 1 => pci::read_config_u8(addr.bus, addr.device, addr.function, offset) as u32,
275 2 => pci::read_config_u16(addr.bus, addr.device, addr.function, offset) as u32,
276 4 => pci::read_config_u32(addr.bus, addr.device, addr.function, offset),
277 _ => return None,
278 })
279 }
280}
281
282fn cfg_write(addr: PciAddress, offset: u8, width: u8, value: u32) -> bool {
284 if open_write(&cfg_path(addr, offset, width), &value.to_le_bytes()) {
285 return true;
286 }
287
288 #[cfg(target_arch = "x86_64")]
290 {
291 let dev = arch_dev_handle(addr);
292 match width {
293 1 => dev.write_config_u8(offset, value as u8),
294 2 => dev.write_config_u16(offset, value as u16),
295 4 => dev.write_config_u32(offset, value),
296 _ => return false,
297 }
298 true
299 }
300 #[cfg(target_arch = "riscv64")]
301 {
302 use crate::arch::riscv64::pci;
303 let aligned = offset & !3;
304 let shift = (offset & 3) * 8;
305 match width {
306 1 | 2 => {
307 let bits = (width as u32) * 8;
308 if shift as u32 + bits > 32 {
309 return false;
310 }
311 let mask = ((1u32 << bits) - 1) << shift;
312 let old = pci::read_config_u32(addr.bus, addr.device, addr.function, aligned);
313 pci::write_config_u32(
314 addr.bus,
315 addr.device,
316 addr.function,
317 aligned,
318 (old & !mask) | ((value << shift) & mask),
319 );
320 }
321 4 => pci::write_config_u32(addr.bus, addr.device, addr.function, aligned, value),
322 _ => return false,
323 }
324 true
325 }
326}
327
328impl PciDevice {
329 pub fn read_config_u8(&self, offset: u8) -> u8 {
331 cfg_read(self.address, offset, 1).map_or(0, |v| v as u8)
332 }
333
334 pub fn read_config_u16(&self, offset: u8) -> u16 {
336 cfg_read(self.address, offset, 2).map_or(0, |v| v as u16)
337 }
338
339 pub fn read_config_u32(&self, offset: u8) -> u32 {
341 cfg_read(self.address, offset, 4).unwrap_or(0)
342 }
343
344 pub fn write_config_u8(&self, offset: u8, value: u8) {
346 let _ = cfg_write(self.address, offset, 1, value as u32);
347 }
348
349 pub fn write_config_u16(&self, offset: u8, value: u16) {
351 let _ = cfg_write(self.address, offset, 2, value as u32);
352 }
353
354 pub fn write_config_u32(&self, offset: u8, value: u32) {
356 let _ = cfg_write(self.address, offset, 4, value);
357 }
358
359 pub fn read_config_u32_ext(&self, offset: u16) -> Option<u32> {
361 if let Some(bytes) = open_read_all(&format!(
362 "/bus/pci/cfg/{:02x}:{:02x}.{:x}/{:02x}/{}",
363 self.address.bus, self.address.device, self.address.function, offset, 4
364 )) {
365 let text = core::str::from_utf8(&bytes).ok()?.trim();
366 let hex = text.strip_prefix("0x")?;
367 return u32::from_str_radix(hex, 16).ok();
368 }
369 #[cfg(target_arch = "x86_64")]
370 {
371 arch_dev_handle(self.address).read_config_u32_ext(offset)
372 }
373 #[cfg(target_arch = "riscv64")]
374 {
375 let offset = u8::try_from(offset).ok()?;
376 Some(crate::arch::riscv64::pci::read_config_u32(
377 self.address.bus,
378 self.address.device,
379 self.address.function,
380 offset,
381 ))
382 }
383 }
384
385 pub fn find_capability(&self, id: u8) -> Option<u8> {
391 let status = self.read_config_u16(config::STATUS);
392 if status & (1 << 4) == 0 {
393 return None; }
395 let mut ptr = self.read_config_u8(config::CAPABILITIES_PTR);
396 ptr &= 0xFC; while ptr != 0 {
398 if self.read_config_u8(ptr) == id {
399 return Some(ptr);
400 }
401 ptr = self.read_config_u8(ptr + 1) & 0xFC;
402 }
403 None
404 }
405
406 pub fn msi_cap_offset(&self) -> Option<u8> {
408 self.find_capability(cap_id::MSI)
409 }
410
411 pub fn msix_cap_offset(&self) -> Option<u8> {
413 self.find_capability(cap_id::MSIX)
414 }
415
416 pub fn read_bar(&self, bar_index: u8) -> Option<Bar> {
418 if bar_index > 5 {
419 return None;
420 }
421 let offset = config::BAR0 + bar_index * 4;
422 let low = self.read_config_u32(offset);
423 if low == 0 {
424 return None;
425 }
426 if (low & 1) != 0 {
427 return Some(Bar::Io {
428 port: (low & 0xFFFF_FFFC) as u16,
429 });
430 }
431 let bar_type = (low >> 1) & 0x3;
432 let prefetchable = ((low >> 3) & 1) != 0;
433 match bar_type {
434 0 => Some(Bar::Memory32 {
435 addr: low & 0xFFFF_FFF0,
436 prefetchable,
437 }),
438 2 => {
439 if bar_index >= 5 {
440 return None;
441 }
442 let high = self.read_config_u32(offset + 4);
443 Some(Bar::Memory64 {
444 addr: ((high as u64) << 32) | ((low & 0xFFFF_FFF0) as u64),
445 prefetchable,
446 })
447 }
448 _ => None,
449 }
450 }
451
452 pub fn read_bar_raw(&self, bar_index: u8) -> Option<u64> {
454 match self.read_bar(bar_index) {
455 Some(Bar::Io { port }) => Some(port as u64),
456 Some(Bar::Memory32 { addr, .. }) => Some(addr as u64),
457 Some(Bar::Memory64 { addr, .. }) => Some(addr),
458 None => None,
459 }
460 }
461
462 pub fn enable_bus_master(&self) {
464 let mut cmd = self.read_config_u16(config::COMMAND);
465 cmd |= command::BUS_MASTER;
466 self.write_config_u16(config::COMMAND, cmd);
467 }
468
469 pub fn enable_memory_space(&self) {
471 let mut cmd = self.read_config_u16(config::COMMAND);
472 cmd |= command::MEMORY_SPACE;
473 self.write_config_u16(config::COMMAND, cmd);
474 }
475
476 pub fn enable_io_space(&self) {
478 let mut cmd = self.read_config_u16(config::COMMAND);
479 cmd |= command::IO_SPACE;
480 self.write_config_u16(config::COMMAND, cmd);
481 }
482}
483
484pub fn all_devices() -> Vec<PciDevice> {
486 let from_bus = all_devices_from_bus_service();
487 if !from_bus.is_empty() {
488 return from_bus;
489 }
490
491 #[cfg(target_arch = "x86_64")]
493 {
494 arch_pci::all_devices()
495 .into_iter()
496 .map(|d| PciDevice {
497 address: PciAddress::new(d.address.bus, d.address.device, d.address.function),
498 vendor_id: d.vendor_id,
499 device_id: d.device_id,
500 class_code: d.class_code,
501 subclass: d.subclass,
502 prog_if: d.prog_if,
503 revision: d.revision,
504 header_type: d.header_type,
505 interrupt_line: d.interrupt_line,
506 interrupt_pin: d.interrupt_pin,
507 })
508 .collect()
509 }
510 #[cfg(target_arch = "riscv64")]
511 {
512 let mut raw = [crate::arch::riscv64::pci::PciDeviceInfo::EMPTY; 256];
513 let count = crate::arch::riscv64::pci::enumerate(&mut raw);
514 raw[..count]
515 .iter()
516 .map(|d| PciDevice {
517 address: PciAddress::new(d.bus, d.device, d.function),
518 vendor_id: d.vendor_id,
519 device_id: d.device_id,
520 class_code: d.class_code,
521 subclass: d.subclass,
522 prog_if: d.prog_if,
523 revision: d.revision,
524 header_type: d.header_type,
525 interrupt_line: d.interrupt_line,
526 interrupt_pin: d.interrupt_pin,
527 })
528 .collect::<Vec<_>>()
529 }
530}
531
532pub fn find_device(vendor_id: u16, device_id: u16) -> Option<PciDevice> {
534 all_devices()
535 .into_iter()
536 .find(|d| d.vendor_id == vendor_id && d.device_id == device_id)
537}
538
539pub fn find_virtio_device(device_id: u16) -> Option<PciDevice> {
541 find_device(vendor::VIRTIO, device_id)
542}
543
544pub fn find_virtio_devices() -> Vec<PciDevice> {
546 find_devices_by_vendor(vendor::VIRTIO)
547}
548
549pub fn find_devices_by_vendor(vendor_id: u16) -> Vec<PciDevice> {
551 all_devices()
552 .into_iter()
553 .filter(|d| d.vendor_id == vendor_id)
554 .collect()
555}
556
557pub fn find_devices_by_class(class_code: u8, subclass: u8) -> Vec<PciDevice> {
559 all_devices()
560 .into_iter()
561 .filter(|d| d.class_code == class_code && d.subclass == subclass)
562 .collect()
563}
564
565pub fn probe_all(criteria: ProbeCriteria) -> Vec<PciDevice> {
567 all_devices()
568 .into_iter()
569 .filter(|d| criteria.matches(d))
570 .collect()
571}
572
573pub fn probe_first(criteria: ProbeCriteria) -> Option<PciDevice> {
575 all_devices().into_iter().find(|d| criteria.matches(d))
576}
577
578pub fn invalidate_cache() {
580 let _ = open_write("/bus/pci/rescan", &[1, 0, 0, 0]);
581 #[cfg(target_arch = "x86_64")]
582 arch_pci::invalidate_cache();
583}