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

GitHub aien-dev/aienux#110 (code only)

closed derived 88c26584a7c3d920 #110

Imported from GitHub aien-dev/aienux#110 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base e943690e1036401d8998427b18114df7de3d6bc5 · Head 2a6b525b298b6246bb3955180001f088313d364e

Apply it

git checkout -b patch-88c26584a7c3d920 e943690e1036401d8998427b18114df7de3d6bc5
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/88c26584a7c3d920.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
110
2a6b525b298b6246bb3955180001f088313d364e
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":110,"url":"https://github.com/aien-dev/aienux/pull/110","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:44Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml
index a525c99a..bb08f0dc 100644
--- a/crates/aienos-boot/Cargo.toml
+++ b/crates/aienos-boot/Cargo.toml
@@ -18,7 +18,19 @@ handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc"]
 # SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012).
 # Only the QEMU keyboard test enables it; hardware staging never does.
 usb-keyboard = ["handoff"]
-debug-xhci-without-smmu = ["usb-keyboard"]
+# Marks an image built for Machine 1 (native hardware) staging.
+# scripts/stage_one_time_boot.sh builds with it. It adds no code; it exists so
+# unsafe debug features refuse to compile into a hardware image.
+hardware-staging = ["handoff"]
+# UNSAFE. DEBUG ONLY. QEMU ONLY. Lets the xHCI keyboard run DMA straight to
+# physical memory, with NO SMMU confinement, when the platform has no SMMU
+# at all. It breaks the M3 rule "no SMMU confinement means no DMA" and exists
+# only to debug the xHCI driver in a QEMU machine without iommu=smmuv3. It
+# never applies when an SMMU exists but failed to initialise, it prints a
+# warning on every boot, and it is a compile error together with
+# `hardware-staging`. Reach it only through AIENOS_UNSAFE_DMA_BYPASS=1 in
+# scripts/qemu_keyboard_test.sh.
+unsafe-debug-dma-without-smmu = ["usb-keyboard"]
 
 [dependencies]
 uefi = { version = "0.41", default-features = false, optional = true }
diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs
index 963805c2..0fe929ff 100644
--- a/crates/aienos-boot/src/handoff.rs
+++ b/crates/aienos-boot/src/handoff.rs
@@ -38,6 +38,8 @@ use aienos_kernel::report::ReportBuf;
 use aienos_kernel::sync::spinlock::SpinLock;
 use core::alloc::{GlobalAlloc, Layout};
 use core::fmt::Write;
+#[cfg(feature = "usb-keyboard")]
+use core::sync::atomic::AtomicUsize;
 use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
 use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams};
 use uefi::mem::memory_map::{MemoryMap, MemoryType};
@@ -60,16 +62,23 @@ static BOOT_SERVICES_LIVE: AtomicBool = AtomicBool::new(true);
 
 #[cfg(feature = "usb-keyboard")]
 #[repr(C)]
+// Field order keeps every queue aligned to its own size (the SMMU ignores
+// low base address bits below the queue size): stream table at 0 (256 KiB),
+// event queue at 256 KiB (512 bytes), command queue after it (256 bytes),
+// then the 64-byte context descriptor.
 struct SmmuTables {
     stream_table: [[u64; 8]; 4096],
-    command_queue: [[u64; 2]; 16],
-    event_queue: [[u64; 4]; 16],
+    event_queue: [[u64; 4]; SMMU_QUEUE_ENTRIES as usize],
+    command_queue: [[u64; 2]; SMMU_QUEUE_ENTRIES as usize],
     context: [u64; 8],
 }
 
 #[cfg(feature = "usb-keyboard")]
 const STREAM_ENTRIES: u32 = 4096;
 
+#[cfg(feature = "usb-keyboard")]
+const SMMU_QUEUE_ENTRIES: u32 = 16;
+
 // The linear stream table base must be aligned to its size (4096 * 64 bytes =
 // 256 KiB) or QEMU truncates it before fetching the STE. COFF/PE cannot encode
 // section alignment above 8192, so a 256 KiB-aligned static is unbuildable for
@@ -217,18 +226,19 @@ fn configure_smmu_for_xhci(
         .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
     let frames = FixedFramePool::new(PhysAddr(next), remaining)
         .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
-    let mut page_table = PageTableBuilder::new(frames, PhysicalTableMemory)
-        .map_err(aienos_kernel::smmu::Error::PageTable)?;
-    page_table
-        .map(
-            dma_base as usize,
-            PhysAddr(dma_base as usize),
-            dma_length,
-            MapFlags::KERNEL_DATA,
-        )
-        .map_err(aienos_kernel::smmu::Error::PageTable)?;
-    let dma_root = page_table.root().0;
-    let table_frames = page_table.frames_used().unwrap_or(0);
+    // Stage-1 table that maps only the xHCI DMA window (identity).
+    let policy = aienos_kernel::smmu::build_dma_policy(
+        stream_id,
+        1,
+        &[aienos_kernel::smmu::DmaWindow {
+            iova: dma_base as usize,
+            pa: PhysAddr(dma_base as usize),
+            length: dma_length,
+        }],
+        frames,
+        PhysicalTableMemory,
+    )?;
+    let table_frames = policy.page_table.frames_used().unwrap_or(0);
     clean_table_pool(next, table_frames * 4096);
 
     let tables = smmu_tables();
@@ -244,22 +254,30 @@ fn configure_smmu_for_xhci(
         0,
         "SMMU stream table is not 256 KiB aligned"
     );
-    clean_table_pool(tables as usize, core::mem::size_of::<SmmuTables>());
-    let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) };
-    unsafe {
-        aienos_kernel::smmu::configure_linear_stream(
-            &mut regs,
-            stream_id,
-            STREAM_ENTRIES,
+    // Safety: the tables are one live, identity-mapped, 256 KiB-aligned
+    // allocation owned by the SMMU from here on; the register aperture is
+    // identity mapped (128 KiB) by enter_kernel_mmu. configure_linear_stream
+    // writes the tables and cleans them to the SMMU itself before it
+    // programs STRTAB_BASE or enables anything.
+    let linear = unsafe {
+        aienos_kernel::smmu::LinearTables::new(
             core::ptr::addr_of_mut!((*tables).stream_table).cast(),
-            16,
+            STREAM_ENTRIES,
             core::ptr::addr_of_mut!((*tables).command_queue).cast(),
-            16,
+            SMMU_QUEUE_ENTRIES,
             core::ptr::addr_of_mut!((*tables).event_queue).cast(),
+            SMMU_QUEUE_ENTRIES,
             core::ptr::addr_of_mut!((*tables).context),
-            dma_root as u64,
-        )?;
-    }
+        )?
+    };
+    let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) };
+    aienos_kernel::smmu::configure_linear_stream(
+        &mut regs,
+        &linear,
+        policy.stream_id,
+        &policy.cd,
+        aienos_kernel::smmu::DEFAULT_SPINS,
+    )?;
     Ok(stream_id)
 }
 
@@ -1386,6 +1404,11 @@ fn main() -> Status {
     let kernel_root = kernel_mmu.root;
     let runtime_rx_unsplit = kernel_mmu.runtime_rx_unsplit;
 
+    // Devices start with DMA off: clear Bus Master Enable on the xHCI's PCI
+    // segment before any SMMU stream or driver is set up (M3 1C.3).
+    #[cfg(feature = "usb-keyboard")]
+    let dma_takeover = usb_keyboard::take_over_dma(xhci, acpi_facts.mcfg);
+
     #[cfg(feature = "usb-keyboard")]
     let smmu_result =
         configure_smmu_for_xhci(acpi_facts.iort.as_ref(), xhci, pt_pool, pt_frames_used);
@@ -1680,7 +1703,7 @@ fn main() -> Status {
     #[cfg(feature = "usb-keyboard")]
     usb_keyboard::run(
         xhci,
-        acpi_facts.mcfg,
+        dma_takeover,
         &mut screen,
         summary.conventional_kb(),
         el,
diff --git a/crates/aienos-boot/src/lib.rs b/crates/aienos-boot/src/lib.rs
index ab069fb2..08cd759f 100644
--- a/crates/aienos-boot/src/lib.rs
+++ b/crates/aienos-boot/src/lib.rs
@@ -5,3 +5,18 @@ pub const FIRMWARE_BANNER: &str = "AIENOS firmware entry: aarch64";
 
 /// The UEFI diagnostic never provisions or reconstructs an agent identity.
 pub const CREATES_AGENT_IDENTITY: bool = false;
+
+// The unsafe DMA bypass lets a device reach physical memory with no SMMU
+// confinement. It is for QEMU debugging only and must never be part of an
+// image staged on Machine 1.
+#[cfg(all(
+    feature = "unsafe-debug-dma-without-smmu",
+    feature = "hardware-staging"
+))]
+compile_error!(
+    "feature `unsafe-debug-dma-without-smmu` (unconfined DMA, QEMU debug only) \
+     cannot be combined with `hardware-staging`: no SMMU confinement means no DMA"
+);
+
+/// Whether this build carries the unsafe, QEMU-only DMA bypass.
+pub const UNSAFE_DMA_BYPASS: bool = cfg!(feature = "unsafe-debug-dma-without-smmu");
diff --git a/crates/aienos-boot/src/usb_keyboard.rs b/crates/aienos-boot/src/usb_keyboard.rs
index 6c032c99..5b0d2d24 100644
--- a/crates/aienos-boot/src/usb_keyboard.rs
+++ b/crates/aienos-boot/src/usb_keyboard.rs
@@ -5,14 +5,20 @@
 //! Built only with the `usb-keyboard` feature, which the QEMU keyboard test
 //! enables and hardware staging does not: the candidate is proven in QEMU
 //! and never admitted to Machine 1 before M3 can confine it.
+//!
+//! DMA rule (M3): no SMMU confinement means no DMA. After firmware exit
+//! [`take_over_dma`] clears Bus Master Enable on every endpoint of the
+//! controller's PCI segment before any SMMU or driver setup, and [`run`] sets
+//! it on the xHCI again only when [`dma_gate::dma_grant`] allows it.
 
 use aienos_kernel::acpi::{self, EcamWindow};
 use aienos_kernel::arch::aarch64::{counter_frequency_hz, counter_ticks, MmioReg};
 use aienos_kernel::console::EarlyConsole;
 use aienos_kernel::display::Screen;
+use aienos_kernel::dma_gate::{self, BusMasterSweep, DmaGrant, PciConfig, PCI_COMMAND};
 use aienos_kernel::usb::hid::{BootKeyboardDecoder, KeyEvent};
+use aienos_kernel::usb::xhci;
 use aienos_kernel::usb::xhci::controller::{DmaMemory, Keyboard};
-use aienos_kernel::usb::xhci::{self, PCI_COMMAND_BUS_MASTER, PCI_COMMAND_MEMORY};
 use core::fmt::Write;
 use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams};
 use uefi::proto::pci::root_bridge::PciRootBridgeIo;
@@ -25,7 +31,10 @@ fn listen_secs() -> u64 {
         .unwrap_or(30)
 }
 
-const DEBUG_XHCI_WITHOUT_SMMU: bool = cfg!(feature = "debug-xhci-without-smmu");
+/// Printed on every boot of an image built with the unsafe DMA bypass.
+const UNSAFE_BYPASS_BANNER: &str =
+    "\nWARNING: UNSAFE DMA BYPASS BUILD (unsafe-debug-dma-without-smmu): \
+    xHCI DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n";
 
 /// DMA memory for the driver, used only after firmware exit.
 static mut DMA: DmaMemory = DmaMemory::new();
@@ -133,21 +142,108 @@ fn say(screen: &mut Option<Screen>, text: &str) {
     }
 }
 
