ostd/bus/pci/cfg_space.rs
1// SPDX-License-Identifier: MPL-2.0
2//! The PCI configuration space.
3//!
4//! Reference: <https://wiki.osdev.org/PCI>
5use vstd::prelude::*;
6
7/*
8use alloc::sync::Arc;
9use core::mem::size_of;
10
11use bitflags_upstream::bitflags;
12
13use super::PciDeviceLocation;
14use crate::{
15 Error, Result,
16 arch::device::io_port::{PortRead, PortWrite},
17 io::IoMem,
18 mm::{
19 PodOnce, VmIoOnce,
20 page_prop::{CachePolicy, PageFlags},
21 },
22};
23
24/// Offset in PCI device's common configuration space(Not the PCI bridge).
25#[repr(u16)]
26pub enum PciDeviceCommonCfgOffset {
27 /// Vendor ID
28 VendorId = 0x00,
29 /// Device ID
30 DeviceId = 0x02,
31 /// PCI Command
32 Command = 0x04,
33 /// PCI Status
34 Status = 0x06,
35 /// Revision ID
36 RevisionId = 0x08,
37 /// Class code
38 ClassCode = 0x09,
39 /// Cache Line Size
40 CacheLineSize = 0x0C,
41 /// Latency Timer
42 LatencyTimer = 0x0D,
43 /// Header Type: Identifies the layout of the header.
44 HeaderType = 0x0E,
45 /// BIST: Represents the status and allows control of a devices BIST(built-in self test).
46 Bist = 0x0F,
47 /// Base Address Register #0
48 Bar0 = 0x10,
49 /// Base Address Register #1
50 Bar1 = 0x14,
51 /// Base Address Register #2
52 Bar2 = 0x18,
53 /// Base Address Register #3
54 Bar3 = 0x1C,
55 /// Base Address Register #4
56 Bar4 = 0x20,
57 /// Base Address Register #5
58 Bar5 = 0x24,
59 /// Cardbus CIS Pointer
60 CardbusCisPtr = 0x28,
61 /// Subsystem Vendor ID
62 SubsystemVendorId = 0x2C,
63 /// Subsystem ID
64 SubsystemId = 0x2E,
65 /// Expansion ROM base address
66 XromBar = 0x30,
67 /// Capabilities pointer
68 CapabilitiesPointer = 0x34,
69 /// Interrupt Line
70 InterruptLine = 0x3C,
71 /// INterrupt PIN
72 InterruptPin = 0x3D,
73 /// Min Grant
74 MinGrant = 0x3E,
75 /// Max latency
76 MaxLatency = 0x3F,
77}
78
79bitflags! {
80 /// PCI device common config space command register.
81 pub struct Command: u16 {
82 /// Sets to 1 if the device can respond to I/O Space accesses.
83 const IO_SPACE = 1 << 0;
84 /// Sets to 1 if the device can respond to Memory SPace accesses.
85 const MEMORY_SPACE = 1 << 1;
86 /// Sets to 1 if the device can behave as a bus master.
87 const BUS_MASTER = 1 << 2;
88 /// Sets to 1 if the device can monitor Special Cycle operations.
89 const SPECIAL_CYCLES = 1 << 3;
90 /// Memory Write and Invalidate Enable. Set to 1 if the device can
91 /// generate the Memory Write and Invalidate command.
92 const MWI_ENABLE = 1 << 4;
93 /// Sets to 1 if the device does not respond to palette register writes
94 /// and will snoop the data.
95 const VGA_PALETTE_SNOOP = 1 << 5;
96 /// Sets to 1 if the device will takes its normal action when a parity
97 /// error is detected.
98 const PARITY_ERROR_RESPONSE = 1 << 6;
99 /// Sets to 1 if the SERR# driver is enabled.
100 const SERR_ENABLE = 1 << 8;
101 /// Sets to 1 if the device is allowed to generate fast back-to-back
102 /// transactions
103 const FAST_BACK_TO_BACK_ENABLE = 1 << 9;
104 /// Sets to 1 if the assertion of the devices INTx# signal is disabled.
105 const INTERRUPT_DISABLE = 1 << 10;
106 }
107}
108
109bitflags! {
110 /// PCI device common config space status register.
111 pub struct Status: u16 {
112 /// The status of the device's INTx# signal.
113 const INTERRUPT_STATUS = 1 << 3;
114 /// Sets to 1 if the device support capabilities.
115 const CAPABILITIES_LIST = 1 << 4;
116 /// Sets to 1 if the device is capable of running at 66 MHz.
117 const MHZ66_CAPABLE = 1 << 5;
118 /// Sets to 1 if the device can accept fast back-to-back transactions
119 /// that are not from the same agent.
120 const FAST_BACK_TO_BACK_CAPABLE = 1 << 7;
121 /// This bit is only set when the following conditions are met:
122 /// 1. The bus agent asserted PERR# on a read or observed an assertion
123 /// of PERR# on a write
124 /// 2. The agent setting the bit acted as the bus master for the
125 /// operation in which the error occurred
126 /// 3. Bit 6 of the Command register (Parity Error Response bit) is set
127 /// to 1.
128 const MASTER_DATA_PARITY_ERROR = 1 << 8;
129 /// The read-only bit that represent the slowest time that a device will
130 /// assert DEVSEL# for any bus command except Configuration Space read
131 /// and writes.
132 ///
133 /// If both `DEVSEL_MEDIUM_TIMING` and `DEVSEL_SLOW_TIMING` are not set,
134 /// then it represents fast timing
135 const DEVSEL_MEDIUM_TIMING = 1 << 9;
136 /// Check `DEVSEL_MEDIUM_TIMING`
137 const DEVSEL_SLOW_TIMING = 1 << 10;
138 /// Sets to 1 when a target device terminates a transaction with Target-
139 /// Abort.
140 const SIGNALED_TARGET_ABORT = 1 << 11;
141 /// Sets to 1 by a master device when its transaction is terminated with
142 /// Target-Abort
143 const RECEIVED_TARGET_ABORT = 1 << 12;
144 /// Sets to 1 by a master device when its transaction (except for Special
145 /// Cycle transactions) is terminated with Master-Abort.
146 const RECEIVED_MASTER_ABORT = 1 << 13;
147 /// Sets to 1 when the device asserts SERR#
148 const SIGNALED_SYSTEM_ERROR = 1 << 14;
149 /// Sets to 1 when the device detects a parity error, even if parity error
150 /// handling is disabled.
151 const DETECTED_PARITY_ERROR = 1 << 15;
152 }
153}
154
155/// BAR space in PCI common config space.
156#[derive(Debug, Clone)]
157pub enum Bar {
158 /// Memory BAR
159 Memory(Arc<MemoryBar>),
160 /// I/O BAR
161 Io(Arc<IoBar>),
162}
163
164impl Bar {
165 pub(super) fn new(location: PciDeviceLocation, index: u8) -> Result<Self> {
166 if index >= 6 {
167 return Err(Error::InvalidArgs);
168 }
169 // Get the original value first, then write all 1 to the register to get the length
170 let offset = index as u16 * 4 + PciDeviceCommonCfgOffset::Bar0 as u16;
171 let raw = location.read32(offset);
172 location.write32(offset, !0);
173 let len_encoded = location.read32(offset);
174 location.write32(offset, raw);
175 if len_encoded == 0 {
176 // no BAR
177 return Err(Error::InvalidArgs);
178 }
179 Ok(if raw & 1 == 0 {
180 Self::Memory(Arc::new(MemoryBar::new(&location, index)?))
181 } else {
182 // IO BAR
183 Self::Io(Arc::new(IoBar::new(&location, index)?))
184 })
185 }
186
187 /// Reads a value of a specified type at a specified offset.
188 pub fn read_once<T: PodOnce + PortRead>(&self, offset: usize) -> Result<T> {
189 match self {
190 Bar::Memory(mem_bar) => mem_bar.io_mem().read_once(offset),
191 Bar::Io(io_bar) => io_bar.read(offset as u32),
192 }
193 }
194
195 /// Writes a value of a specified type at a specified offset.
196 pub fn write_once<T: PodOnce + PortWrite>(&self, offset: usize, value: T) -> Result<()> {
197 match self {
198 Bar::Memory(mem_bar) => mem_bar.io_mem().write_once(offset, &value),
199 Bar::Io(io_bar) => io_bar.write(offset as u32, value),
200 }
201 }
202}
203
204/// Memory BAR
205#[derive(Debug, Clone)]
206pub struct MemoryBar {
207 base: u64,
208 size: u32,
209 prefetchable: bool,
210 address_length: AddrLen,
211 io_memory: IoMem,
212}
213
214impl MemoryBar {
215 /// Memory BAR bits type
216 pub fn address_length(&self) -> AddrLen {
217 self.address_length
218 }
219
220 /// Whether this bar is prefetchable, allowing the CPU to get the data
221 /// in advance.
222 pub fn prefetchable(&self) -> bool {
223 self.prefetchable
224 }
225
226 /// Base address
227 pub fn base(&self) -> u64 {
228 self.base
229 }
230
231 /// Size of the memory
232 pub fn size(&self) -> u32 {
233 self.size
234 }
235
236 /// Grants I/O memory access
237 pub fn io_mem(&self) -> &IoMem {
238 &self.io_memory
239 }
240
241 /// Creates a memory BAR structure.
242 fn new(location: &PciDeviceLocation, index: u8) -> Result<Self> {
243 // Get the original value first, then write all 1 to the register to get the length
244 let offset = index as u16 * 4 + PciDeviceCommonCfgOffset::Bar0 as u16;
245 let raw = location.read32(offset);
246 location.write32(offset, !0);
247 let len_encoded = location.read32(offset);
248 location.write32(offset, raw);
249 let mut address_length = AddrLen::Bits32;
250 // base address, it may be bit64 or bit32
251 let raw_base: u64 = match (raw & 0b110) >> 1 {
252 // bits32
253 0 => (raw & !0xF) as u64,
254 // bits64
255 2 => {
256 address_length = AddrLen::Bits64;
257 ((raw & !0xF) as u64) | ((location.read32(offset + 4) as u64) << 32)
258 }
259 _ => {
260 return Err(Error::InvalidArgs);
261 }
262 };
263 // length
264 let size = (!(len_encoded & !0xF)).wrapping_add(1);
265
266 // Some architectures may not initialize PCI devices at all. Even in x86-64 systems, the
267 // BIOS may leave some devices uninitialized. If support is available, we can allocate the
268 // region ourselves. Otherwise, if the BAR is not properly initialized, we will ignore it
269 // and return an error.
270 #[cfg(not(target_arch = "loongarch64"))]
271 let base = if raw_base == 0 {
272 return Err(Error::InvalidArgs);
273 } else {
274 raw_base
275 };
276 // In LoongArch, the BAR base address needs to be allocated manually.
277 #[cfg(target_arch = "loongarch64")]
278 let base = {
279 use core::alloc::Layout;
280 crate::arch::pci::alloc_mmio(
281 Layout::from_size_align(size as usize, size as usize).unwrap(),
282 )
283 .unwrap() as u64
284 };
285
286 if address_length == AddrLen::Bits64 {
287 location.write32(offset, base as u32);
288 location.write32(offset + 4, (base >> 32) as u32);
289 } else {
290 location.write32(offset, base as u32);
291 }
292
293 let prefetchable = raw & 0b1000 != 0;
294 // The BAR is located in I/O memory region
295 Ok(MemoryBar {
296 base,
297 size,
298 prefetchable,
299 address_length,
300 io_memory: unsafe {
301 IoMem::new(
302 (base as usize)..((base + size as u64) as usize),
303 PageFlags::RW,
304 CachePolicy::Uncacheable,
305 )
306 },
307 })
308 }
309}
310
311/// Whether this BAR is 64bit address or 32bit address
312#[derive(Debug, Copy, Clone, PartialEq, Eq)]
313pub enum AddrLen {
314 /// 32 bits
315 Bits32,
316 /// 64 bits
317 Bits64,
318}
319
320*/
321
322/// I/O port BAR.
323#[verus_verify]
324#[derive(Debug, Clone, Copy)]
325pub struct IoBar {
326 base: u32,
327 size: u32,
328}
329#[verus_verify]
330impl IoBar {
331 /// Base port
332 #[verus_verify(dual_spec)]
333 #[verus_spec(returns self.base())]
334 pub fn base(&self) -> u32 {
335 self.base
336 }
337
338 /// Size of the port
339 #[verus_verify(dual_spec)]
340 #[verus_spec(returns self.size())]
341 pub fn size(&self) -> u32 {
342 self.size
343 }
344}
345
346/*
347impl IoBar {
348 /// Reads from port
349 pub fn read<T: PortRead>(&self, offset: u32) -> Result<T> {
350 // Check alignment
351 if (self.base + offset) % size_of::<T>() as u32 != 0 {
352 return Err(Error::InvalidArgs);
353 }
354 // Check overflow
355 if self.size < size_of::<T>() as u32 || offset > self.size - size_of::<T>() as u32 {
356 return Err(Error::InvalidArgs);
357 }
358 // SAFETY: The range of ports accessed is within the scope managed by the IoBar and
359 // an out-of-bounds check is performed.
360 unsafe { Ok(T::read_from_port((self.base + offset) as u16)) }
361 }
362
363 /// Writes to port
364 pub fn write<T: PortWrite>(&self, offset: u32, value: T) -> Result<()> {
365 // Check alignment
366 if (self.base + offset) % size_of::<T>() as u32 != 0 {
367 return Err(Error::InvalidArgs);
368 }
369 // Check overflow
370 if size_of::<T>() as u32 > self.size || offset > self.size - size_of::<T>() as u32 {
371 return Err(Error::InvalidArgs);
372 }
373 // SAFETY: The range of ports accessed is within the scope managed by the IoBar and
374 // an out-of-bounds check is performed.
375 unsafe { T::write_to_port((self.base + offset) as u16, value) }
376 Ok(())
377 }
378
379 fn new(location: &PciDeviceLocation, index: u8) -> Result<Self> {
380 let offset = index as u16 * 4 + PciDeviceCommonCfgOffset::Bar0 as u16;
381 let raw = location.read32(offset);
382 location.write32(offset, !0);
383 let len_encoded = location.read32(offset);
384 location.write32(offset, raw);
385 let len = !(len_encoded & !0x3) + 1;
386 Ok(Self {
387 base: raw & !0x3,
388 size: len,
389 })
390 }
391}
392*/