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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use crate::arch::x86_64::kernel::pci_ids::{CLASSES, VENDORS};
use crate::arch::x86_64::mm::{PhysAddr, VirtAddr};
use crate::collections::irqsave;
use crate::drivers::net::rtl8139::{self, RTL8139Driver};
use crate::drivers::net::virtio_net::VirtioNetDriver;
use crate::drivers::net::NetworkInterface;
use crate::drivers::virtio::depr::virtio_fs::VirtioFsDriver;
use crate::drivers::virtio::transport::pci as pci_virtio;
use crate::drivers::virtio::transport::pci::VirtioDriver;
use crate::synch::spinlock::SpinlockIrqSave;
use crate::x86::io::*;
use alloc::vec::Vec;
use core::convert::TryInto;
use core::{fmt, u32, u8};
pub const PCI_MAX_BUS_NUMBER: u8 = 32;
pub const PCI_MAX_DEVICE_NUMBER: u8 = 32;
pub const PCI_CONFIG_ADDRESS_PORT: u16 = 0xCF8;
pub const PCI_CONFIG_ADDRESS_ENABLE: u32 = 1 << 31;
pub const PCI_CONFIG_DATA_PORT: u16 = 0xCFC;
pub const PCI_COMMAND_BUSMASTER: u32 = 1 << 2;
pub const PCI_ID_REGISTER: u32 = 0x00;
pub const PCI_COMMAND_REGISTER: u32 = 0x04;
pub const PCI_CLASS_REGISTER: u32 = 0x08;
pub const PCI_HEADER_REGISTER: u32 = 0x0C;
pub const PCI_BAR0_REGISTER: u32 = 0x10;
pub const PCI_CAPABILITY_LIST_REGISTER: u32 = 0x34;
pub const PCI_INTERRUPT_REGISTER: u32 = 0x3C;
pub const PCI_STATUS_CAPABILITIES_LIST: u32 = 1 << 4;
pub const PCI_BASE_ADDRESS_IO_SPACE: u32 = 1 << 0;
pub const PCI_MEM_BASE_ADDRESS_64BIT: u32 = 1 << 2;
pub const PCI_MEM_PREFETCHABLE: u32 = 1 << 3;
pub const PCI_MEM_BASE_ADDRESS_MASK: u32 = 0xFFFF_FFF0;
pub const PCI_IO_BASE_ADDRESS_MASK: u32 = 0xFFFF_FFFC;
pub const PCI_HEADER_TYPE_MASK: u32 = 0x007F_0000;
pub const PCI_MULTIFUNCTION_MASK: u32 = 0x0080_0000;
pub const PCI_CAP_ID_VNDR: u32 = 0x09;
static mut PCI_ADAPTERS: Vec<PciAdapter> = Vec::new();
static mut PCI_DRIVERS: Vec<PciDriver> = Vec::new();
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, FromPrimitive, ToPrimitive, PartialEq)]
pub enum PciClassCode {
TooOld = 0x00,
MassStorage = 0x01,
NetworkController = 0x02,
DisplayController = 0x03,
MultimediaController = 0x04,
MemoryController = 0x05,
BridgeDevice = 0x06,
SimpleCommunicationController = 0x07,
BaseSystemPeripheral = 0x08,
InputDevice = 0x09,
DockingStation = 0x0A,
Processor = 0x0B,
SerialBusController = 0x0C,
WirelessController = 0x0D,
IntelligentIoController = 0x0E,
EncryptionController = 0x0F,
DataAcquisitionSignalProcessing = 0x11,
Other = 0xFF,
}
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, FromPrimitive, ToPrimitive, PartialEq)]
pub enum PciNetworkControllerSubclass {
EthernetController = 0x00,
TokenRingController = 0x01,
FDDIController = 0x02,
ATMController = 0x03,
ISDNController = 0x04,
WorldFipController = 0x05,
PICMGController = 0x06,
InfinibandController = 0x07,
FabricController = 0x08,
NetworkController = 0x80,
}
#[derive(Clone, Debug)]
pub struct PciAdapter {
pub bus: u8,
pub device: u8,
pub vendor_id: u16,
pub device_id: u16,
pub class_id: u8,
pub subclass_id: u8,
pub programming_interface_id: u8,
pub base_addresses: Vec<PciBar>,
pub irq: u8,
}
#[derive(Clone, Copy, Debug)]
pub enum PciBar {
IO(IOBar),
Memory(MemoryBar),
}
#[derive(Clone, Copy, Debug)]
pub struct IOBar {
pub index: u8,
pub addr: u32,
pub size: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct MemoryBar {
pub index: u8,
pub addr: usize,
pub size: usize,
pub width: u8,
pub prefetchable: bool,
}
pub enum PciDriver<'a> {
VirtioFs(SpinlockIrqSave<VirtioFsDriver<'a>>),
VirtioNet(SpinlockIrqSave<VirtioNetDriver>),
RTL8139Net(SpinlockIrqSave<RTL8139Driver>),
}
impl<'a> PciDriver<'a> {
fn get_network_driver(&self) -> Option<&SpinlockIrqSave<dyn NetworkInterface>> {
match self {
Self::VirtioNet(drv) => Some(drv),
Self::RTL8139Net(drv) => Some(drv),
_ => None,
}
}
fn get_filesystem_driver(&self) -> Option<&SpinlockIrqSave<VirtioFsDriver<'a>>> {
match self {
Self::VirtioFs(drv) => Some(drv),
_ => None,
}
}
}
pub fn register_driver(drv: PciDriver<'static>) {
unsafe {
PCI_DRIVERS.push(drv);
}
}
pub fn get_network_driver() -> Option<&'static SpinlockIrqSave<dyn NetworkInterface>> {
unsafe { PCI_DRIVERS.iter().find_map(|drv| drv.get_network_driver()) }
}
pub fn get_filesystem_driver() -> Option<&'static SpinlockIrqSave<VirtioFsDriver<'static>>> {
unsafe {
PCI_DRIVERS
.iter()
.find_map(|drv| drv.get_filesystem_driver())
}
}
fn parse_bars(bus: u8, device: u8, vendor_id: u16, device_id: u16) -> Vec<PciBar> {
let mut bar_idxs = 0..6;
let mut bars = Vec::new();
while let Some(i) = bar_idxs.next() {
let register = PCI_BAR0_REGISTER + ((i as u32) << 2);
let barword = read_config(bus, device, register);
debug!(
"Found bar{} @{:x}:{:x} as 0x{:x}",
i, vendor_id, device_id, barword
);
if barword == 0 {
continue;
}
if barword & PCI_BASE_ADDRESS_IO_SPACE != 0 {
debug!("Bar {} @{:x}:{:x} IO mapped!", i, vendor_id, device_id);
let base_addr = barword & PCI_IO_BASE_ADDRESS_MASK;
write_config(bus, device, register, u32::MAX);
let sizebits = read_config(bus, device, register);
write_config(bus, device, register, barword);
let size = (!(sizebits & PCI_IO_BASE_ADDRESS_MASK) + 1) as usize;
bars.push(PciBar::IO(IOBar {
index: i as u8,
addr: base_addr,
size,
}));
} else {
let prefetchable = barword & PCI_MEM_PREFETCHABLE != 0;
if barword & PCI_MEM_BASE_ADDRESS_64BIT != 0 {
let register_high = PCI_BAR0_REGISTER + (bar_idxs.next().unwrap() << 2);
let barword_high = read_config(bus, device, register_high);
let base_addr = ((barword_high as usize) << 32) + (barword & 0xFFFF_FFF0) as usize;
debug!(
"64-bit memory bar, merged next barword. Addr: 0x{:x}",
base_addr
);
write_config(bus, device, register, u32::MAX);
let sizebits = read_config(bus, device, register);
let size = if sizebits == 0 {
write_config(bus, device, register_high, u32::MAX);
let sizebits = read_config(bus, device, register_high);
write_config(bus, device, register_high, barword);
((!sizebits + 1) as usize) << 32
} else {
(!(sizebits & PCI_MEM_BASE_ADDRESS_MASK) + 1) as usize
};
write_config(bus, device, register, barword);
bars.push(PciBar::Memory(MemoryBar {
index: i as u8,
addr: base_addr,
size,
width: 64,
prefetchable,
}));
} else {
let base_addr = (barword & 0xFFFF_FFF0) as usize;
write_config(bus, device, register, u32::MAX);
let size = !(read_config(bus, device, register) & PCI_MEM_BASE_ADDRESS_MASK) + 1;
write_config(bus, device, register, barword);
bars.push(PciBar::Memory(MemoryBar {
index: i as u8,
addr: base_addr,
size: size.try_into().unwrap(),
width: 32,
prefetchable,
}));
}
}
}
bars
}
impl PciAdapter {
fn new(bus: u8, device: u8, vendor_id: u16, device_id: u16) -> Option<Self> {
let header = read_config(bus, device, PCI_HEADER_REGISTER);
if header & PCI_HEADER_TYPE_MASK != 0 {
error!(
"PCI Device @{:x}:{:x} does not have header type 0!",
vendor_id, device_id
);
return None;
}
if header & PCI_MULTIFUNCTION_MASK != 0 {
warn!(
"PCI Device @{:x}:{:x} has multiple functions! Currently only one is handled.",
vendor_id, device_id
);
}
let class_ids = read_config(bus, device, PCI_CLASS_REGISTER);
let bars = parse_bars(bus, device, vendor_id, device_id);
let interrupt_info = read_config(bus, device, PCI_INTERRUPT_REGISTER);
Some(Self {
bus,
device,
vendor_id,
device_id,
class_id: (class_ids >> 24) as u8,
subclass_id: (class_ids >> 16) as u8,
programming_interface_id: (class_ids >> 8) as u8,
base_addresses: bars,
irq: interrupt_info as u8,
})
}
pub fn make_bus_master(&self) {
let mut command = read_config(self.bus, self.device, PCI_COMMAND_REGISTER);
command |= PCI_COMMAND_BUSMASTER;
write_config(self.bus, self.device, PCI_COMMAND_REGISTER, command);
}
pub fn get_bar(&self, baridx: u8) -> Option<PciBar> {
for pci_bar in &self.base_addresses {
match pci_bar {
PciBar::IO(pci_bar) => {
if pci_bar.index == baridx {
return Some(PciBar::IO(*pci_bar));
}
}
PciBar::Memory(pci_bar) => {
if pci_bar.index == baridx {
return Some(PciBar::Memory(*pci_bar));
}
}
}
}
None
}
pub fn memory_map_bar(&self, index: u8, no_cache: bool) -> Option<(VirtAddr, usize)> {
let pci_bar = match self.get_bar(index) {
Some(PciBar::IO(_)) => {
warn!("Cannot map IOBar!");
return None;
}
Some(PciBar::Memory(mem_bar)) => mem_bar,
None => {
warn!("Memory bar not found!");
return None;
}
};
debug!(
"Mapping bar {} at 0x{:x} with length 0x{:x}",
index, pci_bar.addr, pci_bar.size
);
if pci_bar.width != 64 {
warn!("Currently only mapping of 64 bit bars is supported!");
return None;
}
if !pci_bar.prefetchable {
warn!("Currently only mapping of prefetchable bars is supported!")
}
let physical_address = pci_bar.addr;
let virtual_address = crate::mm::map(
PhysAddr::from(physical_address),
pci_bar.size,
true,
false,
no_cache,
);
Some((virtual_address, pci_bar.size))
}
}
impl fmt::Display for PciBar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (typ, addr, size) = match self {
PciBar::IO(io_bar) => ("IOBar", io_bar.addr as usize, io_bar.size as usize),
PciBar::Memory(mem_bar) => ("MemoryBar", mem_bar.addr, mem_bar.size),
};
write!(f, "{}: 0x{:x} (size 0x{:x})", typ, addr, size)?;
Ok(())
}
}
impl fmt::Display for PciAdapter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut class_name = "Unknown Class";
for ref c in CLASSES {
if c.id == self.class_id {
class_name = c.name;
for ref sc in c.subclasses {
if sc.id == self.subclass_id {
class_name = sc.name;
break;
}
}
break;
}
}
let mut vendor_name = "Unknown Vendor";
let mut device_name = "Unknown Device";
for ref v in VENDORS {
if v.id == self.vendor_id {
vendor_name = v.name;
for ref d in v.devices {
if d.id == self.device_id {
device_name = d.name;
break;
}
}
break;
}
}
write!(
f,
"{:02X}:{:02X} {} [{:02X}{:02X}]: {} {} [{:04X}:{:04X}]",
self.bus,
self.device,
class_name,
self.class_id,
self.subclass_id,
vendor_name,
device_name,
self.vendor_id,
self.device_id
)?;
if self.irq != 0 && self.irq != u8::MAX {
write!(f, ", IRQ {}", self.irq)?;
}
for pci_bar in &self.base_addresses {
write!(f, ", {}", pci_bar)?;
}
Ok(())
}
}
pub fn read_config(bus: u8, device: u8, register: u32) -> u32 {
let address =
PCI_CONFIG_ADDRESS_ENABLE | u32::from(bus) << 16 | u32::from(device) << 11 | register;
unsafe {
outl(PCI_CONFIG_ADDRESS_PORT, address);
inl(PCI_CONFIG_DATA_PORT)
}
}
pub fn write_config(bus: u8, device: u8, register: u32, data: u32) {
let address =
PCI_CONFIG_ADDRESS_ENABLE | u32::from(bus) << 16 | u32::from(device) << 11 | register;
unsafe {
outl(PCI_CONFIG_ADDRESS_PORT, address);
outl(PCI_CONFIG_DATA_PORT, data);
}
}
pub fn get_adapter(vendor_id: u16, device_id: u16) -> Option<PciAdapter> {
for adapter in unsafe { PCI_ADAPTERS.iter() } {
if adapter.vendor_id == vendor_id && adapter.device_id == device_id {
return Some(adapter.clone());
}
}
None
}
pub fn init() {
debug!("Scanning PCI Busses 0 to {}", PCI_MAX_BUS_NUMBER - 1);
for bus in 0..PCI_MAX_BUS_NUMBER {
for device in 0..PCI_MAX_DEVICE_NUMBER {
let device_vendor_id = read_config(bus, device, PCI_ID_REGISTER);
if device_vendor_id != u32::MAX {
let device_id = (device_vendor_id >> 16) as u16;
let vendor_id = device_vendor_id as u16;
let adapter = PciAdapter::new(bus, device, vendor_id, device_id);
if let Some(adapter) = adapter {
unsafe {
PCI_ADAPTERS.push(adapter);
}
}
}
}
}
}
pub fn init_drivers() {
let mut nic_available = false;
irqsave(|| {
for adapter in unsafe {
PCI_ADAPTERS
.iter()
.filter(|x| x.vendor_id == 0x1AF4 && x.device_id >= 0x1000 && x.device_id <= 0x107F)
} {
info!(
"Found virtio network device with device id 0x{:x}",
adapter.device_id
);
match pci_virtio::init_device(&adapter) {
Ok(drv) => match drv {
VirtioDriver::Network(drv) => {
nic_available = true;
register_driver(PciDriver::VirtioNet(SpinlockIrqSave::new(drv)))
}
VirtioDriver::FileSystem => (),
},
Err(_) => (),
}
}
if !nic_available {
for adapter in unsafe {
PCI_ADAPTERS.iter().filter(|x| {
x.vendor_id == 0x10ec && x.device_id >= 0x8138 && x.device_id <= 0x8139
})
} {
info!(
"Found Realtek network device with device id 0x{:x}",
adapter.device_id
);
match rtl8139::init_device(&adapter) {
Ok(drv) => register_driver(PciDriver::RTL8139Net(SpinlockIrqSave::new(drv))),
Err(_) => (),
}
}
}
});
}
pub fn print_information() {
infoheader!(" PCI BUS INFORMATION ");
for adapter in unsafe { PCI_ADAPTERS.iter() } {
info!("{}", adapter);
}
infofooter!();
}
pub mod error {
#[derive(Debug)]
pub enum PciError {
General(u16),
NoBar(u16),
NoCapPtr(u16),
BadCapPtr(u16),
NoBarForCap(u16),
NoVirtioCaps(u16),
}
}