-/// Enable memory decode and bus mastering through ECAM: firmware may have
-/// turned them off when it stopped its own USB driver at exit.
-fn enable_controller(ecam: &EcamWindow, at: &XhciLocation) -> bool {
-    let Some(addr) = ecam.config_address(at.bus, at.device, at.function, 0x04) else {
-        return false;
-    };
-    let command = MmioReg::<u16>::new(addr as usize);
-    command.write(command.read() | PCI_COMMAND_MEMORY | PCI_COMMAND_BUS_MASTER);
-    true
+/// Config space of one ECAM window, reached through the kernel identity map.
+/// Only valid after `enter_kernel_mmu` mapped the window as device memory.
+struct Ecam(EcamWindow);
+
+impl PciConfig for Ecam {
+    fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32> {
+        let addr = self.0.config_address(bus, device, function, offset)?;
+        Some(MmioReg::<u32>::new(addr as usize).read())
+    }
+    fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) {
+        if let Some(addr) = self.0.config_address(bus, device, function, offset) {
+            MmioReg::<u16>::new(addr as usize).write(value);
+        }
+    }
+}
+
+impl Ecam {
+    fn command(&mut self, at: &XhciLocation) -> Option<u16> {
+        self.read32(at.bus, at.device, at.function, PCI_COMMAND)
+            .map(|v| v as u16)
+    }
+    fn set_command(&mut self, at: &XhciLocation, value: u16) {
+        self.write16(at.bus, at.device, at.function, PCI_COMMAND, value);
+    }
+}
+
+/// What [`take_over_dma`] did to the controller's PCI segment.
+#[derive(Clone, Copy)]
+pub struct DmaTakeover {
+    window: EcamWindow,
+    sweep: BusMasterSweep,
+}
+
+/// Post-exit, before any SMMU or driver setup: clear Bus Master Enable on
+/// every endpoint in the xHCI's ECAM window, so every device there starts
+/// with DMA off. `None` (DMA state unknown, keyboard stays unavailable) when
+/// there is no controller or no ECAM window for it.
+pub fn take_over_dma(xhci: Option<XhciLocation>, mcfg: Option<&[u8]>) -> Option<DmaTakeover> {
+    let at = xhci?;
+    let window = acpi::mcfg_window(mcfg?, at.segment, at.bus)
+        .ok()
+        .flatten()?;
+    let sweep = dma_gate::sweep_bus_master(&mut Ecam(window), window.start_bus, window.end_bus);
+    Some(DmaTakeover { window, sweep })
+}
+
+fn report_takeover(screen: &mut Option<Screen>, takeover: &DmaTakeover) {
+    let (w, s) = (&takeover.window, &takeover.sweep);
+    let mut line = aienos_kernel::report::ReportBuf::<256>::new();
+    let _ = writeln!(
+        line,
+        "dma_sweep: seg {:04x} bus {:02x}-{:02x} functions={} bridges={} bridges_bme={} \
+         endpoints_bme_found={} still_enabled={}",
+        w.segment,
+        w.start_bus,
+        w.end_bus,
+        s.functions,
+        s.bridges,
+        s.bridges_bus_master,
+        s.endpoints_bus_master,
+        s.still_enabled
+    );
+    say(screen, line.as_str());
+    for f in s.findings() {
+        let mut entry = aienos_kernel::report::ReportBuf::<128>::new();
+        let _ = writeln!(
+            entry,
+            "dma_sweep: bme {} {:04x}:{:02x}:{:02x}.{} command {:#06x} -> {:#06x}",
+            if f.cleared() { "cleared" } else { "STUCK" },
+            w.segment,
+            f.at.bus,
+            f.at.device,
+            f.at.function,
+            f.command_before,
+            f.command_after
+        );
+        say(screen, entry.as_str());
+    }
+}
+
+/// Clear Bus Master Enable on the controller again (revoke its DMA).
+fn revoke_dma(screen: &mut Option<Screen>, ecam: &mut Ecam, at: &XhciLocation) {
+    if let Some(command) = ecam.command(at) {
+        ecam.set_command(at, dma_gate::without_bus_master(command));
+    }
+    let off = ecam
+        .command(at)
+        .is_some_and(|c| !dma_gate::bus_master_enabled(c));
+    say(
+        screen,
+        if off {
+            "dma_gate: xhci bus master revoked\n"
+        } else {
+            "dma_gate: xhci bus master revoke FAILED\n"
+        },
+    );
 }
 
 /// Post-exit: bring up the keyboard and echo keys until Enter or timeout.
 pub fn run(
     xhci: Option<XhciLocation>,
-    mcfg: Option<&[u8]>,
+    takeover: Option<DmaTakeover>,
     screen: &mut Option<Screen>,
     conventional_memory_kb: u64,
     _exception_level: u8,
@@ -157,6 +253,9 @@ pub fn run(
     smmu_stream_id: Option<u32>,
     smmu_events: *const [[u64; 4]; 16],
 ) {
+    if aienos_boot::UNSAFE_DMA_BYPASS {
+        say(screen, UNSAFE_BYPASS_BANNER);
+    }
     let mut line = aienos_kernel::report::ReportBuf::<512>::new();
     let Some(at) = xhci else {
         say(screen, "\nkeyboard: unavailable (no xHCI controller)\n");
@@ -168,34 +267,78 @@ pub fn run(
         at.segment, at.bus, at.device, at.function, at.mmio
     );
     say(screen, line.as_str());
-    if !smmu_ready && !DEBUG_XHCI_WITHOUT_SMMU {
+    let Some(takeover) = takeover else {
         say(
             screen,
-            "keyboard: unavailable (SMMU DMA isolation not active)\n",
+            "keyboard: unavailable (no ECAM window for the controller; DMA not granted)\n",
         );
         return;
-    }
-    let dma_mode = if smmu_ready {
-        "smmu-translated"
-    } else {
-        "debug-identity"
     };
-    let mut mode = aienos_kernel::report::ReportBuf::<128>::new();
+    report_takeover(screen, &takeover);
+    let mut ecam = Ecam(takeover.window);
+    let Some(command) = ecam.command(&at) else {
+        say(
+            screen,
+            "keyboard: unavailable (xHCI config space unreadable)\n",
+        );
+        return;
+    };
+    let mut state = aienos_kernel::report::ReportBuf::<96>::new();
     let _ = writeln!(
-        mode,
-        "xhci_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}",
-        core::ptr::addr_of!(DMA) as usize,
-        core::mem::size_of::<DmaMemory>()
+        state,
+        "xhci_pci: command={command:#06x} bus_master={}",
+        if dma_gate::bus_master_enabled(command) {
+            "on"
+        } else {
+            "off"
+        }
     );
-    say(screen, mode.as_str());
-    let ecam = mcfg.and_then(|t| acpi::mcfg_window(t, at.segment, at.bus).ok().flatten());
-    if !ecam.is_some_and(|w| enable_controller(&w, &at)) {
+    say(screen, state.as_str());
+    if dma_gate::bus_master_enabled(command) {
         say(
             screen,
-            "keyboard: unavailable (no ECAM window for the controller)\n",
+            "keyboard: unavailable (xHCI bus master would not clear)\n",
         );
         return;
     }
+    let grant = match dma_gate::dma_grant(
+        smmu_ready,
+        smmu_base.is_some(),
+        aienos_boot::UNSAFE_DMA_BYPASS,
+    ) {
+        Ok(grant) => grant,
+        Err(denied) => {
+            let mut msg = aienos_kernel::report::ReportBuf::<160>::new();
+            let _ = writeln!(
+                msg,
+                "dma_gate: xhci denied ({denied:?}), bus master stays off\n\
+                 keyboard: unavailable (SMMU DMA isolation not active)"
+            );
+            say(screen, msg.as_str());
+            return;
+        }
+    };
+    let dma_mode = match grant {
+        DmaGrant::Confined => "smmu-translated",
+        DmaGrant::UnsafeBypass => {
+            say(
+                screen,
+                "WARNING: UNSAFE DMA BYPASS ACTIVE: no SMMU on this machine, xHCI DMA \
+                 reaches physical memory UNCONFINED (QEMU debug only)\n",
+            );
+            "UNSAFE-identity-no-smmu"
+        }
+    };
+    let mut mode = aienos_kernel::report::ReportBuf::<192>::new();
+    let _ = writeln!(
+        mode,
+        "dma_gate: xhci granted ({grant:?}), bus master on\n\
+         xhci_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}",
+        core::ptr::addr_of!(DMA) as usize,
+        core::mem::size_of::<DmaMemory>()
+    );
+    ecam.set_command(&at, dma_gate::with_bus_master(command));
+    say(screen, mode.as_str());
     // SAFETY: firmware has exited and released the controller; DMA is used
     // by nothing else, is identity-mapped, and lives for the whole boot.
     let started = unsafe { Keyboard::start(at.mmio, core::ptr::addr_of_mut!(DMA)) };
@@ -205,6 +348,7 @@ pub fn run(
             let mut msg = aienos_kernel::report::ReportBuf::<512>::new();
             let _ = writeln!(msg, "keyboard: unavailable ({e:?})");
             say(screen, msg.as_str());
+            revoke_dma(screen, &mut ecam, &at);
             if let Some(base) = smmu_base {
                 let reg = |offset| MmioReg::<u32>::new(base as usize + offset).read();
                 aienos_kernel::arch::aarch64::clean_invalidate_dcache_range(
@@ -312,4 +456,5 @@ pub fn run(
     };
     let _ = writeln!(end, "\nkeyboard: done ({reason})",);
     say(screen, end.as_str());
+    revoke_dma(screen, &mut ecam, &at);
 }
diff --git a/crates/aienos-kernel/src/dma_gate.rs b/crates/aienos-kernel/src/dma_gate.rs
new file mode 100644
index 00000000..bfbc7e1b
--- /dev/null
+++ b/crates/aienos-kernel/src/dma_gate.rs
@@ -0,0 +1,375 @@
+//! PCI bus mastering (DMA) gate. Governing rule for M3: no SMMU confinement
+//! means no DMA.
+//!
+//! A PCI function can only start DMA while bit 2 of its Command register
+//! (Bus Master Enable, BME) is set. This module holds the pure decisions
+//! around that bit so they can be host tested:
+//!
+//! - [`sweep_bus_master`] walks an ECAM bus range after firmware exit and
+//!   clears BME on every endpoint firmware left with it set, so each device
+//!   starts with DMA off.
+//! - [`dma_grant`] decides whether a driver may set BME again: only when an
+//!   SMMU translation domain for the device is installed, or when the
+//!   explicit, unsafe, QEMU-only debug bypass is compiled in AND the platform
+//!   describes no SMMU at all. A present SMMU that failed to initialise never
+//!   falls back to the bypass.
+//!
+//! No MMIO happens here: config space is reached through [`PciConfig`].
+
+/// Offset of the 16-bit PCI Command register.
+pub const PCI_COMMAND: u16 = 0x04;
+/// Command register bit: memory space decode.
+pub const PCI_COMMAND_MEMORY: u16 = 1 << 1;
+/// Command register bit: Bus Master Enable (the device may issue DMA).
+pub const PCI_COMMAND_BUS_MASTER: u16 = 1 << 2;
+
+/// Whether `command` lets the device issue DMA.
+pub const fn bus_master_enabled(command: u16) -> bool {
+    command & PCI_COMMAND_BUS_MASTER != 0
+}
+
+/// `command` with Bus Master Enable cleared and every other bit kept.
+pub const fn without_bus_master(command: u16) -> u16 {
+    command & !PCI_COMMAND_BUS_MASTER
+}
+
+/// `command` with memory decode and Bus Master Enable set.
+pub const fn with_bus_master(command: u16) -> u16 {
+    command | PCI_COMMAND_MEMORY | PCI_COMMAND_BUS_MASTER
+}
+
+/// Why a device got DMA.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum DmaGrant {
+    /// An SMMU domain translates this device's stream: confined DMA.
+    Confined,
+    /// UNSAFE: no SMMU on the platform and the debug bypass is compiled in.
+    /// The device reaches physical memory directly. QEMU debugging only.
+    UnsafeBypass,
+}
+
+/// Why a device stays without DMA (Bus Master Enable left clear).
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum DmaDenied {
+    /// The platform describes no SMMU (no IORT SMMUv3 node).
+    NoSmmu,
+    /// An SMMU exists but no domain for this device is installed.
+    SmmuNotReady,
+}
+
+/// Decide whether a device may have Bus Master Enable set.
+///
+/// - `smmu_ready`: a translation domain for this device's stream is live.
+/// - `smmu_present`: firmware described an SMMU for this platform.
+/// - `unsafe_bypass`: the `unsafe-debug-dma-without-smmu` build feature.
+///
+/// The bypass only applies when there is no SMMU at all. If an SMMU exists
+/// and its setup failed, the answer is always [`DmaDenied::SmmuNotReady`].
+pub const fn dma_grant(
+    smmu_ready: bool,
+    smmu_present: bool,
+    unsafe_bypass: bool,
+) -> Result<DmaGrant, DmaDenied> {
+    if smmu_ready {
+        Ok(DmaGrant::Confined)
+    } else if smmu_present {
+        Err(DmaDenied::SmmuNotReady)
+    } else if unsafe_bypass {
+        Ok(DmaGrant::UnsafeBypass)
+    } else {
+        Err(DmaDenied::NoSmmu)
+    }
+}
+
+/// Config space access for one PCI segment (an ECAM window).
+pub trait PciConfig {
+    /// Read the 32-bit register at `offset`, `None` when outside the window.
+    fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32>;
+    /// Write the 16-bit register at `offset`. A 16-bit write keeps the
+    /// write-one-to-clear Status bits next to the Command register intact.
+    fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16);
+}
+
+/// A PCI function address on one segment.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct Bdf {
+    pub bus: u8,
+    pub device: u8,
+    pub function: u8,
+}
+
+/// One endpoint whose Bus Master Enable the sweep found set.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct BusMasterFinding {
+    pub at: Bdf,
+    /// Command register as firmware left it.
+    pub command_before: u16,
+    /// Command register read back after the clear.
+    pub command_after: u16,
+}
+
+impl BusMasterFinding {
+    /// Whether the clear took effect.
+    pub const fn cleared(&self) -> bool {
+        !bus_master_enabled(self.command_after)
+    }
+}
+
+/// Findings kept in full; later ones are only counted.
+pub const SWEEP_FINDINGS: usize = 8;
+
+/// Result of [`sweep_bus_master`].
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct BusMasterSweep {
+    /// Functions that answered a config read.
+    pub functions: u16,
+    /// PCI-to-PCI bridges among them (left untouched, see below).
+    pub bridges: u16,
+    /// Bridges with Bus Master Enable set.
+    pub bridges_bus_master: u16,
+    /// Endpoints firmware left with Bus Master Enable set.
+    pub endpoints_bus_master: u16,
+    /// Endpoints whose Bus Master Enable is still set after the clear.
+    pub still_enabled: u16,
+    /// The first [`SWEEP_FINDINGS`] endpoints found with BME set.
+    pub findings: [BusMasterFinding; SWEEP_FINDINGS],
+}
+
+impl BusMasterSweep {
+    /// The recorded findings.
+    pub fn findings(&self) -> &[BusMasterFinding] {
+        let n = usize::from(self.endpoints_bus_master).min(SWEEP_FINDINGS);
+        &self.findings[..n]
+    }
+}
+
+/// Walk buses `start_bus..=end_bus` and clear Bus Master Enable on every
+/// endpoint (header type 0) that has it set. Bridges (header type 1) are
+/// counted but not changed: a bridge's BME only forwards DMA from devices
+/// below it, and those devices are cleared individually.
+pub fn sweep_bus_master<C: PciConfig>(
+    config: &mut C,
+    start_bus: u8,
+    end_bus: u8,
+) -> BusMasterSweep {
+    let mut sweep = BusMasterSweep::default();
+    for bus in start_bus..=end_bus {
+        for device in 0..32u8 {
+            for function in 0..8u8 {
+                let present = config
+                    .read32(bus, device, function, 0)
+                    .filter(|id| id & 0xffff != 0xffff);
+                if present.is_none() {
+                    if function == 0 {
+                        break;
+                    }
+                    continue;
+                }
+                sweep.functions = sweep.functions.saturating_add(1);
+                let header = config
+                    .read32(bus, device, function, 0x0c)
+                    .map_or(0, |v| ((v >> 16) & 0xff) as u8);
+                let command = config
+                    .read32(bus, device, function, PCI_COMMAND)
+                    .map_or(0, |v| v as u16);
+                if header & 0x7f == 0x01 {
+                    sweep.bridges = sweep.bridges.saturating_add(1);
+                    if bus_master_enabled(command) {
+                        sweep.bridges_bus_master = sweep.bridges_bus_master.saturating_add(1);
+                    }
+                } else if bus_master_enabled(command) {
+                    config.write16(
+                        bus,
+                        device,
+                        function,
+                        PCI_COMMAND,
+                        without_bus_master(command),
+                    );
+                    let after = config
+                        .read32(bus, device, function, PCI_COMMAND)
+                        .map_or(command, |v| v as u16);
+                    let finding = BusMasterFinding {
+                        at: Bdf {
+                            bus,
+                            device,
+                            function,
+                        },
+                        command_before: command,
+                        command_after: after,
+                    };
+                    if let Some(slot) = sweep
+                        .findings
+                        .get_mut(usize::from(sweep.endpoints_bus_master))
+                    {
+                        *slot = finding;
+                    }
+                    sweep.endpoints_bus_master = sweep.endpoints_bus_master.saturating_add(1);
+                    if !finding.cleared() {
+                        sweep.still_enabled = sweep.still_enabled.saturating_add(1);
+                    }
+                }
+                if function == 0 && header & 0x80 == 0 {
+                    break;
+                }
+            }
+        }
+    }
+    sweep
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::collections::BTreeMap;
+    use std::vec::Vec;
+
+    /// Config space image keyed by (bus, device, function); each entry holds
+    /// the vendor/device id, header type and Command register.
+    #[derive(Default)]
+    struct FakeConfig {
+        functions: BTreeMap<(u8, u8, u8), (u32, u8, u16)>,
+        /// Functions whose Command register ignores writes.
+        stuck: Vec<(u8, u8, u8)>,
+        writes: Vec<((u8, u8, u8), u16, u16)>,
+    }
+
+    impl PciConfig for FakeConfig {
+        fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32> {
+            let Some(&(id, header, command)) = self.functions.get(&(bus, device, function)) else {
+                return Some(u32::MAX);
+            };
+            Some(match offset {
+                0 => id,
+                0x0c => u32::from(header) << 16,
+                // Status bits in the upper half must survive a Command write.
+                PCI_COMMAND => 0x0010_0000 | u32::from(command),
+                _ => 0,
+            })
+        }
+        fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) {
+            self.writes.push(((bus, device, function), offset, value));
+            if self.stuck.contains(&(bus, device, function)) {
+                return;
+            }
+            if let Some(entry) = self.functions.get_mut(&(bus, device, function)) {
+                if offset == PCI_COMMAND {
+                    entry.2 = value;
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn command_bits() {
+        assert!(bus_master_enabled(0x0007));
+        assert!(!bus_master_enabled(0x0003));
+        assert_eq!(without_bus_master(0x0407), 0x0403);
+        assert_eq!(with_bus_master(0x0400), 0x0406);
+    }
+
+    #[test]
+    fn grant_requires_smmu_or_explicit_bypass_without_smmu() {
+        assert_eq!(dma_grant(true, true, false), Ok(DmaGrant::Confined));
+        assert_eq!(dma_grant(true, true, true), Ok(DmaGrant::Confined));
+        assert_eq!(dma_grant(false, false, false), Err(DmaDenied::NoSmmu));
+        assert_eq!(dma_grant(false, false, true), Ok(DmaGrant::UnsafeBypass));
+    }
+
+    #[test]
+    fn failed_smmu_never_falls_back_to_bypass() {
+        assert_eq!(dma_grant(false, true, false), Err(DmaDenied::SmmuNotReady));
+        assert_eq!(dma_grant(false, true, true), Err(DmaDenied::SmmuNotReady));
+    }
+
+    #[test]
+    fn sweep_clears_endpoints_and_leaves_bridges() {
+        let mut config = FakeConfig::default();
+        // Host bridge, BME off.
+        config.functions.insert((0, 0, 0), (0x0008_1b36, 0, 0x0000));
+        // Endpoint with BME on (virtio-blk left running by firmware).
+        config.functions.insert((0, 1, 0), (0x1042_1af4, 0, 0x0007));
+        // xHCI with memory decode only.
+        config.functions.insert((0, 2, 0), (0x000d_1b36, 0, 0x0002));
+        // Root port with BME on.
+        config.functions.insert((0, 3, 0), (0x000c_1b36, 1, 0x0007));
+        // Endpoint behind the root port with BME on.
+        config.functions.insert((1, 0, 0), (0x1234_abcd, 0, 0x0006));
+        let sweep = sweep_bus_master(&mut config, 0, 1);
+        assert_eq!(sweep.functions, 5);
+        assert_eq!(sweep.bridges, 1);
+        assert_eq!(sweep.bridges_bus_master, 1);
+        assert_eq!(sweep.endpoints_bus_master, 2);
+        assert_eq!(sweep.still_enabled, 0);
+        let found: Vec<_> = sweep.findings().iter().map(|f| f.at).collect();
+        assert_eq!(
+            found,
+            [
+                Bdf {
+                    bus: 0,
+                    device: 1,
+                    function: 0
+                },
+                Bdf {
+                    bus: 1,
+                    device: 0,
+                    function: 0
+                }
+            ]
+        );
+        assert_eq!(sweep.findings()[0].command_before, 0x0007);
+        assert_eq!(sweep.findings()[0].command_after, 0x0003);
+        assert_eq!(config.functions[&(0, 1, 0)].2, 0x0003);
+        assert_eq!(config.functions[&(0, 3, 0)].2, 0x0007, "bridge untouched");
+        assert_eq!(config.functions[&(0, 2, 0)].2, 0x0002, "no write when off");
+        assert_eq!(config.writes.len(), 2);
+        assert!(config.writes.iter().all(|w| w.1 == PCI_COMMAND));
+    }
+
+    #[test]
+    fn sweep_reports_a_bus_master_bit_that_will_not_clear() {
+        let mut config = FakeConfig::default();
+        config.functions.insert((0, 4, 0), (0x5678_abcd, 0, 0x0006));
+        config.stuck.push((0, 4, 0));
+        let sweep = sweep_bus_master(&mut config, 0, 0);
+        assert_eq!(sweep.endpoints_bus_master, 1);
+        assert_eq!(sweep.still_enabled, 1);
+        assert!(!sweep.findings()[0].cleared());
+    }
+
+    #[test]
+    fn sweep_walks_multifunction_devices_only_when_marked() {
+        let mut config = FakeConfig::default();
+        // Single-function device: function 1 must not be probed.
+        config
+            .functions
+            .insert((0, 5, 0), (0x1111_abcd, 0x00, 0x0004));
+        config
+            .functions
+            .insert((0, 5, 1), (0x2222_abcd, 0x00, 0x0004));
+        // Multi-function device: both functions are visited.
+        config
+            .functions
+            .insert((0, 6, 0), (0x3333_abcd, 0x80, 0x0004));
+        config
+            .functions
+            .insert((0, 6, 1), (0x4444_abcd, 0x00, 0x0004));
+        let sweep = sweep_bus_master(&mut config, 0, 0);
+        assert_eq!(sweep.functions, 3);
+        assert_eq!(sweep.endpoints_bus_master, 3);
+        assert_eq!(config.functions[&(0, 5, 1)].2, 0x0004, "never visited");
+    }
+
+    #[test]
+    fn sweep_keeps_counting_past_the_recorded_findings() {
+        let mut config = FakeConfig::default();
+        for device in 0..12u8 {
+            config
+                .functions
+                .insert((0, device, 0), (0x9999_abcd, 0, 0x0004));
+        }
+        let sweep = sweep_bus_master(&mut config, 0, 0);
+        assert_eq!(sweep.endpoints_bus_master, 12);
+        assert_eq!(sweep.findings().len(), SWEEP_FINDINGS);
+        assert!(config.functions.values().all(|f| f.2 == 0));
+    }
+}
diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs
index 34905f71..d63d0a5a 100644
--- a/crates/aienos-kernel/src/lib.rs
+++ b/crates/aienos-kernel/src/lib.rs
@@ -20,6 +20,7 @@ pub mod caps;
 pub mod console;
 pub mod crypto;
 pub mod display;
+pub mod dma_gate;
 pub mod fatal;
 pub mod gic;
 pub mod infer;
diff --git a/crates/aienos-kernel/src/smmu.rs b/crates/aienos-kernel/src/smmu.rs
index f31fb5fc..c01ad603 100644
--- a/crates/aienos-kernel/src/smmu.rs
+++ b/crates/aienos-kernel/src/smmu.rs
@@ -1,11 +1,23 @@
 //! Host-testable SMMUv3 descriptors, queues, and register sequencing.
-//! This module does not map MMIO or perform cache maintenance.
+//!
+//! This module does not map MMIO. Register access and the cache maintenance
+//! that makes CPU-written tables visible to the SMMU both go through the
+//! [`Registers`] trait, so the whole bring-up runs against a fake in host
+//! tests.
+//!
+//! Governing rule: no SMMU confinement means no DMA. The bring-up sets
+//! GBPA.ABORT before anything else and never clears it, so a disabled SMMU
+//! (SMMUEN = 0) aborts every transaction instead of bypassing. Once SMMUEN is
+//! acknowledged, each stream follows its own STE, and every STE this module
+//! does not configure is an abort STE.
 
 use crate::mem::frame_allocator::PhysAddr;
 use crate::mem::pagetable::{FrameSource, MapFlags, PageTableBuilder, PageTableError, TableMemory};
 
 pub const STE_BYTES: usize = 64;
 pub const CD_BYTES: usize = 64;
+pub const COMMAND_BYTES: usize = 16;
+pub const EVENT_BYTES: usize = 32;
 pub const CR0: u32 = 0x20;
 pub const CR0ACK: u32 = 0x24;
 pub const CR1: u32 = 0x28;
@@ -16,27 +28,77 @@ pub const IDR2: u32 = 0x08;
 pub const IDR3: u32 = 0x0c;
 pub const IDR4: u32 = 0x10;
 pub const IDR5: u32 = 0x14;
+pub const GBPA: u32 = 0x44;
 pub const STRTAB_BASE: u32 = 0x80;
 pub const STRTAB_BASE_CFG: u32 = 0x88;
 pub const CMDQ_BASE: u32 = 0x90;
 pub const CMDQ_PROD: u32 = 0x98;
 pub const CMDQ_CONS: u32 = 0x9c;
 pub const EVENTQ_BASE: u32 = 0xa0;
-pub const EVENTQ_PROD: u32 = 0xa8;
-pub const EVENTQ_CONS: u32 = 0xac;
-pub const GBPA: u32 = 0x44;
+/// The event queue indexes live in register page 1 (base + 64 KiB).
+pub const EVENTQ_PROD: u32 = 0x1_00a8;
+pub const EVENTQ_CONS: u32 = 0x1_00ac;
+
+pub const IDR0_S1P: u32 = 1 << 1;
 pub const IDR1_SIDSIZE_MASK: u32 = 0x3f;
+const IDR1_EVENTQS_SHIFT: u32 = 16;
+const IDR1_CMDQS_SHIFT: u32 = 21;
+const IDR1_QS_MASK: u32 = 0x1f;
+
+/// GBPA.ABORT: with SMMUEN clear, abort every incoming transaction.
+pub const GBPA_ABORT: u32 = 1 << 20;
+/// GBPA.UPDATE: set by software to request an update, cleared by the SMMU
+/// once the new GBPA value is in effect.
+pub const GBPA_UPDATE: u32 = 1 << 31;
+
+pub const CR0_SMMUEN: u32 = 1 << 0;
+pub const CR0_EVENTQEN: u32 = 1 << 2;
+pub const CR0_CMDQEN: u32 = 1 << 3;
+const CR0_ACK_MASK: u32 = 0x0f;
+
+/// CMDQ_CONS.ERR: non-zero when the SMMU stopped on a bad command.
+const CMDQ_CONS_ERR_MASK: u32 = 0x7f << 24;
+/// EVENTQ_PROD.OVFLG and EVENTQ_CONS.OVACKFLG.
+const EVENTQ_OVERFLOW: u32 = 1 << 31;
 
+/// Default poll bound for every SMMU handshake.
+pub const DEFAULT_SPINS: usize = 1_000_000;
+
+/// Platform seam for one SMMUv3 instance: 32-bit register access plus the
+/// cache maintenance for memory the SMMU reads or writes.
 pub trait Registers {
     fn read(&mut self, offset: u32) -> u32;
     fn write(&mut self, offset: u32, value: u32);
+
+    /// Write a 64-bit register as two 32-bit halves, low half first.
+    fn write64(&mut self, offset: u32, value: u64) {
+        self.write(offset, value as u32);
+        self.write(offset + 4, (value >> 32) as u32);
+    }
+
+    /// Make CPU writes to `[address, address + bytes)` visible to the SMMU
+    /// before the next register write. There is no default: an implementor
+    /// that forgets this on a non-coherent system would hand the SMMU stale
+    /// tables.
+    fn clean_dma(&mut self, address: usize, bytes: usize);
+
+    /// Drop CPU cache lines over `[address, address + bytes)` so the next CPU
+    /// read sees what the SMMU wrote.
+    fn invalidate_dma(&mut self, address: usize, bytes: usize);
 }
 
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub enum Error {
+    /// A poll ran out of spins.
     Timeout,
+    /// CMDQ_CONS.ERR reported a command error.
     CommandQueue,
+    /// A table, queue, stream id or window failed validation.
     InvalidWindow,
+    /// The SMMU lacks a feature this bring-up needs (IDR checks).
+    Unsupported,
+    /// GBPA did not read back with ABORT set after the update completed.
+    AbortNotLatched,
     PageTable(PageTableError),
 }
 
@@ -44,12 +106,11 @@ pub enum Error {
 pub struct Ste(pub [u64; 8]);
 
 impl Ste {
+    /// V = 1, Config = 0b000: abort every transaction from the stream.
+    /// There is deliberately no bypass constructor.
     pub const fn abort() -> Self {
         Self([1, 0, 0, 0, 0, 0, 0, 0])
     }
-    pub const fn bypass() -> Self {
-        Self([1 | (0b100 << 1), 0, 0, 0, 0, 0, 0, 0])
-    }
     /// Stage-1 translate, stage-2 bypass. STE word 0 holds V (bit 0),
     /// Config (bits 3:1, 0b101 = S1 translate / S2 bypass), S1Fmt (bits 5:4,
     /// 0 = linear, one CD) and S1ContextPtr (bits 51:6, 64-byte aligned).
@@ -88,8 +149,8 @@ impl ContextDescriptor {
             | (1 << 31) // V: descriptor valid
             | (0b101 << 32) // IPS: 5 (48-bit)
             | (1 << 41) // AA64
-            | (1 << 45) // R: record faults
-            | (1 << 46) // A: access flag
+            | (1 << 45) // R: record faults as events
+            | (1 << 46) // A: abort faulting transactions (not RAZ/WI)
             | (u64::from(asid) << 48);
         // CD word 1 is the 4 KiB-aligned TTBR0 (48-bit physical address).
         let word1 = ttb0 & 0x0000_ffff_ffff_fff0;
@@ -116,16 +177,28 @@ pub const fn command(opcode: u8, sid: u32, leaf: bool) -> [u64; 2] {
     [word0, word1]
 }
 
-/// Queue index encoding used by SMMUv3: low bits index, bit 31 wrap.
+/// SMMUv3 queue index: for a queue of 2^n entries the register holds the
+/// index in bits n-1:0 and the wrap flag in bit n.
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub struct QueueCursor {
     pub index: u32,
     pub wrap: bool,
 }
+
 impl QueueCursor {
-    pub fn encode(self) -> u32 {
-        (self.index & 0x7fff_ffff) | ((self.wrap as u32) << 31)
+    /// `entries` must be a power of two.
+    pub fn encode(self, entries: u32) -> u32 {
+        (self.index & (entries - 1)) | ((self.wrap as u32) << entries.trailing_zeros())
+    }
+
+    /// `entries` must be a power of two.
+    pub fn decode(value: u32, entries: u32) -> Self {
+        Self {
+            index: value & (entries - 1),
+            wrap: value & entries != 0,
+        }
     }
+
     pub fn advance(&mut self, entries: u32) {
         self.index += 1;
         if self.index == entries {
@@ -135,61 +208,18 @@ impl QueueCursor {
     }
 }
 
-pub fn submit_command<R: Registers>(
-    regs: &mut R,
-    cursor: &mut QueueCursor,
-    entries: u32,
-    command: [u64; 2],
-    write_entry: impl FnOnce(u32, [u64; 2]),
-    spins: usize,
-) -> Result<(), Error> {
-    write_entry(cursor.index, command);
-    cursor.advance(entries);
-    regs.write(CMDQ_PROD, cursor.encode());
-    for _ in 0..spins {
-        let cons = regs.read(CMDQ_CONS);
-        if cons & 0x7f00_0000 != 0 {
-            return Err(Error::CommandQueue);
-        }
-        if cons & 0x7fff_ffff == cursor.index && (cons >> 31 != 0) == cursor.wrap {
-            return Ok(());
-        }
-    }
-    Err(Error::Timeout)
-}
-
-/// Keep global abort enabled until command queues and translation state are ready.
-pub fn enable<R: Registers>(regs: &mut R, spins: usize) -> Result<(), Error> {
-    let gbpa = regs.read(GBPA);
-    // GBPA.ABORT is bit 20; bit 31 commits the requested global-bypass update.
-    regs.write(GBPA, (gbpa & !(1 << 20)) | (1 << 31));
-    regs.write(CR0, 0);
-    wait_cr0(regs, 0, spins)?;
-    regs.write(CR0, 1);
-    wait_cr0(regs, 1, spins)
-}
-
-/// Register mapping for an identity-mapped SMMUv3 register aperture.
+/// Register mapping for an identity-mapped SMMUv3 register aperture
+/// (both 64 KiB register pages).
 pub struct MmioRegisters {
     base: usize,
 }
 
 impl MmioRegisters {
     /// # Safety
-    /// `base` must address a mapped SMMUv3 register aperture.
+    /// `base` must address a mapped SMMUv3 register aperture of 128 KiB.
     pub const unsafe fn new(base: usize) -> Self {
         Self { base }
     }
-
-    pub fn write64(&mut self, offset: u32, value: u64) {
-        unsafe {
-            core::ptr::write_volatile((self.base + offset as usize) as *mut u32, value as u32);
-            core::ptr::write_volatile(
-                (self.base + offset as usize + 4) as *mut u32,
-                (value >> 32) as u32,
-            );
-        }
-    }
 }
 
 impl Registers for MmioRegisters {
@@ -200,149 +230,483 @@ impl Registers for MmioRegisters {
     fn write(&mut self, offset: u32, value: u32) {
         unsafe { core::ptr::write_volatile((self.base + offset as usize) as *mut u32, value) }
     }
+
+    fn clean_dma(&mut self, address: usize, bytes: usize) {
+        // Ends with DSB, which also orders the clean before the next MMIO write.
+        crate::arch::aarch64::clean_dcache_range(address, bytes);
+    }
+
+    fn invalidate_dma(&mut self, address: usize, bytes: usize) {
+        crate::arch::aarch64::clean_invalidate_dcache_range(address, bytes);
+    }
+}
+
+/// The memory one SMMU reads and writes in linear stream table mode: the
+/// stream table, the command queue, the event queue and one context
+/// descriptor. Addresses are identity mapped (virtual == physical).
+#[derive(Debug)]
+pub struct LinearTables {
+    stream_table: *mut [u64; 8],
+    stream_entries: u32,
+    command_queue: *mut [u64; 2],
+    command_entries: u32,
+    event_queue: *mut [u64; 4],
+    event_entries: u32,
+    context: *mut [u64; 8],
+}
+
+fn aligned(address: usize, bytes: usize) -> bool {
+    address != 0 && address & (bytes.max(32) - 1) == 0
+}
+
+impl LinearTables {
+    /// Validate the table geometry: every entry count is a power of two, each
+    /// queue has at least two entries, and every base is aligned to its own
+    /// size (the SMMU ignores low address bits below the size, so a
+    /// misaligned queue would overlap its neighbour).
+    ///
+    /// # Safety
+    /// Each pointer must address live, physically contiguous, identity
+    /// mapped RAM visible to the SMMU with room for the stated number of
+    /// entries, and nothing else may use that memory while this value (or
+    /// the SMMU programmed from it) is in use.
+    pub unsafe fn new(
+        stream_table: *mut [u64; 8],
+        stream_entries: u32,
+        command_queue: *mut [u64; 2],
+        command_entries: u32,
+        event_queue: *mut [u64; 4],
+        event_entries: u32,
+        context: *mut [u64; 8],
+    ) -> Result<Self, Error> {
+        let pow2 = |n: u32, min: u32| n >= min && n.is_power_of_two();
+        if !pow2(stream_entries, 1)
+            || !pow2(command_entries, 2)
+            || !pow2(event_entries, 2)
+            || !aligned(stream_table as usize, stream_entries as usize * STE_BYTES)
+            || !aligned(
+                command_queue as usize,
+                command_entries as usize * COMMAND_BYTES,
+            )
+            || !aligned(event_queue as usize, event_entries as usize * EVENT_BYTES)
+            || !aligned(context as usize, CD_BYTES)
+        {
+            return Err(Error::InvalidWindow);
+        }
+        Ok(Self {
+            stream_table,
+            stream_entries,
+            command_queue,
+            command_entries,
+            event_queue,
+            event_entries,
+            context,
+        })
+    }
+
+    pub fn stream_entries(&self) -> u32 {
+        self.stream_entries
+    }
+
+    pub fn context_address(&self) -> u64 {
+        self.context as u64
+    }
+
+    fn write_ste_word(&self, sid: u32, word: usize, value: u64) {
+        // Safety: `new` established that the table holds `stream_entries`
+        // STEs; callers check `sid` first. A 64-bit aligned store is single
+        // copy atomic, so the SMMU never sees a torn word 0.
+        unsafe {
+            core::ptr::write_volatile(
+                (self.stream_table.add(sid as usize) as *mut u64).add(word),
+                value,
+            )
+        }
+    }
+
+    fn ste_address(&self, sid: u32) -> usize {
+        self.stream_table as usize + sid as usize * STE_BYTES
+    }
 }
 
-fn submit_raw<R: Registers>(
+/// Wait for any GBPA update in flight, then request `value` and wait for the
+/// SMMU to clear GBPA.UPDATE.
+fn update_gbpa<R: Registers>(regs: &mut R, value: u32, spins: usize) -> Result<u32, Error> {
+    let mut current = poll_gbpa_idle(regs, spins)?;
+    current = (current & !GBPA_UPDATE) | value;
+    regs.write(GBPA, current | GBPA_UPDATE);
+    poll_gbpa_idle(regs, spins)
+}
+
+fn poll_gbpa_idle<R: Registers>(regs: &mut R, spins: usize) -> Result<u32, Error> {
+    for _ in 0..spins {
+        let gbpa = regs.read(GBPA);
+        if gbpa & GBPA_UPDATE == 0 {
+            return Ok(gbpa);
+        }
+    }
+    Err(Error::Timeout)
+}
+
+/// Set GBPA.ABORT so that whenever SMMUEN is clear every transaction aborts.
+pub fn set_global_abort<R: Registers>(regs: &mut R, spins: usize) -> Result<(), Error> {
+    let gbpa = update_gbpa(regs, GBPA_ABORT, spins)?;
+    if gbpa & GBPA_ABORT == 0 {
+        return Err(Error::AbortNotLatched);
+    }
+    Ok(())
+}
+
+fn wait_cr0<R: Registers>(regs: &mut R, expected: u32, spins: usize) -> Result<(), Error> {
+    for _ in 0..spins {
+        // CR0ACK mirrors the enabled queue and SMMU bits from CR0.
+        if regs.read(CR0ACK) & CR0_ACK_MASK == expected & CR0_ACK_MASK {
+            return Ok(());
+        }
+    }
+    Err(Error::Timeout)
+}
+
+fn cmdq_cons<R: Registers>(regs: &mut R, entries: u32) -> Result<QueueCursor, Error> {
+    let cons = regs.read(CMDQ_CONS);
+    if cons & CMDQ_CONS_ERR_MASK != 0 {
+        return Err(Error::CommandQueue);
+    }
+    Ok(QueueCursor::decode(cons, entries))
+}
+
+/// Append `commands` to the command queue and wait until the SMMU has
+/// consumed all of them. Each poll is bounded by `spins`; a stuck queue
+/// returns `Error::Timeout` and a command error returns
+/// `Error::CommandQueue`. End the batch with `CMD_SYNC` when the caller
+/// needs every earlier command to have taken effect.
+pub fn submit_commands<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    commands: &[[u64; 2]],
+    spins: usize,
+) -> Result<(), Error> {
+    let entries = tables.command_entries;
+    let mut prod = QueueCursor::decode(regs.read(CMDQ_PROD), entries);
+    for &words in commands {
+        // Wait for a free slot: the queue is full when the indexes match and
+        // the wrap flags differ.
+        let mut has_space = false;
+        for _ in 0..spins {
+            let cons = cmdq_cons(regs, entries)?;
+            if !(cons.index == prod.index && cons.wrap != prod.wrap) {
+                has_space = true;
+                break;
+            }
+        }
+        if !has_space {
+            return Err(Error::Timeout);
+        }
+        // Safety: `new` established that the queue holds `entries` slots and
+        // `prod.index < entries`.
+        let slot = unsafe { tables.command_queue.add(prod.index as usize) };
+        unsafe { core::ptr::write_volatile(slot, words) };
+        regs.clean_dma(slot as usize, COMMAND_BYTES);
+        prod.advance(entries);
+        regs.write(CMDQ_PROD, prod.encode(entries));
+    }
+    for _ in 0..spins {
+        if cmdq_cons(regs, entries)? == prod {
+            return Ok(());
+        }
+    }
+    Err(Error::Timeout)
+}
+
+/// Point stream `sid` at `ste` and make the SMMU forget any cached copy.
+///
+/// The old entry is first replaced by an abort STE (one atomic store of word
+/// 0) and invalidated, so the SMMU never sees a half-written entry: the new
+/// words 1..7 are written behind that abort, then word 0 last. Finally
+/// `CMD_CFGI_STE(sid)`, `CMD_TLBI_NSNH_ALL` and `CMD_SYNC` are issued and
+/// waited for.
+pub fn install_ste<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    sid: u32,
+    ste: Ste,
+    spins: usize,
+) -> Result<(), Error> {
+    if sid >= tables.stream_entries {
+        return Err(Error::InvalidWindow);
+    }
+    abort_ste(regs, tables, sid, spins)?;
+    for (word, value) in ste.0.iter().enumerate().skip(1) {
+        tables.write_ste_word(sid, word, *value);
+    }
+    // Clean (and, through its DSB, order) words 1..7 before word 0 makes the
+    // entry live, so a coherent SMMU cannot fetch the new word 0 with stale
+    // words behind it.
+    regs.clean_dma(tables.ste_address(sid), STE_BYTES);
+    tables.write_ste_word(sid, 0, ste.0[0]);
+    invalidate_ste(regs, tables, sid, spins)
+}
+
+/// Return stream `sid` to abort: write an abort STE, then issue
+/// `CMD_CFGI_STE(sid)`, `CMD_TLBI_NSNH_ALL` and `CMD_SYNC` and wait for them.
+/// On `Ok` no further DMA from `sid` can translate.
+pub fn abort_ste<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    sid: u32,
+    spins: usize,
+) -> Result<(), Error> {
+    if sid >= tables.stream_entries {
+        return Err(Error::InvalidWindow);
+    }
+    let abort = Ste::abort();
+    // Word 0 first: once V=1 and Config=abort, the other words are ignored.
+    tables.write_ste_word(sid, 0, abort.0[0]);
+    for (word, value) in abort.0.iter().enumerate().skip(1) {
+        tables.write_ste_word(sid, word, *value);
+    }
+    invalidate_ste(regs, tables, sid, spins)
+}
+
+fn invalidate_ste<R: Registers>(
     regs: &mut R,
-    cursor: &mut QueueCursor,
-    entries: u32,
-    queue: *mut [u64; 2],
-    cmd: [u64; 2],
+    tables: &LinearTables,
+    sid: u32,
+    spins: usize,
 ) -> Result<(), Error> {
-    submit_command(
+    regs.clean_dma(tables.ste_address(sid), STE_BYTES);
+    submit_commands(
         regs,
-        cursor,
-        entries,
-        cmd,
-        |index, words| unsafe { core::ptr::write_volatile(queue.add(index as usize), words) },
-        1_000_000,
+        tables,
+        &[
+            command(CMD_CFGI_STE, sid, true),
+            command(CMD_TLBI_NSNH_ALL, 0, false),
+            command(CMD_SYNC, 0, false),
+        ],
+        spins,
     )
 }
 
-/// Configure one DMA stream to translate only the supplied stream table's PTEs.
-/// The linear stream table starts with every stream in abort mode.
+pub const EVENT_F_UUT: u8 = 0x01;
+pub const EVENT_C_BAD_STREAMID: u8 = 0x02;
+pub const EVENT_F_STE_FETCH: u8 = 0x03;
+pub const EVENT_C_BAD_STE: u8 = 0x04;
+pub const EVENT_F_STREAM_DISABLED: u8 = 0x06;
+pub const EVENT_F_TRANSL_FORBIDDEN: u8 = 0x07;
+pub const EVENT_F_CD_FETCH: u8 = 0x09;
+pub const EVENT_C_BAD_CD: u8 = 0x0a;
+pub const EVENT_F_WALK_EABT: u8 = 0x0b;
+pub const EVENT_F_TRANSLATION: u8 = 0x10;
+pub const EVENT_F_ADDR_SIZE: u8 = 0x11;
+pub const EVENT_F_ACCESS: u8 = 0x12;
+pub const EVENT_F_PERMISSION: u8 = 0x13;
+
+/// One decoded 32-byte event queue record.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct EventRecord {
+    /// Word 0 bits 7:0 (see the `EVENT_*` constants).
+    pub event_type: u8,
+    /// Word 0 bits 63:32.
+    pub stream_id: u32,
+    /// Word 2: the faulting input address for translation-class events
+    /// (`EVENT_F_TRANSLATION` through `EVENT_F_PERMISSION`, and walk faults).
+    pub input_address: u64,
+    pub raw: [u64; 4],
+}
+
+impl EventRecord {
+    pub fn decode(raw: [u64; 4]) -> Self {
+        Self {
+            event_type: raw[0] as u8,
+            stream_id: (raw[0] >> 32) as u32,
+            input_address: raw[2],
+            raw,
+        }
+    }
+}
+
+/// Result of one [`read_events`] call.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct EventDrain {
+    /// Records written to the front of the output slice.
+    pub count: usize,
+    /// The SMMU reported an event queue overflow since the last
+    /// acknowledgement (some events were lost). It is acknowledged here.
+    pub overflowed: bool,
+}
+
+/// Consume event records between EVENTQ_CONS and EVENTQ_PROD, oldest first,
+/// up to `out.len()`, then publish the new EVENTQ_CONS. Records left over
+/// stay queued for the next call.
+pub fn read_events<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    out: &mut [EventRecord],
+) -> EventDrain {
+    let entries = tables.event_entries;
+    let prod_raw = regs.read(EVENTQ_PROD);
+    let cons_raw = regs.read(EVENTQ_CONS);
+    let prod = QueueCursor::decode(prod_raw, entries);
+    let mut cons = QueueCursor::decode(cons_raw, entries);
+    let overflow_flag = prod_raw & EVENTQ_OVERFLOW;
+    let mut count = 0;
+    while cons != prod && count < out.len() {
+        // Safety: `new` established that the queue holds `entries` records
+        // and `cons.index < entries`.
+        let slot = unsafe { tables.event_queue.add(cons.index as usize) };
+        regs.invalidate_dma(slot as usize, EVENT_BYTES);
+        let raw = unsafe { core::ptr::read_volatile(slot) };
+        out[count] = EventRecord::decode(raw);
+        count += 1;
+        cons.advance(entries);
+    }
+    // Copying OVFLG into OVACKFLG acknowledges an overflow.
+    regs.write(EVENTQ_CONS, cons.encode(entries) | overflow_flag);
+    EventDrain {
+        count,
+        overflowed: overflow_flag != cons_raw & EVENTQ_OVERFLOW,
+    }
+}
+
+/// Bring the SMMU up with every stream in abort except `stream_id`, which
+/// translates through `cd` (stage 1 only).
 ///
-/// # Safety
-/// All descriptor and queue pointers must address live, aligned, physically
-/// contiguous RAM visible to the SMMU. `base` must be mapped device memory.
-#[allow(clippy::too_many_arguments)]
-pub unsafe fn configure_linear_stream(
-    regs: &mut MmioRegisters,
+/// Order, fail closed at every step:
+/// 1. Set GBPA.ABORT and wait for the update. From here on a disabled SMMU
+///    aborts all DMA. GBPA.ABORT is never cleared.
+/// 2. Check the stream id and that IDR0/IDR1 support the geometry.
+/// 3. Write the tables (all abort STEs, the CD, then the one live STE) and
+///    clean them to the SMMU.
+/// 4. Disable the SMMU, program queues and the stream table, enable the
+///    queues, invalidate all cached config and TLBs, then set SMMUEN and wait
+///    for CR0ACK.
+///
+/// If step 1 fails the error is returned without touching CR0 (GBPA may
+/// not have latched, so the caller must treat the SMMU as unusable). Any
+/// later error writes CR0 = 0, which leaves the SMMU disabled behind
+/// GBPA.ABORT (and so aborting every stream), and returns the error.
+pub fn configure_linear_stream<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
     stream_id: u32,
-    stream_entries: u32,
-    stream_table: *mut [u64; 8],
-    command_entries: u32,
-    command_queue: *mut [u64; 2],
-    event_entries: u32,
-    event_queue: *mut [u64; 4],
-    context: *mut [u64; 8],
-    translation_root: u64,
+    cd: &ContextDescriptor,
+    spins: usize,
 ) -> Result<(), Error> {
-    if stream_entries == 0
-        || !stream_entries.is_power_of_two()
-        || stream_id >= stream_entries
-        || command_entries < 2
-        || !command_entries.is_power_of_two()
-        || event_entries < 2
-        || !event_entries.is_power_of_two()
-        || stream_table as usize & (stream_entries as usize * STE_BYTES - 1) != 0
-        || command_queue as usize & 0x3f != 0
-        || event_queue as usize & 0x3f != 0
-        || context as usize & 0x3f != 0
-        || translation_root & 0xfff != 0
-    {
-        return Err(Error::InvalidWindow);
+    set_global_abort(regs, spins)?;
+    let result = check_and_program(regs, tables, stream_id, cd, spins);
+    if result.is_err() {
+        // Disable translation so that GBPA.ABORT governs every stream. The
+        // acknowledgement wait is best effort: the original error is the
+        // one reported, and ABORT stays set either way.
+        regs.write(CR0, 0);
+        let _ = wait_cr0(regs, 0, spins);
     }
-    let sid_bits = stream_entries.trailing_zeros();
-    if regs.read(IDR1) & IDR1_SIDSIZE_MASK < sid_bits {
+    result
+}
+
+fn check_and_program<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    stream_id: u32,
+    cd: &ContextDescriptor,
+    spins: usize,
+) -> Result<(), Error> {
+    if stream_id >= tables.stream_entries {
         return Err(Error::InvalidWindow);
     }
-    let table = unsafe { core::slice::from_raw_parts_mut(stream_table, stream_entries as usize) };
-    for entry in table.iter_mut() {
-        unsafe { core::ptr::write(entry, Ste::abort().0) };
+    let sid_bits = tables.stream_entries.trailing_zeros();
+    if regs.read(IDR0) & IDR0_S1P == 0 {
+        return Err(Error::Unsupported);
     }
-    unsafe {
-        core::ptr::write(
-            context,
-            ContextDescriptor::stage1(translation_root, 1, 0x00ff, 16)?.0,
-        );
-        core::ptr::write(
-            stream_table.add(stream_id as usize),
-            Ste::stage1(context as u64).0,
-        );
+    let idr1 = regs.read(IDR1);
+    if idr1 & IDR1_SIDSIZE_MASK < sid_bits
+        || (idr1 >> IDR1_CMDQS_SHIFT) & IDR1_QS_MASK < tables.command_entries.trailing_zeros()
+        || (idr1 >> IDR1_EVENTQS_SHIFT) & IDR1_QS_MASK < tables.event_entries.trailing_zeros()
+    {
+        return Err(Error::Unsupported);
     }
+    program_linear_stream(regs, tables, stream_id, cd, sid_bits, spins)
+}
 
-    let gbpa = regs.read(GBPA);
-    regs.write(GBPA, gbpa | (1 << 20) | (1 << 31));
-    for _ in 0..1_000_000 {
-        if regs.read(GBPA) & (1 << 31) == 0 {
-            break;
+fn program_linear_stream<R: Registers>(
+    regs: &mut R,
+    tables: &LinearTables,
+    stream_id: u32,
+    cd: &ContextDescriptor,
+    sid_bits: u32,
+    spins: usize,
+) -> Result<(), Error> {
+    for sid in 0..tables.stream_entries {
+        for (word, value) in Ste::abort().0.iter().enumerate() {
+            tables.write_ste_word(sid, word, *value);
+        }
+    }
+    // Safety: `LinearTables::new` established the CD and queue geometry.
+    unsafe {
+        core::ptr::write_volatile(tables.context, cd.0);
+        for i in 0..tables.command_entries as usize {
+            core::ptr::write_volatile(tables.command_queue.add(i), [0; 2]);
+        }
+        for i in 0..tables.event_entries as usize {
+            core::ptr::write_volatile(tables.event_queue.add(i), [0; 4]);
         }
     }
+    let ste = Ste::stage1(tables.context_address());
+    for (word, value) in ste.0.iter().enumerate().skip(1) {
+        tables.write_ste_word(stream_id, word, *value);
+    }
+    tables.write_ste_word(stream_id, 0, ste.0[0]);
+
+    // Everything the SMMU will fetch is written; clean it before any
+    // register points the SMMU at it.
+    regs.clean_dma(
+        tables.stream_table as usize,
+        tables.stream_entries as usize * STE_BYTES,
+    );
+    regs.clean_dma(tables.context as usize, CD_BYTES);
+    regs.clean_dma(
+        tables.command_queue as usize,
+        tables.command_entries as usize * COMMAND_BYTES,
+    );
+    // Clean and invalidate: no dirty CPU line may later overwrite an event.
+    regs.invalidate_dma(
+        tables.event_queue as usize,
+        tables.event_entries as usize * EVENT_BYTES,
+    );
+
     regs.write(CR0, 0);
-    wait_cr0(regs, 0, 1_000_000)?;
+    wait_cr0(regs, 0, spins)?;
     regs.write(CR1, 0x0d75);
     regs.write64(
         CMDQ_BASE,
-        command_queue as u64 | u64::from(command_entries.trailing_zeros()),
+        tables.command_queue as u64 | u64::from(tables.command_entries.trailing_zeros()),
     );
     regs.write(CMDQ_CONS, 0);
     regs.write(CMDQ_PROD, 0);
     regs.write64(
         EVENTQ_BASE,
-        event_queue as u64 | u64::from(event_entries.trailing_zeros()),
+        tables.event_queue as u64 | u64::from(tables.event_entries.trailing_zeros()),
     );
     regs.write(EVENTQ_CONS, 0);
     regs.write(EVENTQ_PROD, 0);
     regs.write(STRTAB_BASE_CFG, sid_bits);
-    regs.write64(STRTAB_BASE, stream_table as u64);
-    regs.write(CR0, 0x0c); // CMDQEN | EVENTQEN; SMMUEN remains clear.
-    wait_cr0(regs, 0x0c, 1_000_000)?;
+    regs.write64(STRTAB_BASE, tables.stream_table as u64);
+    regs.write(CR0, CR0_CMDQEN | CR0_EVENTQEN);
+    wait_cr0(regs, CR0_CMDQEN | CR0_EVENTQEN, spins)?;
 
-    let mut cursor = QueueCursor {
-        index: 0,
-        wrap: false,
-    };
-    submit_raw(
+    submit_commands(
         regs,
-        &mut cursor,
-        command_entries,
-        command_queue,
-        command(CMD_CFGI_STE, stream_id, true),
+        tables,
+        &[
+            command(CMD_CFGI_ALL, 0, false),
+            command(CMD_TLBI_NSNH_ALL, 0, false),
+            command(CMD_SYNC, 0, false),
+        ],
+        spins,
     )?;
-    submit_raw(
-        regs,
-        &mut cursor,
-        command_entries,
-        command_queue,
-        command(CMD_TLBI_NSNH_ALL, 0, false),
-    )?;
-    submit_raw(
-        regs,
-        &mut cursor,
-        command_entries,
-        command_queue,
-        command(CMD_SYNC, 0, false),
-    )?;
-    let gbpa = regs.read(GBPA);
-    regs.write(GBPA, (gbpa & !(1 << 20)) | (1 << 31));
-    for _ in 0..1_000_000 {
-        if regs.read(GBPA) & (1 << 31) == 0 {
-            break;
-        }
-    }
-    regs.write(CR0, 0x0d); // SMMUEN | CMDQEN | EVENTQEN
-    wait_cr0(regs, 0x0d, 1_000_000)
-}
-
-fn wait_cr0<R: Registers>(regs: &mut R, expected: u32, spins: usize) -> Result<(), Error> {
-    for _ in 0..spins {
-        // CR0ACK mirrors the enabled queue and SMMU bits from CR0.
-        if regs.read(CR0ACK) & 0x0f == expected & 0x0f {
-            return Ok(());
-        }
-    }
-    Err(Error::Timeout)
+    let enable = CR0_SMMUEN | CR0_CMDQEN | CR0_EVENTQEN;
+    regs.write(CR0, enable);
+    wait_cr0(regs, enable, spins)
 }
 
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -352,25 +716,24 @@ pub struct DmaWindow {
     pub length: usize,
 }
 
+/// The stage-1 translation for one stream: a page table that maps only the
+/// allowed windows and the context descriptor that points at it.
 pub struct DmaPolicy<F, M> {
     pub stream_id: u32,
-    pub ste: Ste,
     pub cd: ContextDescriptor,
     pub page_table: PageTableBuilder<F, M>,
 }
 
 /// Build an identity-policy stage-1 table: only the supplied windows translate.
+/// Hand `policy.cd` to [`configure_linear_stream`] after cleaning the page
+/// table frames to the SMMU.
 pub fn build_dma_policy<F: FrameSource, M: TableMemory>(
     stream_id: u32,
-    cd_address: u64,
     asid: u16,
     windows: &[DmaWindow],
     frames: F,
     memory: M,
 ) -> Result<DmaPolicy<F, M>, Error> {
-    if cd_address & (CD_BYTES as u64 - 1) != 0 {
-        return Err(Error::InvalidWindow);
-    }
     let mut table = PageTableBuilder::new(frames, memory).map_err(Error::PageTable)?;
     for window in windows {
         if window.iova != window.pa.0 {
@@ -383,7 +746,6 @@ pub fn build_dma_policy<F: FrameSource, M: TableMemory>(
     let cd = ContextDescriptor::stage1(table.root().0 as u64, asid, 0x00ff, 16)?;
     Ok(DmaPolicy {
         stream_id,
-        ste: Ste::stage1(cd_address),
         cd,
         page_table: table,
     })
@@ -392,29 +754,162 @@ pub fn build_dma_policy<F: FrameSource, M: TableMemory>(
 #[cfg(test)]
 mod tests {
     use super::*;
-    use std::{cell::RefCell, collections::BTreeMap, vec::Vec};
+    use std::{boxed::Box, cell::RefCell, collections::BTreeMap, vec::Vec};
+
+    const SIDS: u32 = 16;
+    const QUEUE: u32 = 16;
+
+    #[repr(C, align(1024))]
+    struct TestTables {
+        stream: [[u64; 8]; SIDS as usize],
+        events: [[u64; 4]; QUEUE as usize],
+        commands: [[u64; 2]; QUEUE as usize],
+        context: [u64; 8],
+    }
 
-    #[derive(Default)]
+    fn test_tables() -> (Box<TestTables>, LinearTables) {
+        let mut memory = Box::new(TestTables {
+            stream: [[0xdead; 8]; SIDS as usize],
+            events: [[0; 4]; QUEUE as usize],
+            commands: [[0; 2]; QUEUE as usize],
+            context: [0; 8],
+        });
+        let tables = unsafe {
+            LinearTables::new(
+                memory.stream.as_mut_ptr(),
+                SIDS,
+                memory.commands.as_mut_ptr(),
+                QUEUE,
+                memory.events.as_mut_ptr(),
+                QUEUE,
+                &mut memory.context,
+            )
+        }
+        .unwrap();
+        (memory, tables)
+    }
+
+    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+    enum Op {
+        /// Offset, value, and whether GBPA.ABORT was in effect after it.
+        Write(u32, u32, bool),
+        Clean(usize, usize),
+        Invalidate(usize, usize),
+    }
+
+    /// Register model: GBPA.UPDATE clears when the update completes (unless
+    /// `gbpa_stuck`), CR0ACK follows CR0 except for `ack_never` bits, and the
+    /// command queue consumes everything up to CMDQ_PROD (unless
+    /// `cmdq_stuck`), recording the commands it read.
     struct Fake {
         values: BTreeMap<u32, u32>,
-        writes: Vec<(u32, u32)>,
+        log: Vec<Op>,
+        gbpa_stuck: bool,
+        ack_never: u32,
+        cmdq_stuck: bool,
+        cmdq_error: bool,
+        consumed: Vec<[u64; 2]>,
+    }
+
+    impl Fake {
+        fn new() -> Self {
+            let mut values = BTreeMap::new();
+            values.insert(IDR0, IDR0_S1P);
+            values.insert(
+                IDR1,
+                16 | (19 << IDR1_EVENTQS_SHIFT) | (19 << IDR1_CMDQS_SHIFT),
+            );
+            // Reset GBPA: bypass (ABORT clear).
+            values.insert(GBPA, 0x1000);
+            Self {
+                values,
+                log: Vec::new(),
+                gbpa_stuck: false,
+                ack_never: 0,
+                cmdq_stuck: false,
+                cmdq_error: false,
+                consumed: Vec::new(),
+            }
+        }
+        fn get(&self, offset: u32) -> u32 {
+            *self.values.get(&offset).unwrap_or(&0)
+        }
+        fn abort_in_effect(&self) -> bool {
+            let gbpa = self.get(GBPA);
+            gbpa & GBPA_UPDATE == 0 && gbpa & GBPA_ABORT != 0
+        }
+        fn writes(&self) -> Vec<(u32, u32, bool)> {
+            self.log
+                .iter()
+                .filter_map(|op| match *op {
+                    Op::Write(o, v, a) => Some((o, v, a)),
+                    _ => None,
+                })
+                .collect()
+        }
+        fn position(&self, pred: impl Fn(&Op) -> bool) -> Option<usize> {
+            self.log.iter().position(pred)
+        }
+        fn consume_commands(&mut self, prod: u32) {
+            let base = u64::from(self.get(CMDQ_BASE)) | (u64::from(self.get(CMDQ_BASE + 4)) << 32);
+            let entries = 1u32 << (base & 0x1f);
+            let queue = (base & !0x1f) as *const [u64; 2];
+            let mut cons = QueueCursor::decode(self.get(CMDQ_CONS), entries);
+            let prod = QueueCursor::decode(prod, entries);
+            while cons != prod {
+                self.consumed
+                    .push(unsafe { core::ptr::read_volatile(queue.add(cons.index as usize)) });
+                cons.advance(entries);
+            }
+            self.values.insert(CMDQ_CONS, cons.encode(entries));
+        }
     }
+
     impl Registers for Fake {
         fn read(&mut self, offset: u32) -> u32 {
-            *self.values.get(&offset).unwrap_or(&0)
+            self.get(offset)
         }
         fn write(&mut self, offset: u32, value: u32) {
-            self.writes.push((offset, value));
-            self.values.insert(offset, value);
-            if offset == CR0 {
-                self.values.insert(CR0ACK, value);
+            let mut stored = value;
+            if offset == GBPA && !self.gbpa_stuck {
+                stored &= !GBPA_UPDATE;
             }
+            self.values.insert(offset, stored);
+            match offset {
+                CR0 => {
+                    self.values.insert(CR0ACK, value & !self.ack_never);
+                }
+                CMDQ_PROD if self.get(CR0ACK) & CR0_CMDQEN != 0 => {
+                    if self.cmdq_error {
+                        self.values.insert(CMDQ_CONS, 0x01 << 24);
+                    } else if !self.cmdq_stuck {
+                        self.consume_commands(value);
+                    }
+                }
+                _ => {}
+            }
+            let abort = self.abort_in_effect();
+            self.log.push(Op::Write(offset, value, abort));
+        }
+        fn clean_dma(&mut self, address: usize, bytes: usize) {
+            self.log.push(Op::Clean(address, bytes));
+        }
+        fn invalidate_dma(&mut self, address: usize, bytes: usize) {
+            self.log.push(Op::Invalidate(address, bytes));
         }
     }
+
+    fn cd() -> ContextDescriptor {
+        ContextDescriptor::stage1(0x4000, 1, 0x00ff, 16).unwrap()
+    }
+
+    fn smmuen_write(regs: &Fake) -> Option<usize> {
+        regs.position(|op| matches!(op, Op::Write(CR0, v, _) if v & CR0_SMMUEN != 0))
+    }
+
     #[test]
     fn descriptor_layouts() {
         assert_eq!(Ste::abort().0[0], 1);
-        assert_eq!(Ste::bypass().0[0], 9);
         // Review fix: Config 0b101 (S1 translate) and S1ContextPtr in word 0.
         let ste = Ste::stage1(0x1_2345_6780);
         assert_eq!(ste.0[0] & 1, 1, "V");
@@ -448,6 +943,7 @@ mod tests {
         assert_eq!(cd.0[2], 0, "TTBR1 unused (EPD1 set)");
         assert_eq!(cd.0[3], 0xff00, "MAIR");
     }
+
     #[test]
     fn command_words_and_queue_wrap() {
         assert_eq!(
@@ -469,15 +965,376 @@ mod tests {
                 wrap: true
             }
         );
+        // The wrap flag sits just above the index bits, not in bit 31.
+        assert_eq!(c.encode(2), 0b10);
+        let c = QueueCursor {
+            index: 5,
+            wrap: true,
+        };
+        assert_eq!(c.encode(16), 0x15);
+        assert_eq!(QueueCursor::decode(0x15, 16), c);
+        assert!(!QueueCursor::decode(0x8000_0005, 16).wrap);
+    }
+
+    #[test]
+    fn tables_reject_misaligned_or_bad_geometry() {
+        let (mut memory, _) = test_tables();
+        let stream = memory.stream.as_mut_ptr();
+        let commands = memory.commands.as_mut_ptr();
+        let events = memory.events.as_mut_ptr();
+        let context: *mut [u64; 8] = &mut memory.context;
+        let new = |s, se, c, ce, e, ee, cd| unsafe { LinearTables::new(s, se, c, ce, e, ee, cd) };
+        assert!(new(stream, SIDS, commands, QUEUE, events, QUEUE, context).is_ok());
+        assert!(new(stream, 12, commands, QUEUE, events, QUEUE, context).is_err());
+        assert!(new(stream, SIDS, commands, 1, events, QUEUE, context).is_err());
+        // The event queue base must be aligned to its 512-byte size.
+        let shifted = unsafe { (commands as *mut u8).sub(256) }.cast::<[u64; 4]>();
+        assert!(new(stream, SIDS, commands, QUEUE, shifted, QUEUE, context).is_err());
+        let cd = unsafe { (context as *mut u8).add(8) }.cast::<[u64; 8]>();
+        assert!(new(stream, SIDS, commands, QUEUE, events, QUEUE, cd).is_err());
+    }
+
+    #[test]
+    fn bring_up_keeps_global_abort_through_smmuen() {
+        let (memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+
+        // The first register write sets GBPA.ABORT, and ABORT is in effect
+        // after every register write up to and including SMMUEN.
+        let writes = regs.writes();
+        assert_eq!(writes[0].0, GBPA);
+        assert!(writes.iter().all(|&(_, _, abort)| abort), "{writes:x?}");
+        assert!(writes
+            .iter()
+            .filter(|w| w.0 == GBPA)
+            .all(|w| w.1 & GBPA_ABORT != 0));
+        let last = *writes.last().unwrap();
+        assert_eq!((last.0, last.1), (CR0, 0x0d), "SMMUEN is the final write");
+        assert_eq!(regs.get(CR0ACK), 0x0d, "SMMUEN acknowledged");
+        assert!(regs.abort_in_effect(), "GBPA still aborts if SMMUEN drops");
+
+        // Only stream 3 translates, through the CD this call wrote.
+        for (sid, ste) in memory.stream.iter().enumerate() {
+            if sid == 3 {
+                assert_eq!(*ste, Ste::stage1(tables.context_address()).0);
+            } else {
+                assert_eq!(*ste, Ste::abort().0, "sid {sid}");
+            }
+        }
+        assert_eq!(memory.context, cd().0);
+        assert_eq!(
+            regs.consumed,
+            [
+                command(CMD_CFGI_ALL, 0, false),
+                command(CMD_TLBI_NSNH_ALL, 0, false),
+                command(CMD_SYNC, 0, false)
+            ]
+        );
+        assert_eq!(regs.get(STRTAB_BASE_CFG), 4);
+    }
+
+    #[test]
+    fn bring_up_cleans_tables_after_writing_before_programming() {
+        let (memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+        let stream = memory.stream.as_ptr() as usize;
+        let context = &memory.context as *const _ as usize;
+        let commands = memory.commands.as_ptr() as usize;
+        let events = memory.events.as_ptr() as usize;
+        let cleans = [
+            regs.position(|op| *op == Op::Clean(stream, SIDS as usize * STE_BYTES)),
+            regs.position(|op| *op == Op::Clean(context, CD_BYTES)),
+            regs.position(|op| *op == Op::Clean(commands, QUEUE as usize * COMMAND_BYTES)),
+            regs.position(|op| *op == Op::Invalidate(events, QUEUE as usize * EVENT_BYTES)),
+        ];
+        let first_cr0 = regs
+            .position(|op| matches!(op, Op::Write(CR0, _, _)))
+            .unwrap();
+        let first_strtab = regs
+            .position(|op| matches!(op, Op::Write(STRTAB_BASE, _, _)))
+            .unwrap();
+        for clean in cleans {
+            let clean = clean.expect("table region cleaned");
+            assert!(clean < first_cr0 && clean < first_strtab);
+        }
+        // Tables are cleaned after GBPA.ABORT, so the cleans cover the final
+        // contents (this function writes tables only after that point).
+        assert!(regs.position(|op| matches!(op, Op::Write(GBPA, _, _))) < cleans[0]);
+    }
+
+    #[test]
+    fn gbpa_update_timeout_fails_closed() {
+        let (_memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        regs.gbpa_stuck = true;
+        assert_eq!(
+            configure_linear_stream(&mut regs, &tables, 3, &cd(), 4),
+            Err(Error::Timeout)
+        );
+        assert_eq!(regs.get(GBPA) & GBPA_ABORT, GBPA_ABORT, "ABORT requested");
+        assert!(regs.writes().iter().all(|w| w.0 == GBPA), "nothing else");
+    }
+
+    #[test]
+    fn smmuen_ack_failure_fails_closed() {
+        let (_memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        regs.ack_never = CR0_SMMUEN;
+        assert_eq!(
+            configure_linear_stream(&mut regs, &tables, 3, &cd(), 4),
+            Err(Error::Timeout)
+        );
+        assert!(regs.abort_in_effect());
+        let last = *regs.writes().last().unwrap();
+        assert_eq!((last.0, last.1), (CR0, 0), "SMMU left disabled");
+        assert!(regs.writes().iter().all(|&(_, _, abort)| abort));
+    }
+
+    #[test]
+    fn command_timeout_and_error_fail_closed() {
+        for error in [false, true] {
+            let (_memory, tables) = test_tables();
+            let mut regs = Fake::new();
+            regs.cmdq_stuck = !error;
+            regs.cmdq_error = error;
+            let expected = if error {
+                Error::CommandQueue
+            } else {
+                Error::Timeout
+            };
+            assert_eq!(
+                configure_linear_stream(&mut regs, &tables, 3, &cd(), 4),
+                Err(expected)
+            );
+            assert!(smmuen_write(&regs).is_none(), "SMMUEN never requested");
+            assert!(regs.abort_in_effect());
+            assert_eq!(regs.get(CR0), 0);
+        }
+    }
+
+    #[test]
+    #[allow(clippy::type_complexity)]
+    fn unsupported_hardware_or_bad_sid_fails_closed() {
+        let cases: [(Box<dyn Fn(&mut Fake)>, u32, Error); 3] = [
+            (
+                Box::new(|r| {
+                    let _ = r.values.insert(IDR1, 2);
+                }),
+                3,
+                Error::Unsupported,
+            ),
+            (
+                Box::new(|r| {
+                    let _ = r.values.insert(IDR0, 0);
+                }),
+                3,
+                Error::Unsupported,
+            ),
+            (Box::new(|_| {}), SIDS, Error::InvalidWindow),
+        ];
+        for (setup, sid, expected) in cases {
+            let (memory, tables) = test_tables();
+            let mut regs = Fake::new();
+            // Firmware left the SMMU enabled: the error path must disable it
+            // so that GBPA.ABORT governs every stream.
+            regs.write(CR0, CR0_SMMUEN | CR0_CMDQEN);
+            regs.log.clear();
+            setup(&mut regs);
+            assert_eq!(
+                configure_linear_stream(&mut regs, &tables, sid, &cd(), 4),
+                Err(expected)
+            );
+            let writes = regs.writes();
+            assert_eq!(writes[0].0, GBPA, "ABORT is requested first");
+            assert_eq!(*writes.last().unwrap(), (CR0, 0, true), "{writes:x?}");
+            assert!(writes.iter().all(|w| w.0 == GBPA || w.0 == CR0));
+            assert!(regs.abort_in_effect());
+            assert_eq!(regs.get(CR0ACK), 0, "SMMU disabled");
+            assert!(smmuen_write(&regs).is_none());
+            // No table was written.
+            assert!(memory.stream.iter().all(|ste| *ste == [0xdead; 8]));
+        }
+    }
+
+    #[test]
+    fn gbpa_that_will_not_abort_is_an_error() {
+        struct NoAbort(Fake);
+        impl Registers for NoAbort {
+            fn read(&mut self, offset: u32) -> u32 {
+                self.0.read(offset)
+            }
+            fn write(&mut self, offset: u32, value: u32) {
+                let value = if offset == GBPA {
+                    value & !GBPA_ABORT
+                } else {
+                    value
+                };
+                self.0.write(offset, value)
+            }
+            fn clean_dma(&mut self, a: usize, b: usize) {
+                self.0.clean_dma(a, b)
+            }
+            fn invalidate_dma(&mut self, a: usize, b: usize) {
+                self.0.invalidate_dma(a, b)
+            }
+        }
+        let (_memory, tables) = test_tables();
+        let mut regs = NoAbort(Fake::new());
+        assert_eq!(
+            configure_linear_stream(&mut regs, &tables, 3, &cd(), 4),
+            Err(Error::AbortNotLatched)
+        );
+        assert!(regs.0.writes().iter().all(|w| w.0 == GBPA));
+    }
+
+    #[test]
+    fn install_and_abort_ste_invalidate_that_stream() {
+        let (memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+        regs.consumed.clear();
+        regs.log.clear();
+
+        let ste = Ste::stage1(tables.context_address());
+        install_ste(&mut regs, &tables, 7, ste, 4).unwrap();
+        assert_eq!(memory.stream[7], ste.0);
+        let invalidate = [
+            command(CMD_CFGI_STE, 7, true),
+            command(CMD_TLBI_NSNH_ALL, 0, false),
+            command(CMD_SYNC, 0, false),
+        ];
+        // Abort first, then the new entry, each invalidated and synced.
+        assert_eq!(regs.consumed[..3], invalidate);
+        assert_eq!(regs.consumed[3..], invalidate);
+        let ste7 = memory.stream.as_ptr() as usize + 7 * STE_BYTES;
+        let clean = regs
+            .position(|op| *op == Op::Clean(ste7, STE_BYTES))
+            .unwrap();
+        let prod = regs
+            .position(|op| matches!(op, Op::Write(CMDQ_PROD, _, _)))
+            .unwrap();
+        assert!(clean < prod, "STE cleaned before the SMMU is told");
+
+        regs.consumed.clear();
+        abort_ste(&mut regs, &tables, 7, 4).unwrap();
+        assert_eq!(memory.stream[7], Ste::abort().0);
+        assert_eq!(regs.consumed, invalidate);
+
+        assert_eq!(
+            install_ste(&mut regs, &tables, SIDS, ste, 4),
+            Err(Error::InvalidWindow)
+        );
+        assert_eq!(
+            abort_ste(&mut regs, &tables, SIDS, 4),
+            Err(Error::InvalidWindow)
+        );
+    }
+
+    #[test]
+    fn command_queue_wraps_and_times_out() {
+        let (_memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+        // 3 + 11 * 3 = 36 commands: the 16-entry queue wraps twice.
+        for _ in 0..11 {
+            abort_ste(&mut regs, &tables, 5, 4).unwrap();
+        }
+        assert_eq!(regs.consumed.len(), 36);
+        assert_eq!(regs.get(CMDQ_PROD), 36 % 16, "two wraps: flag clear");
+        for _ in 0..4 {
+            abort_ste(&mut regs, &tables, 5, 4).unwrap();
+        }
+        assert_eq!(
+            regs.get(CMDQ_PROD),
+            0x10,
+            "48 commands, three wraps: flag set"
+        );
+
+        regs.cmdq_stuck = true;
+        assert_eq!(abort_ste(&mut regs, &tables, 5, 4), Err(Error::Timeout));
+    }
+
+    #[test]
+    fn submit_refuses_to_overwrite_a_full_queue() {
+        let (_memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+        regs.cmdq_stuck = true;
+        let sync = [command(CMD_SYNC, 0, false); QUEUE as usize + 1];
+        assert_eq!(
+            submit_commands(&mut regs, &tables, &sync, 4),
+            Err(Error::Timeout)
+        );
+        // 16 slots were used from index 3; the 17th would have overwritten
+        // an unconsumed command, so it was never published.
+        let prod = QueueCursor::decode(regs.get(CMDQ_PROD), QUEUE);
+        let cons = QueueCursor::decode(regs.get(CMDQ_CONS), QUEUE);
+        assert_eq!(prod.index, cons.index);
+        assert_ne!(prod.wrap, cons.wrap);
     }
+
+    fn event(kind: u8, sid: u32, address: u64) -> [u64; 4] {
+        [u64::from(kind) | (u64::from(sid) << 32), 0, address, 0]
+    }
+
+    #[test]
+    fn event_reader_decodes_and_consumes_records() {
+        let (mut memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap();
+
+        assert_eq!(
+            read_events(&mut regs, &tables, &mut []),
+            EventDrain::default()
+        );
+        // Records at 14, 15, 0 (wrapped): PROD index 1 with wrap set.
+        memory.events[14] = event(EVENT_F_TRANSLATION, 3, 0x1234_5000);
+        memory.events[15] = event(EVENT_C_BAD_STE, 9, 0);
+        memory.events[0] = event(EVENT_F_PERMISSION, 3, 0xdead_b000);
+        regs.values.insert(EVENTQ_CONS, 14);
+        regs.values.insert(EVENTQ_PROD, 0x10 | 1);
+
+        let mut out = [EventRecord::default(); 2];
+        let drain = read_events(&mut regs, &tables, &mut out);
+        assert_eq!(
+            drain,
+            EventDrain {
+                count: 2,
+                overflowed: false
+            }
+        );
+        assert_eq!(out[0].event_type, EVENT_F_TRANSLATION);
+        assert_eq!(out[0].stream_id, 3);
+        assert_eq!(out[0].input_address, 0x1234_5000);
+        assert_eq!(out[1].event_type, EVENT_C_BAD_STE);
+        assert_eq!(out[1].stream_id, 9);
+        assert_eq!(regs.get(EVENTQ_CONS), 0x10, "index 0, wrapped");
+        let slot14 = memory.events.as_ptr() as usize + 14 * EVENT_BYTES;
+        assert!(regs
+            .position(|op| *op == Op::Invalidate(slot14, EVENT_BYTES))
+            .is_some());
+
+        let drain = read_events(&mut regs, &tables, &mut out);
+        assert_eq!(drain.count, 1);
+        assert_eq!(out[0].event_type, EVENT_F_PERMISSION);
+        assert_eq!(out[0].input_address, 0xdead_b000);
+        assert_eq!(regs.get(EVENTQ_CONS), 0x11);
+        assert_eq!(read_events(&mut regs, &tables, &mut out).count, 0);
+    }
+
     #[test]
-    fn enable_handshake_and_abort_default() {
-        let mut regs = Fake::default();
-        regs.values.insert(GBPA, 0);
-        enable(&mut regs, 2).unwrap();
-        assert_eq!(&regs.writes[..3], &[(GBPA, 1 << 31), (CR0, 0), (CR0, 1)]);
-        assert_eq!(regs.values[&GBPA] & (1 << 20), 0);
+    fn event_reader_acknowledges_overflow() {
+        let (_memory, tables) = test_tables();
+        let mut regs = Fake::new();
+        regs.values.insert(EVENTQ_PROD, EVENTQ_OVERFLOW);
+        let mut out = [EventRecord::default(); 1];
+        assert!(read_events(&mut regs, &tables, &mut out).overflowed);
+        assert_eq!(regs.get(EVENTQ_CONS), EVENTQ_OVERFLOW, "OVACKFLG copied");
+        assert!(!read_events(&mut regs, &tables, &mut out).overflowed);
     }
+
     #[test]
     fn policy_maps_only_allowed_windows() {
         struct Frames(usize);
@@ -502,22 +1359,17 @@ mod tests {
                 true
             }
         }
-        let policy = build_dma_policy(
-            9,
-            0x8000,
-            1,
-            &[DmaWindow {
-                iova: 0x1000,
-                pa: PhysAddr(0x1000),
-                length: 4096,
-            }],
-            Frames(0x100000),
-            Mem::default(),
-        )
-        .unwrap();
+        let window = DmaWindow {
+            iova: 0x1000,
+            pa: PhysAddr(0x1000),
+            length: 4096,
+        };
+        let policy = build_dma_policy(9, 1, &[window], Frames(0x100000), Mem::default()).unwrap();
         assert_eq!(policy.stream_id, 9);
-        assert_eq!(policy.ste, Ste::stage1(0x8000));
-        assert_eq!(policy.cd.0[1], 0x100000);
+        assert_eq!(
+            policy.cd,
+            ContextDescriptor::stage1(0x100000, 1, 0x00ff, 16).unwrap()
+        );
         assert_eq!(
             policy
                 .page_table
@@ -528,5 +1380,13 @@ mod tests {
             PhysAddr(0x1000)
         );
         assert!(policy.page_table.translate(0x2000).unwrap().is_none());
+        let skewed = DmaWindow {
+            iova: 0x2000,
+            ..window
+        };
+        assert!(matches!(
+            build_dma_policy(9, 1, &[skewed], Frames(0x100000), Mem::default()),
+            Err(Error::InvalidWindow)
+        ));
     }
 }
diff --git a/crates/aienos-kernel/src/usb/xhci/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs
index d5da37d2..8c9148d2 100644
--- a/crates/aienos-kernel/src/usb/xhci/mod.rs
+++ b/crates/aienos-kernel/src/usb/xhci/mod.rs
@@ -13,8 +13,7 @@ pub mod trb;
 /// programming interface xHCI (0x30).
 pub const XHCI_CLASS_CODE: u32 = 0x0c_03_30;
 /// PCI command register bits the driver needs: memory decode and DMA.
-pub const PCI_COMMAND_MEMORY: u16 = 1 << 1;
-pub const PCI_COMMAND_BUS_MASTER: u16 = 1 << 2;
+pub use crate::dma_gate::{PCI_COMMAND_BUS_MASTER, PCI_COMMAND_MEMORY};
 
 /// Base of an xHCI controller's register block from its PCI header: the
 /// class/revision dword (offset 0x08) and BAR0/BAR1 (offsets 0x10, 0x14).
diff --git a/scripts/qemu_keyboard_test.sh b/scripts/qemu_keyboard_test.sh
index 24aa12c2..f9750dfb 100755
--- a/scripts/qemu_keyboard_test.sh
+++ b/scripts/qemu_keyboard_test.sh
@@ -25,24 +25,47 @@ expected="abc"
 attempts="${AIENOS_KEYBOARD_ATTEMPTS:-3}"
 boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}"
 machine="virt,virtualization=on,gic-version=3"
-if [[ "${AIENOS_QEMU_SMMU:-0}" == "1" ]]; then
+
+# DMA mode (M3 rule: no SMMU confinement means no DMA).
+#   default                    QEMU SMMUv3 (iommu=smmuv3); the xHCI gets DMA
+#                              only through a translated SMMU stream.
+#   AIENOS_QEMU_SMMU=0         no SMMU, normal build: the keyboard must stay
+#                              unavailable with bus mastering off (fail-closed).
+#   AIENOS_UNSAFE_DMA_BYPASS=1 no SMMU, UNSAFE debug build that lets the xHCI
+#                              DMA to physical memory unconfined. QEMU
+#                              debugging only; never part of verify_all.sh.
+bypass_feature="unsafe-debug-dma-without-smmu"
+if [[ "${AIENOS_UNSAFE_DMA_BYPASS:-0}" == "1" ]]; then
+    mode="unsafe-bypass"
+    default_features="usb-keyboard,${bypass_feature}"
+    target_dir="target/qemu-keyboard-unsafe-dma-bypass"
+    echo "################################################################"
+    echo "WARNING: AIENOS_UNSAFE_DMA_BYPASS=1: building ${bypass_feature}."
+    echo "WARNING: xHCI DMA runs WITHOUT SMMU confinement. QEMU debug only."
+    echo "WARNING: this run proves nothing about DMA isolation."
+    echo "################################################################"
+elif [[ "${AIENOS_QEMU_SMMU:-1}" == "1" ]]; then
+    mode="smmu"
     machine+=",iommu=smmuv3"
+    default_features="usb-keyboard"
+    target_dir="target/qemu-keyboard"
+else
+    mode="fail-closed"
+    default_features="usb-keyboard"
+    target_dir="target/qemu-keyboard"
 fi
-
-# Without an SMMU the keyboard capability is fail-closed, so the identity-DMA
-# path is only reachable behind the debug bypass feature. The confined path is
-# covered by qemu_smmu_test.sh (AIENOS_QEMU_SMMU=1).
-default_features="usb-keyboard"
-if [[ "${AIENOS_QEMU_SMMU:-0}" != "1" ]]; then
-    default_features="usb-keyboard,debug-xhci-without-smmu"
+features="${AIENOS_BUILD_FEATURES:-$default_features}"
+if [[ "${mode}" != "unsafe-bypass" && ",${features}," == *",${bypass_feature},"* ]]; then
+    echo "STOP: ${bypass_feature} requested without AIENOS_UNSAFE_DMA_BYPASS=1"
+    exit 2
 fi
 
 # Own target directory: a keyboard-enabled image never lands where hardware
 # staging or the other tests pick up the handoff image.
 commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
 AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 AIENOS_KEYBOARD_SECS=60 cargo build --quiet --release \
-    -p aienos-boot --target aarch64-unknown-uefi --features "${AIENOS_BUILD_FEATURES:-$default_features}" --bin aienos-handoff \
-    --target-dir target/qemu-keyboard
+    -p aienos-boot --target aarch64-unknown-uefi --features "${features}" --bin aienos-handoff \
+    --target-dir "${target_dir}"
 
 work="$(mktemp -d)"
 qemu_pid=""
@@ -54,7 +77,7 @@ cleanup() {
 trap cleanup EXIT
 mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS"
 touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT"
-cp target/qemu-keyboard/aarch64-unknown-uefi/release/aienos-handoff.efi "${work}/esp/EFI/BOOT/BOOTAA64.EFI"
+cp "${target_dir}/aarch64-unknown-uefi/release/aienos-handoff.efi" "${work}/esp/EFI/BOOT/BOOTAA64.EFI"
 
 serial_has() { tr -d '\r' 2>/dev/null <"${work}/serial.log" | grep -q -- "$1"; }
 qemu_running() { kill -0 "${qemu_pid}" 2>/dev/null; }
@@ -151,21 +174,48 @@ check() { # description, pattern
         failed=1
     fi
 }
-echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), sent lines: abc, help, el, mem, exit"
+check_absent() { # description, pattern
+    if grep -q -- "$2" "${work}/serial.txt"; then
+        echo "FAIL  $1"
+        failed=1
+    else
+        echo "PASS  $1"
+    fi
+}
+echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), dma mode ${mode}, sent lines: abc, help, el, mem, exit"
 check "left firmware and entered the kernel" "kernel: alive"
 check "xHCI controller found before exit" "keyboard: xhci "
-check "keyboard attached by the AIENOS driver" "keyboard: ready"
-if [[ "${AIENOS_QEMU_SMMU:-0}" == "1" ]]; then
-    check "IORT stream configured for xHCI DMA" "smmu: enabled"
-    check "xHCI DMA window translated" "smmu_dma_window: xhci only, translation active"
+check "PCI segment swept for bus masters after exit" "dma_sweep: seg "
+check_absent "no endpoint left with bus master stuck on" "dma_sweep: bme STUCK"
+check "xHCI bus master off before the DMA gate" "xhci_pci: command=0x[0-9a-f]* bus_master=off"
+if [[ "${mode}" == "fail-closed" ]]; then
+    check "xHCI DMA denied without an SMMU" "dma_gate: xhci denied (NoSmmu), bus master stays off"
+    check "keyboard fail-closed without an SMMU" "keyboard: unavailable (SMMU DMA isolation not active)"
+    check_absent "xHCI never granted DMA" "dma_gate: xhci granted"
+    check_absent "keyboard never attached" "keyboard: ready"
+else
+    check "keyboard attached by the AIENOS driver" "keyboard: ready"
+    if [[ "${mode}" == "smmu" ]]; then
+        check "IORT stream configured for xHCI DMA" "smmu: enabled"
+        check "xHCI DMA window translated" "smmu_dma_window: xhci only, translation active"
+        check "xHCI DMA granted only as confined" "dma_gate: xhci granted (Confined), bus master on"
+    else
+        check "unsafe bypass build announced on serial" "WARNING: UNSAFE DMA BYPASS BUILD"
+        check "unsafe bypass grant announced on serial" "WARNING: UNSAFE DMA BYPASS ACTIVE"
+        check "xHCI DMA granted through the unsafe bypass" "dma_gate: xhci granted (UnsafeBypass)"
+    fi
+    check "typed text echoed on the serial console" "keyboard_echo: ${expected}"
+    check "line ended by Enter and reported" "keyboard_line: ${expected}\$"
+    check "keyboard phase finished on Enter" "keyboard: done (enter)"
+    check "help command output" "commands: help mem el report uptime exit"
+    check "EL command output" "EL1"
+    check "memory command output" "conventional_memory_kb:"
+    check "keyboard phase finished on exit" "keyboard: done (exit)"
+    check "xHCI bus master revoked after the keyboard phase" "dma_gate: xhci bus master revoked"
+fi
+if [[ "${mode}" != "unsafe-bypass" ]]; then
+    check_absent "no unsafe DMA bypass in this image" "UNSAFE DMA BYPASS"
 fi
-check "typed text echoed on the serial console" "keyboard_echo: ${expected}"
-check "line ended by Enter and reported" "keyboard_line: ${expected}\$"
-check "keyboard phase finished on Enter" "keyboard: done (enter)"
-check "help command output" "commands: help mem el report uptime exit"
-check "EL command output" "EL1"
-check "memory command output" "conventional_memory_kb:"
-check "keyboard phase finished on exit" "keyboard: done (exit)"
 if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then
     echo "FAIL  panic or fault reported"
     failed=1
@@ -175,4 +225,7 @@ if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then
     echo "---- serial console ----"
     cat "${work}/serial.txt"
 fi
-[[ "${failed}" == 0 ]] && echo "QEMU_KEYBOARD: PASS" || { echo "QEMU_KEYBOARD: FAIL"; exit 1; }
+if [[ "${mode}" == "unsafe-bypass" ]]; then
+    echo "WARNING: this was an UNSAFE DMA BYPASS run (no SMMU confinement)."
+fi
+[[ "${failed}" == 0 ]] && echo "QEMU_KEYBOARD: PASS (${mode})" || { echo "QEMU_KEYBOARD: FAIL (${mode})"; exit 1; }
diff --git a/scripts/qemu_smmu_test.sh b/scripts/qemu_smmu_test.sh
index 1714faf4..b6f91897 100755
--- a/scripts/qemu_smmu_test.sh
+++ b/scripts/qemu_smmu_test.sh
@@ -1,6 +1,8 @@
 #!/usr/bin/env bash
 # Exercise IORT discovery, SMMUv3 translation and real xHCI keyboard DMA.
+# Always the confined path: the unsafe DMA bypass is forced off here.
 set -euo pipefail
 repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
 cd "${repo_root}"
-AIENOS_QEMU_SMMU=1 exec bash scripts/qemu_keyboard_test.sh
+unset AIENOS_BUILD_FEATURES
+AIENOS_UNSAFE_DMA_BYPASS=0 AIENOS_QEMU_SMMU=1 exec bash scripts/qemu_keyboard_test.sh
diff --git a/scripts/stage_one_time_boot.sh b/scripts/stage_one_time_boot.sh
index 72e75c15..9b14e63e 100755
--- a/scripts/stage_one_time_boot.sh
+++ b/scripts/stage_one_time_boot.sh
@@ -29,7 +29,7 @@ fi
 commit="$(git rev-parse HEAD)"
 
 AIENOS_COMMIT="${commit}" cargo build --quiet --release -p aienos-boot \
-    --target aarch64-unknown-uefi --features handoff --bin aienos-handoff
+    --target aarch64-unknown-uefi --features handoff,hardware-staging --bin aienos-handoff
 cargo run --quiet --release -p aienos-evidence -- verify-efi "${image}"
 
 if [[ -r "${secure_boot_var}" ]] && [[ "$(od -An -t u1 -j 4 -N 1 "${secure_boot_var}" | tr -d ' ')" == "1" ]]; then
diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh
index 9dea907f..1bbc2575 100755
--- a/scripts/verify_all.sh
+++ b/scripts/verify_all.sh
@@ -60,8 +60,13 @@ fi
 echo ""
 echo "--- [SEED-0A USB Keyboard in QEMU (input.keyboard.usb)] ---"
 if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" ]]; then
-    ./scripts/qemu_keyboard_test.sh
+    # Never an unsafe DMA bypass build here: clear any inherited override.
+    unset AIENOS_UNSAFE_DMA_BYPASS AIENOS_BUILD_FEATURES
+    # Default mode: keyboard DMA only through a QEMU SMMUv3 stream.
+    AIENOS_QEMU_SMMU=1 ./scripts/qemu_keyboard_test.sh
     ./scripts/qemu_smmu_test.sh
+    # No SMMU and no bypass: the keyboard must stay unavailable, DMA off.
+    AIENOS_QEMU_SMMU=0 ./scripts/qemu_keyboard_test.sh
 else
     echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host."
 fi