Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-boot/src/usb_keyboard.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-boot / src / usb_keyboard.rs` 477 lines ยท 18674 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! SEED-0A candidate `input.keyboard.usb` (ADR 0012): after firmware exit, 17 //! drive the xHCI controller with the polled AIENOS driver and echo typed 18 //! keys on the SPCR console and the screen. 19 //! 20 //! Built only with the `usb-keyboard` feature, which the QEMU keyboard test 21 //! enables and hardware staging does not: the candidate is proven in QEMU 22 //! and never admitted to Machine 1 before M3 can confine it. 23 //! 24 //! DMA rule (M3): no SMMU confinement means no DMA. After firmware exit 25 //! [`take_over_dma`] clears Bus Master Enable on every endpoint of the 26 //! controller's PCI segment before any SMMU or driver setup, and [`run`] sets 27 //! it on the xHCI again only when [`dma_gate::dma_grant`] allows it. 28 29 use aienos_kernel::acpi::{self, EcamWindow}; 30 use aienos_kernel::arch::aarch64::{counter_frequency_hz, counter_ticks, MmioReg}; 31 use aienos_kernel::console::EarlyConsole; 32 use aienos_kernel::display::Screen; 33 use aienos_kernel::dma_gate::{self, BusMasterSweep, DmaGrant, PciConfig, PCI_COMMAND}; 34 use aienos_kernel::usb::hid::{BootKeyboardDecoder, KeyEvent}; 35 use aienos_kernel::usb::xhci; 36 use aienos_kernel::usb::xhci::controller::{DmaMemory, Keyboard}; 37 use core::fmt::Write; 38 use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; 39 use uefi::proto::pci::root_bridge::PciRootBridgeIo; 40 use uefi::proto::pci::PciIoAddress; 41 42 /// Seconds to wait for a line; `AIENOS_KEYBOARD_SECS` at build time. 43 fn listen_secs() -> u64 { 44 option_env!("AIENOS_KEYBOARD_SECS") 45 .and_then(|s| s.parse().ok()) 46 .unwrap_or(30) 47 } 48 49 /// Printed on every boot of an image built with the unsafe DMA bypass. 50 const UNSAFE_BYPASS_BANNER: &str = 51 "\nWARNING: UNSAFE DMA BYPASS BUILD (unsafe-debug-dma-without-smmu): \ 52 xHCI DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n"; 53 54 /// DMA memory for the driver, used only after firmware exit. 55 static mut DMA: DmaMemory = DmaMemory::new(); 56 57 /// Where the first xHCI controller sits, found before firmware exit. 58 #[derive(Clone, Copy)] 59 pub struct XhciLocation { 60 segment: u16, 61 bus: u8, 62 device: u8, 63 function: u8, 64 mmio: u64, 65 } 66 67 impl XhciLocation { 68 pub fn mmio_base(self) -> u64 { 69 self.mmio 70 } 71 pub fn ecam_location(self) -> (u16, u8) { 72 (self.segment, self.bus) 73 } 74 pub fn requester_id(self) -> u32 { 75 (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function) 76 } 77 pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option { 78 iort.stream_id_for(self.requester_id()) 79 } 80 pub fn dma_window(self) -> (u64, usize) { 81 let base = core::ptr::addr_of!(DMA) as u64; 82 (base & !0xfff, core::mem::size_of::()) 83 } 84 } 85 86 /// Walk every root bridge for the first xHCI controller (pre-exit only). 87 pub fn find_xhci() -> Option { 88 for handle in uefi::boot::find_handles::().ok()? { 89 // Shared open, read-only use, as in GB10 discovery. 90 let params = OpenProtocolParams { 91 handle, 92 agent: uefi::boot::image_handle(), 93 controller: None, 94 }; 95 let Ok(mut root) = (unsafe { 96 uefi::boot::open_protocol::( 97 params, 98 OpenProtocolAttributes::GetProtocol, 99 ) 100 }) else { 101 continue; 102 }; 103 let (bus_min, bus_max) = crate::bus_ranges(&mut root).unwrap_or((0, 0)); 104 for bus in bus_min..=bus_max { 105 for device in 0..32u8 { 106 for function in 0..8u8 { 107 let address = PciIoAddress::new(bus, device, function); 108 let mut read = |offset| { 109 root.pci() 110 .read_one::(address.with_register(offset)) 111 .ok() 112 }; 113 let Some(_) = read(0).filter(|id| id & 0xffff != 0xffff) else { 114 if function == 0 { 115 break; 116 } 117 continue; 118 }; 119 let bar = (read(0x08), read(0x10), read(0x14)); 120 if let (Some(class), Some(low), Some(high)) = bar { 121 if let Some(mmio) = xhci::xhci_mmio_base(class, low, high) { 122 let segment = root.segment_nr() as u16; 123 return Some(XhciLocation { 124 segment, 125 bus, 126 device, 127 function, 128 mmio, 129 }); 130 } 131 } 132 let multi = read(0x0c).is_some_and(|v| v & 0x80_0000 != 0); 133 if function == 0 && !multi { 134 break; 135 } 136 } 137 } 138 } 139 } 140 None 141 } 142 143 fn console() -> Option { 144 crate::CONSOLE 145 .try_lock() 146 .and_then(|k| *k) 147 .and_then(EarlyConsole::from_kind) 148 } 149 150 /// Write `text` to the SPCR console and the screen. 151 fn say(screen: &mut Option, text: &str) { 152 if let Some(console) = console() { 153 console.write_str(text); 154 } 155 if let Some(s) = screen.as_mut() { 156 let _ = s.write_str(text); 157 } 158 } 159 160 /// Config space of one ECAM window, reached through the kernel identity map. 161 /// Only valid after `enter_kernel_mmu` mapped the window as device memory. 162 struct Ecam(EcamWindow); 163 164 impl PciConfig for Ecam { 165 fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option { 166 let addr = self.0.config_address(bus, device, function, offset)?; 167 // SAFETY: `config_address` returned an address inside this ECAM window, 168 // which `enter_kernel_mmu` mapped as device memory. 169 Some(unsafe { MmioReg::::new(addr as usize) }.read()) 170 } 171 fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) { 172 if let Some(addr) = self.0.config_address(bus, device, function, offset) { 173 // SAFETY: as in `read32`. 174 unsafe { MmioReg::::new(addr as usize) }.write(value); 175 } 176 } 177 } 178 179 impl Ecam { 180 fn command(&mut self, at: &XhciLocation) -> Option { 181 self.read32(at.bus, at.device, at.function, PCI_COMMAND) 182 .map(|v| v as u16) 183 } 184 fn set_command(&mut self, at: &XhciLocation, value: u16) { 185 self.write16(at.bus, at.device, at.function, PCI_COMMAND, value); 186 } 187 } 188 189 /// What [`take_over_dma`] did to the controller's PCI segment. 190 #[derive(Clone, Copy)] 191 pub struct DmaTakeover { 192 window: EcamWindow, 193 sweep: BusMasterSweep, 194 } 195 196 /// Post-exit, before any SMMU or driver setup: clear Bus Master Enable on 197 /// every endpoint in the xHCI's ECAM window, so every device there starts 198 /// with DMA off. `None` (DMA state unknown, keyboard stays unavailable) when 199 /// there is no controller or no ECAM window for it. 200 pub fn take_over_dma(xhci: Option, mcfg: Option<&[u8]>) -> Option { 201 let at = xhci?; 202 let window = acpi::mcfg_window(mcfg?, at.segment, at.bus) 203 .ok() 204 .flatten()?; 205 let sweep = dma_gate::sweep_bus_master(&mut Ecam(window), window.start_bus, window.end_bus); 206 Some(DmaTakeover { window, sweep }) 207 } 208 209 fn report_takeover(screen: &mut Option, takeover: &DmaTakeover) { 210 let (w, s) = (&takeover.window, &takeover.sweep); 211 let mut line = aienos_kernel::report::ReportBuf::<256>::new(); 212 let _ = writeln!( 213 line, 214 "dma_sweep: seg {:04x} bus {:02x}-{:02x} functions={} bridges={} bridges_bme={} \ 215 endpoints_bme_found={} still_enabled={}", 216 w.segment, 217 w.start_bus, 218 w.end_bus, 219 s.functions, 220 s.bridges, 221 s.bridges_bus_master, 222 s.endpoints_bus_master, 223 s.still_enabled 224 ); 225 say(screen, line.as_str()); 226 for f in s.findings() { 227 let mut entry = aienos_kernel::report::ReportBuf::<128>::new(); 228 let _ = writeln!( 229 entry, 230 "dma_sweep: bme {} {:04x}:{:02x}:{:02x}.{} command {:#06x} -> {:#06x}", 231 if f.cleared() { "cleared" } else { "STUCK" }, 232 w.segment, 233 f.at.bus, 234 f.at.device, 235 f.at.function, 236 f.command_before, 237 f.command_after 238 ); 239 say(screen, entry.as_str()); 240 } 241 } 242 243 /// Clear Bus Master Enable on the controller again (revoke its DMA). 244 fn revoke_dma(screen: &mut Option, ecam: &mut Ecam, at: &XhciLocation) { 245 if let Some(command) = ecam.command(at) { 246 ecam.set_command(at, dma_gate::without_bus_master(command)); 247 } 248 let off = ecam 249 .command(at) 250 .is_some_and(|c| !dma_gate::bus_master_enabled(c)); 251 say( 252 screen, 253 if off { 254 "dma_gate: xhci bus master revoked\n" 255 } else { 256 "dma_gate: xhci bus master revoke FAILED\n" 257 }, 258 ); 259 } 260 261 /// Post-exit: bring up the keyboard and echo keys until Enter or timeout. 262 #[allow(clippy::too_many_arguments)] 263 pub fn run( 264 xhci: Option, 265 takeover: Option, 266 screen: &mut Option, 267 conventional_memory_kb: u64, 268 _exception_level: u8, 269 boot_report: &str, 270 smmu_ready: bool, 271 smmu_base: Option, 272 smmu_stream_id: Option, 273 smmu_events: *const [[u64; 4]; 16], 274 ) { 275 if aienos_boot::UNSAFE_DMA_BYPASS { 276 say(screen, UNSAFE_BYPASS_BANNER); 277 } 278 let mut line = aienos_kernel::report::ReportBuf::<512>::new(); 279 let Some(at) = xhci else { 280 say(screen, "\nkeyboard: unavailable (no xHCI controller)\n"); 281 return; 282 }; 283 let _ = writeln!( 284 line, 285 "\nkeyboard: xhci {:04x}:{:02x}:{:02x}.{} mmio {:#x}", 286 at.segment, at.bus, at.device, at.function, at.mmio 287 ); 288 say(screen, line.as_str()); 289 let Some(takeover) = takeover else { 290 say( 291 screen, 292 "keyboard: unavailable (no ECAM window for the controller; DMA not granted)\n", 293 ); 294 return; 295 }; 296 report_takeover(screen, &takeover); 297 let mut ecam = Ecam(takeover.window); 298 let Some(command) = ecam.command(&at) else { 299 say( 300 screen, 301 "keyboard: unavailable (xHCI config space unreadable)\n", 302 ); 303 return; 304 }; 305 let mut state = aienos_kernel::report::ReportBuf::<96>::new(); 306 let _ = writeln!( 307 state, 308 "xhci_pci: command={command:#06x} bus_master={}", 309 if dma_gate::bus_master_enabled(command) { 310 "on" 311 } else { 312 "off" 313 } 314 ); 315 say(screen, state.as_str()); 316 if dma_gate::bus_master_enabled(command) { 317 say( 318 screen, 319 "keyboard: unavailable (xHCI bus master would not clear)\n", 320 ); 321 return; 322 } 323 let grant = match dma_gate::dma_grant( 324 smmu_ready, 325 smmu_base.is_some(), 326 aienos_boot::UNSAFE_DMA_BYPASS, 327 ) { 328 Ok(grant) => grant, 329 Err(denied) => { 330 let mut msg = aienos_kernel::report::ReportBuf::<160>::new(); 331 let _ = writeln!( 332 msg, 333 "dma_gate: xhci denied ({denied:?}), bus master stays off\n\ 334 keyboard: unavailable (SMMU DMA isolation not active)" 335 ); 336 say(screen, msg.as_str()); 337 return; 338 } 339 }; 340 let dma_mode = match grant { 341 DmaGrant::Confined => "smmu-translated", 342 DmaGrant::UnsafeBypass => { 343 say( 344 screen, 345 "WARNING: UNSAFE DMA BYPASS ACTIVE: no SMMU on this machine, xHCI DMA \ 346 reaches physical memory UNCONFINED (QEMU debug only)\n", 347 ); 348 "UNSAFE-identity-no-smmu" 349 } 350 }; 351 let mut mode = aienos_kernel::report::ReportBuf::<192>::new(); 352 let _ = writeln!( 353 mode, 354 "dma_gate: xhci granted ({grant:?}), bus master on\n\ 355 xhci_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}", 356 core::ptr::addr_of!(DMA) as usize, 357 core::mem::size_of::() 358 ); 359 ecam.set_command(&at, dma_gate::with_bus_master(command)); 360 say(screen, mode.as_str()); 361 // SAFETY: firmware has exited and released the controller; DMA is used 362 // by nothing else, is identity-mapped, and lives for the whole boot. 363 let started = unsafe { Keyboard::start(at.mmio, core::ptr::addr_of_mut!(DMA)) }; 364 let mut keyboard = match started { 365 Ok(k) => k, 366 Err(e) => { 367 let mut msg = aienos_kernel::report::ReportBuf::<512>::new(); 368 let _ = writeln!(msg, "keyboard: unavailable ({e:?})"); 369 say(screen, msg.as_str()); 370 revoke_dma(screen, &mut ecam, &at); 371 if let Some(base) = smmu_base { 372 // SAFETY: `base` is the identity-mapped SMMUv3 register aperture 373 // from the IORT; only register offsets inside it are read. 374 let reg = |offset| unsafe { MmioReg::::new(base as usize + offset) }.read(); 375 aienos_kernel::arch::aarch64::clean_invalidate_dcache_range( 376 smmu_events as usize, 377 core::mem::size_of::<[[u64; 4]; 16]>(), 378 ); 379 let events = unsafe { core::ptr::read_volatile(smmu_events) }; 380 let mut fault = aienos_kernel::report::ReportBuf::<1024>::new(); 381 let _ = writeln!(fault, "smmu_fault: GERROR={:#x} GERRORN={:#x} EVENTQ_PROD={:#x} EVENTQ_CONS={:#x} events={events:016x?}", reg(0x60), reg(0x64), reg(0xa8), reg(0xac)); 382 say(screen, fault.as_str()); 383 if let Some(sid) = smmu_stream_id { 384 let table_base = (u64::from(reg(0x84)) << 32 | u64::from(reg(0x80))) & !0x3f; 385 let cfg = reg(0x88); 386 let ste_addr = table_base + u64::from(sid) * 64; 387 let ste0 = unsafe { core::ptr::read_volatile(ste_addr as *const u64) }; 388 let ste1 = unsafe { core::ptr::read_volatile((ste_addr + 8) as *const u64) }; 389 let mut entry = aienos_kernel::report::ReportBuf::<192>::new(); 390 let _ = writeln!(entry, "smmu_ste: base={table_base:#x} cfg={cfg:#x} sid={sid:#x} addr={ste_addr:#x} words=[{ste0:#x},{ste1:#x}]"); 391 say(screen, entry.as_str()); 392 } 393 } 394 return; 395 } 396 }; 397 let (port, slot, endpoint) = keyboard.location(); 398 let mut msg = aienos_kernel::report::ReportBuf::<200>::new(); 399 let _ = writeln!( 400 msg, 401 "keyboard: ready (port {port}, slot {slot}, endpoint {endpoint:#04x})" 402 ); 403 let _ = writeln!(msg, "keyboard: shell ready ({} s)", listen_secs()); 404 say(screen, msg.as_str()); 405 406 let mut decoder = BootKeyboardDecoder::new(); 407 let mut line = [0u8; aienos_kernel::shell::LINE_CAPACITY]; 408 let mut length = 0usize; 409 let mut exit = false; 410 let deadline = listen_secs().saturating_mul(counter_frequency_hz()); 411 let start = counter_ticks(); 412 say(screen, "aienos> "); 413 while !exit && counter_ticks().wrapping_sub(start) < deadline && !keyboard.is_halted() { 414 let Some(report) = keyboard.poll() else { 415 core::hint::spin_loop(); 416 continue; 417 }; 418 decoder.handle_report(&report, |event| { 419 if event == KeyEvent::Enter { 420 say(screen, "\n"); 421 say(screen, "keyboard_echo: "); 422 say(screen, core::str::from_utf8(&line[..length]).unwrap_or("")); 423 say(screen, "\n"); 424 let mut entered = aienos_kernel::report::ReportBuf::<96>::new(); 425 let _ = writeln!( 426 entered, 427 "keyboard_line: {}", 428 core::str::from_utf8(&line[..length]).unwrap_or("") 429 ); 430 say(screen, entered.as_str()); 431 say(screen, "keyboard: done (enter)\n"); 432 let elapsed = counter_ticks().wrapping_sub(start); 433 let hz = counter_frequency_hz(); 434 let uptime_ms = elapsed.saturating_mul(1000).checked_div(hz).unwrap_or(0); 435 let input = core::str::from_utf8(&line[..length]).unwrap_or(""); 436 let parsed = aienos_kernel::shell::parse_line(input); 437 let output = aienos_kernel::shell::dispatch( 438 input, 439 &aienos_kernel::shell::ShellContext { 440 conventional_memory_kb, 441 // Read live when the command runs, not cached at shell start. 442 exception_level: aienos_kernel::arch::aarch64::current_el(), 443 report: boot_report, 444 uptime_ms, 445 }, 446 ); 447 say(screen, output.as_str()); 448 exit = parsed.is_some_and(|p| p.command == aienos_kernel::shell::Command::Exit); 449 length = 0; 450 if !exit { 451 say(screen, "aienos> "); 452 } 453 } else if event == KeyEvent::Backspace { 454 if length > 0 { 455 length -= 1; 456 say(screen, "\x08 \x08"); 457 } 458 } else if let KeyEvent::Char(c) = event { 459 if c.is_ascii() && length < line.len() { 460 line[length] = c as u8; 461 length += 1; 462 let mut buf = [0u8; 4]; 463 say(screen, c.encode_utf8(&mut buf)); 464 } 465 } 466 }); 467 } 468 let mut end = aienos_kernel::report::ReportBuf::<200>::new(); 469 let reason = match (exit, keyboard.is_halted()) { 470 (true, _) => "exit", 471 (false, true) => "endpoint halted", 472 (false, false) => "timeout", 473 }; 474 let _ = writeln!(end, "\nkeyboard: done ({reason})",); 475 say(screen, end.as_str()); 476 revoke_dma(screen, &mut ecam, &at); 477 }