interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / dma_gate.rs

390 lines · 14992 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! PCI bus mastering (DMA) gate. Governing rule for M3: no SMMU confinement
17//! means no DMA.
18//!
19//! A PCI function can only start DMA while bit 2 of its Command register
20//! (Bus Master Enable, BME) is set. This module holds the pure decisions
21//! around that bit so they can be host tested:
22//!
23//! - [`sweep_bus_master`] walks an ECAM bus range after firmware exit and
24//! clears BME on every endpoint firmware left with it set, so each device
25//! starts with DMA off.
26//! - [`dma_grant`] decides whether a driver may set BME again: only when an
27//! SMMU translation domain for the device is installed, or when the
28//! explicit, unsafe, QEMU-only debug bypass is compiled in AND the platform
29//! describes no SMMU at all. A present SMMU that failed to initialise never
30//! falls back to the bypass.
31//!
32//! No MMIO happens here: config space is reached through [`PciConfig`].
33
34/// Offset of the 16-bit PCI Command register.
35pub const PCI_COMMAND: u16 = 0x04;
36/// Command register bit: memory space decode.
37pub const PCI_COMMAND_MEMORY: u16 = 1 << 1;
38/// Command register bit: Bus Master Enable (the device may issue DMA).
39pub const PCI_COMMAND_BUS_MASTER: u16 = 1 << 2;
40
41/// Whether `command` lets the device issue DMA.
42pub const fn bus_master_enabled(command: u16) -> bool {
43 command & PCI_COMMAND_BUS_MASTER != 0
44}
45
46/// `command` with Bus Master Enable cleared and every other bit kept.
47pub const fn without_bus_master(command: u16) -> u16 {
48 command & !PCI_COMMAND_BUS_MASTER
49}
50
51/// `command` with memory decode and Bus Master Enable set.
52pub const fn with_bus_master(command: u16) -> u16 {
53 command | PCI_COMMAND_MEMORY | PCI_COMMAND_BUS_MASTER
54}
55
56/// Why a device got DMA.
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum DmaGrant {
59 /// An SMMU domain translates this device's stream: confined DMA.
60 Confined,
61 /// UNSAFE: no SMMU on the platform and the debug bypass is compiled in.
62 /// The device reaches physical memory directly. QEMU debugging only.
63 UnsafeBypass,
64}
65
66/// Why a device stays without DMA (Bus Master Enable left clear).
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum DmaDenied {
69 /// The platform describes no SMMU (no IORT SMMUv3 node).
70 NoSmmu,
71 /// An SMMU exists but no domain for this device is installed.
72 SmmuNotReady,
73}
74
75/// Decide whether a device may have Bus Master Enable set.
76///
77/// - `smmu_ready`: a translation domain for this device's stream is live.
78/// - `smmu_present`: firmware described an SMMU for this platform.
79/// - `unsafe_bypass`: the `unsafe-debug-dma-without-smmu` build feature.
80///
81/// The bypass only applies when there is no SMMU at all. If an SMMU exists
82/// and its setup failed, the answer is always [`DmaDenied::SmmuNotReady`].
83pub const fn dma_grant(
84 smmu_ready: bool,
85 smmu_present: bool,
86 unsafe_bypass: bool,
87) -> Result<DmaGrant, DmaDenied> {
88 if smmu_ready {
89 Ok(DmaGrant::Confined)
90 } else if smmu_present {
91 Err(DmaDenied::SmmuNotReady)
92 } else if unsafe_bypass {
93 Ok(DmaGrant::UnsafeBypass)
94 } else {
95 Err(DmaDenied::NoSmmu)
96 }
97}
98
99/// Config space access for one PCI segment (an ECAM window).
100pub trait PciConfig {
101 /// Read the 32-bit register at `offset`, `None` when outside the window.
102 fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32>;
103 /// Write the 16-bit register at `offset`. A 16-bit write keeps the
104 /// write-one-to-clear Status bits next to the Command register intact.
105 fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16);
106}
107
108/// A PCI function address on one segment.
109#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
110pub struct Bdf {
111 pub bus: u8,
112 pub device: u8,
113 pub function: u8,
114}
115
116/// One endpoint whose Bus Master Enable the sweep found set.
117#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118pub struct BusMasterFinding {
119 pub at: Bdf,
120 /// Command register as firmware left it.
121 pub command_before: u16,
122 /// Command register read back after the clear.
123 pub command_after: u16,
124}
125
126impl BusMasterFinding {
127 /// Whether the clear took effect.
128 pub const fn cleared(&self) -> bool {
129 !bus_master_enabled(self.command_after)
130 }
131}
132
133/// Findings kept in full; later ones are only counted.
134pub const SWEEP_FINDINGS: usize = 8;
135
136/// Result of [`sweep_bus_master`].
137#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
138pub struct BusMasterSweep {
139 /// Functions that answered a config read.
140 pub functions: u16,
141 /// PCI-to-PCI bridges among them (left untouched, see below).
142 pub bridges: u16,
143 /// Bridges with Bus Master Enable set.
144 pub bridges_bus_master: u16,
145 /// Endpoints firmware left with Bus Master Enable set.
146 pub endpoints_bus_master: u16,
147 /// Endpoints whose Bus Master Enable is still set after the clear.
148 pub still_enabled: u16,
149 /// The first [`SWEEP_FINDINGS`] endpoints found with BME set.
150 pub findings: [BusMasterFinding; SWEEP_FINDINGS],
151}
152
153impl BusMasterSweep {
154 /// The recorded findings.
155 pub fn findings(&self) -> &[BusMasterFinding] {
156 let n = usize::from(self.endpoints_bus_master).min(SWEEP_FINDINGS);
157 &self.findings[..n]
158 }
159}
160
161/// Walk buses `start_bus..=end_bus` and clear Bus Master Enable on every
162/// endpoint (header type 0) that has it set. Bridges (header type 1) are
163/// counted but not changed: a bridge's BME only forwards DMA from devices
164/// below it, and those devices are cleared individually.
165pub fn sweep_bus_master<C: PciConfig>(
166 config: &mut C,
167 start_bus: u8,
168 end_bus: u8,
169) -> BusMasterSweep {
170 let mut sweep = BusMasterSweep::default();
171 for bus in start_bus..=end_bus {
172 for device in 0..32u8 {
173 for function in 0..8u8 {
174 let present = config
175 .read32(bus, device, function, 0)
176 .filter(|id| id & 0xffff != 0xffff);
177 if present.is_none() {
178 if function == 0 {
179 break;
180 }
181 continue;
182 }
183 sweep.functions = sweep.functions.saturating_add(1);
184 let header = config
185 .read32(bus, device, function, 0x0c)
186 .map_or(0, |v| ((v >> 16) & 0xff) as u8);
187 let command = config
188 .read32(bus, device, function, PCI_COMMAND)
189 .map_or(0, |v| v as u16);
190 if header & 0x7f == 0x01 {
191 sweep.bridges = sweep.bridges.saturating_add(1);
192 if bus_master_enabled(command) {
193 sweep.bridges_bus_master = sweep.bridges_bus_master.saturating_add(1);
194 }
195 } else if bus_master_enabled(command) {
196 config.write16(
197 bus,
198 device,
199 function,
200 PCI_COMMAND,
201 without_bus_master(command),
202 );
203 let after = config
204 .read32(bus, device, function, PCI_COMMAND)
205 .map_or(command, |v| v as u16);
206 let finding = BusMasterFinding {
207 at: Bdf {
208 bus,
209 device,
210 function,
211 },
212 command_before: command,
213 command_after: after,
214 };
215 if let Some(slot) = sweep
216 .findings
217 .get_mut(usize::from(sweep.endpoints_bus_master))
218 {
219 *slot = finding;
220 }
221 sweep.endpoints_bus_master = sweep.endpoints_bus_master.saturating_add(1);
222 if !finding.cleared() {
223 sweep.still_enabled = sweep.still_enabled.saturating_add(1);
224 }
225 }
226 if function == 0 && header & 0x80 == 0 {
227 break;
228 }
229 }
230 }
231 }
232 sweep
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238 use std::collections::BTreeMap;
239 use std::vec::Vec;
240
241 /// Config space image keyed by (bus, device, function); each entry holds
242 /// the vendor/device id, header type and Command register.
243 #[derive(Default)]
244 struct FakeConfig {
245 functions: BTreeMap<(u8, u8, u8), (u32, u8, u16)>,
246 /// Functions whose Command register ignores writes.
247 stuck: Vec<(u8, u8, u8)>,
248 writes: Vec<((u8, u8, u8), u16, u16)>,
249 }
250
251 impl PciConfig for FakeConfig {
252 fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32> {
253 let Some(&(id, header, command)) = self.functions.get(&(bus, device, function)) else {
254 return Some(u32::MAX);
255 };
256 Some(match offset {
257 0 => id,
258 0x0c => u32::from(header) << 16,
259 // Status bits in the upper half must survive a Command write.
260 PCI_COMMAND => 0x0010_0000 | u32::from(command),
261 _ => 0,
262 })
263 }
264 fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) {
265 self.writes.push(((bus, device, function), offset, value));
266 if self.stuck.contains(&(bus, device, function)) {
267 return;
268 }
269 if let Some(entry) = self.functions.get_mut(&(bus, device, function)) {
270 if offset == PCI_COMMAND {
271 entry.2 = value;
272 }
273 }
274 }
275 }
276
277 #[test]
278 fn command_bits() {
279 assert!(bus_master_enabled(0x0007));
280 assert!(!bus_master_enabled(0x0003));
281 assert_eq!(without_bus_master(0x0407), 0x0403);
282 assert_eq!(with_bus_master(0x0400), 0x0406);
283 }
284
285 #[test]
286 fn grant_requires_smmu_or_explicit_bypass_without_smmu() {
287 assert_eq!(dma_grant(true, true, false), Ok(DmaGrant::Confined));
288 assert_eq!(dma_grant(true, true, true), Ok(DmaGrant::Confined));
289 assert_eq!(dma_grant(false, false, false), Err(DmaDenied::NoSmmu));
290 assert_eq!(dma_grant(false, false, true), Ok(DmaGrant::UnsafeBypass));
291 }
292
293 #[test]
294 fn failed_smmu_never_falls_back_to_bypass() {
295 assert_eq!(dma_grant(false, true, false), Err(DmaDenied::SmmuNotReady));
296 assert_eq!(dma_grant(false, true, true), Err(DmaDenied::SmmuNotReady));
297 }
298
299 #[test]
300 fn sweep_clears_endpoints_and_leaves_bridges() {
301 let mut config = FakeConfig::default();
302 // Host bridge, BME off.
303 config.functions.insert((0, 0, 0), (0x0008_1b36, 0, 0x0000));
304 // Endpoint with BME on (virtio-blk left running by firmware).
305 config.functions.insert((0, 1, 0), (0x1042_1af4, 0, 0x0007));
306 // xHCI with memory decode only.
307 config.functions.insert((0, 2, 0), (0x000d_1b36, 0, 0x0002));
308 // Root port with BME on.
309 config.functions.insert((0, 3, 0), (0x000c_1b36, 1, 0x0007));
310 // Endpoint behind the root port with BME on.
311 config.functions.insert((1, 0, 0), (0x1234_abcd, 0, 0x0006));
312 let sweep = sweep_bus_master(&mut config, 0, 1);
313 assert_eq!(sweep.functions, 5);
314 assert_eq!(sweep.bridges, 1);
315 assert_eq!(sweep.bridges_bus_master, 1);
316 assert_eq!(sweep.endpoints_bus_master, 2);
317 assert_eq!(sweep.still_enabled, 0);
318 let found: Vec<_> = sweep.findings().iter().map(|f| f.at).collect();
319 assert_eq!(
320 found,
321 [
322 Bdf {
323 bus: 0,
324 device: 1,
325 function: 0
326 },
327 Bdf {
328 bus: 1,
329 device: 0,
330 function: 0
331 }
332 ]
333 );
334 assert_eq!(sweep.findings()[0].command_before, 0x0007);
335 assert_eq!(sweep.findings()[0].command_after, 0x0003);
336 assert_eq!(config.functions[&(0, 1, 0)].2, 0x0003);
337 assert_eq!(config.functions[&(0, 3, 0)].2, 0x0007, "bridge untouched");
338 assert_eq!(config.functions[&(0, 2, 0)].2, 0x0002, "no write when off");
339 assert_eq!(config.writes.len(), 2);
340 assert!(config.writes.iter().all(|w| w.1 == PCI_COMMAND));
341 }
342
343 #[test]
344 fn sweep_reports_a_bus_master_bit_that_will_not_clear() {
345 let mut config = FakeConfig::default();
346 config.functions.insert((0, 4, 0), (0x5678_abcd, 0, 0x0006));
347 config.stuck.push((0, 4, 0));
348 let sweep = sweep_bus_master(&mut config, 0, 0);
349 assert_eq!(sweep.endpoints_bus_master, 1);
350 assert_eq!(sweep.still_enabled, 1);
351 assert!(!sweep.findings()[0].cleared());
352 }
353
354 #[test]
355 fn sweep_walks_multifunction_devices_only_when_marked() {
356 let mut config = FakeConfig::default();
357 // Single-function device: function 1 must not be probed.
358 config
359 .functions
360 .insert((0, 5, 0), (0x1111_abcd, 0x00, 0x0004));
361 config
362 .functions
363 .insert((0, 5, 1), (0x2222_abcd, 0x00, 0x0004));
364 // Multi-function device: both functions are visited.
365 config
366 .functions
367 .insert((0, 6, 0), (0x3333_abcd, 0x80, 0x0004));
368 config
369 .functions
370 .insert((0, 6, 1), (0x4444_abcd, 0x00, 0x0004));
371 let sweep = sweep_bus_master(&mut config, 0, 0);
372 assert_eq!(sweep.functions, 3);
373 assert_eq!(sweep.endpoints_bus_master, 3);
374 assert_eq!(config.functions[&(0, 5, 1)].2, 0x0004, "never visited");
375 }
376
377 #[test]
378 fn sweep_keeps_counting_past_the_recorded_findings() {
379 let mut config = FakeConfig::default();
380 for device in 0..12u8 {
381 config
382 .functions
383 .insert((0, device, 0), (0x9999_abcd, 0, 0x0004));
384 }
385 let sweep = sweep_bus_master(&mut config, 0, 0);
386 assert_eq!(sweep.endpoints_bus_master, 12);
387 assert_eq!(sweep.findings().len(), SWEEP_FINDINGS);
388 assert!(config.functions.values().all(|f| f.2 == 0));
389 }
390}