//! AHCI (Serial ATA AHCI 1.3.1): SATA disks, on PCI (class 01:06:01), as //! older laptops and PCs have them and QEMU's `q35` has its controller //! built in. Each port with a disk behind it is a disk (`sata0`); each //! request is one command in a slot of its own, up to [`SLOTS`] in flight, //! completed by interrupt (MSI on a PC, INTx on ARM), as `block::wait` has //! it. Drives that are not disks (an optical drive's ATAPI) are left alone. use super::block::{self, BLOCK, Controller, Data, Op}; use crate::mm::pages; use crate::mmu::physical; use crate::println; use crate::sync::SpinLock; use alloc::string::String; use alloc::sync::Arc; use alloc::vec::Vec; use core::sync::atomic::{Ordering, fence}; const CLASS: u32 = 0x01_06_01; const HBA_CAP: usize = 0x00; const HBA_GHC: usize = 0x04; const HBA_IS: usize = 0x08; const HBA_PI: usize = 0x0c; const GHC_AHCI: u32 = 1 << 31; const GHC_INTERRUPTS: u32 = 1 << 1; const PORT_CLB: usize = 0x00; const PORT_FB: usize = 0x08; const PORT_IS: usize = 0x10; const PORT_IE: usize = 0x14; const PORT_CMD: usize = 0x18; const PORT_TFD: usize = 0x20; const PORT_SIG: usize = 0x24; const PORT_SSTS: usize = 0x28; const PORT_SERR: usize = 0x30; const PORT_CI: usize = 0x38; const CMD_START: u32 = 1; const CMD_SPIN_UP: u32 = 1 << 1; const CMD_POWER_ON: u32 = 1 << 2; const CMD_FIS_RECEIVE: u32 = 1 << 4; const CMD_FIS_RUNNING: u32 = 1 << 14; const CMD_RUNNING: u32 = 1 << 15; /// A device-to-host register FIS arrived, and the task file's error. const IS_D2H: u32 = 1; const IS_TASK_FILE_ERROR: u32 = 1 << 30; const TFD_BUSY: u32 = 0x80; const TFD_DRQ: u32 = 0x08; const TFD_ERROR: u32 = 0x01; const SIGNATURE_DISK: u32 = 0x0000_0101; const ATA_READ_DMA_EXT: u8 = 0x25; const ATA_WRITE_DMA_EXT: u8 = 0x35; const ATA_FLUSH_CACHE_EXT: u8 = 0xea; const ATA_IDENTIFY: u8 = 0xec; /// Command slots used, each with a table and a page of data. const SLOTS: usize = 16; /// Each slot's command table: its FIS, then one PRD entry. const TABLE: usize = 256; const _: () = assert!(1024 + 256 + SLOTS * TABLE <= 2 * crate::mm::PAGE); /// One port, with a disk behind it. struct Port { regs: usize, /// The command list (32 headers), the received FISes, and the slots' /// tables, in two pages. page: usize, data: [usize; SLOTS], /// The slots issued and not yet completed. issued: u32, error: bool, waiter: Option, } impl Port { fn read(&self, offset: usize) -> u32 { // SAFETY: the port's registers, in the controller's BAR. unsafe { ((self.regs + offset) as *const u32).read_volatile() } } fn write(&self, offset: usize, value: u32) { // SAFETY: as in `read`. unsafe { ((self.regs + offset) as *mut u32).write_volatile(value) } } fn table(&self, slot: usize) -> usize { self.page + 1024 + 256 + slot * TABLE } /// Prepares slot `slot` to send `command` on `lba` for `sectors`, with /// its data, if any: `len` bytes at `buffer`, written to the disk when /// `write`. fn prepare( &mut self, slot: usize, command: u8, lba: u64, sectors: u16, data: Option<(usize, usize, bool)>, ) { let (buffer, len, write) = data.unwrap_or((0, 0, false)); let table = self.table(slot); // SAFETY: the slot's table and header, ours while it is not issued. unsafe { core::ptr::write_bytes(table as *mut u8, 0, TABLE); let fis = table as *mut u8; fis.write(0x27); // register, host to device fis.add(1).write(0x80); // a command fis.add(2).write(command); for i in 0..3 { fis.add(4 + i).write((lba >> (8 * i)) as u8); fis.add(8 + i).write((lba >> (24 + 8 * i)) as u8); } fis.add(7).write(0x40); // LBA addressing fis.add(12).write(sectors as u8); fis.add(13).write((sectors >> 8) as u8); let prd = (table + 0x80) as *mut u32; if len > 0 { let at = physical(buffer) as u64; prd.write(at as u32); prd.add(1).write((at >> 32) as u32); prd.add(3).write(len as u32 - 1); } let header = (self.page + slot * 32) as *mut u32; // Five double words of FIS, written to the device or read, and // one PRD entry when there are data. header.write(5 | if write { 1 << 6 } else { 0 } | if len > 0 { 1 << 16 } else { 0 }); header.add(1).write(0); let t = physical(table) as u64; header.add(2).write(t as u32); header.add(3).write((t >> 32) as u32); } } fn issue(&mut self, slots: u32) { fence(Ordering::SeqCst); self.issued |= slots; self.write(PORT_CI, slots); } /// Takes what completed. True when nothing issued is left. fn collect(&mut self) -> bool { let status = self.read(PORT_IS); self.write(PORT_IS, status); if status & IS_TASK_FILE_ERROR != 0 || self.read(PORT_TFD) & TFD_ERROR != 0 { self.error = true; // A command that failed stops the port: none after it completes. self.issued = 0; } self.issued &= self.read(PORT_CI); self.issued == 0 } fn wait_idle(&self) -> bool { let deadline = crate::timer::now_ms() + 1_000; while self.read(PORT_TFD) & (TFD_BUSY | TFD_DRQ) != 0 { if crate::timer::now_ms() > deadline { return false; } core::hint::spin_loop(); } true } } /// One disk. pub struct Disk { port: Arc>, sectors: u64, sector: u64, name: String, model: String, } impl Controller for Disk { fn transfer(&self, op: Op, blocks: &[u64], mut data: Data) -> bool { let per_block = BLOCK as u64 / self.sector; let mut ok = true; let mut at = 0; while at < blocks.len() { let n = SLOTS.min(blocks.len() - at); { let mut p = self.port.lock(); p.error = false; let mut slots = 0; for k in 0..n { let buffer = p.data[k]; match op { Op::Read => p.prepare( k, ATA_READ_DMA_EXT, blocks[at + k] * per_block, per_block as u16, Some((buffer, BLOCK, false)), ), Op::Write => { if let Data::From(from) = &data { // SAFETY: the slot's data page, ours while it is not issued. unsafe { core::ptr::copy_nonoverlapping( from[at + k].as_ptr(), buffer as *mut u8, BLOCK, ) }; } p.prepare( k, ATA_WRITE_DMA_EXT, blocks[at + k] * per_block, per_block as u16, Some((buffer, BLOCK, true)), ) } Op::Flush => p.prepare(k, ATA_FLUSH_CACHE_EXT, 0, 0, None), } slots |= 1 << k; } p.issue(slots); } block::wait(&self.port, |p| &mut p.waiter, Port::collect); let p = self.port.lock(); ok &= !p.error; if let Data::Into(into) = &mut data { for k in 0..n { // SAFETY: the device filled the slot's data page. unsafe { core::ptr::copy_nonoverlapping( p.data[k] as *const u8, into[at + k].as_mut_ptr(), BLOCK, ) }; } } drop(p); at += n; } ok } fn blocks(&self) -> u64 { self.sectors * self.sector / BLOCK as u64 } fn sector(&self) -> u64 { self.sector } fn write_cache(&self) -> bool { true } fn name(&self) -> &str { &self.name } fn model(&self) -> &str { &self.model } fn reset(&self) { let p = self.port.lock(); p.write(PORT_CMD, p.read(PORT_CMD) & !(CMD_START | CMD_FIS_RECEIVE)); } } /// Every port with a disk, by its controller's interrupt, for the handler; /// with the controller's registers and the port's number. static PORTS: SpinLock> = SpinLock::new(Vec::new()); /// A port with a disk: its controller's interrupt and registers, its /// number, and itself. type PortEntry = (u32, usize, usize, Arc>); /// Sets up every AHCI controller and returns its disks. pub fn find() -> Vec> { let mut found: Vec> = Vec::new(); for f in crate::pci::find_class(CLASS) { crate::pci::claim(&f, "ahci", crate::device::Class::Storage); let Some(hba) = f.bar_address(5, 0) else { println!("ahci: no registers"); continue; }; let Some(intid) = f.take_interrupt() else { println!("ahci: no interrupt"); continue; }; let read = |o: usize| { // SAFETY: the controller's registers. unsafe { ((hba + o) as *const u32).read_volatile() } }; let write = |o: usize, v: u32| { // SAFETY: as above. unsafe { ((hba + o) as *mut u32).write_volatile(v) } }; write(HBA_GHC, read(HBA_GHC) | GHC_AHCI); let cap = read(HBA_CAP); if cap & (1 << 31) == 0 && core::mem::size_of::() == 8 { // No 64-bit addressing: the kernel's pages may lie above 4 GiB. println!("ahci: 32-bit addressing only, left alone"); } let implemented = read(HBA_PI); for n in 0..32 { if implemented & (1 << n) == 0 { continue; } let regs = hba + 0x100 + 0x80 * n; if let Some(disk) = start_port(found.len(), regs) { PORTS.lock().push((intid, hba, n, disk.port.clone())); found.push(Arc::new(disk)); } } write(HBA_IS, u32::MAX); write(HBA_GHC, read(HBA_GHC) | GHC_INTERRUPTS); block::route_interrupt(intid); } found } /// Starts port `regs` when a disk is behind it, and asks the disk what it /// is. The disk's number among those found is `n`. fn start_port(n: usize, regs: usize) -> Option { let page = pages::alloc(1)?; let mut data = [0usize; SLOTS]; for d in &mut data { *d = pages::alloc(0)?; } // SAFETY: a fresh page. unsafe { core::ptr::write_bytes(page as *mut u8, 0, 2 * crate::mm::PAGE) }; let mut port = Port { regs, page, data, issued: 0, error: false, waiter: None, }; // Stopped, as the firmware may not have left it, before its memory // changes. port.write(PORT_CMD, port.read(PORT_CMD) & !CMD_START); let deadline = crate::timer::now_ms() + 500; while port.read(PORT_CMD) & CMD_RUNNING != 0 && crate::timer::now_ms() < deadline {} port.write(PORT_CMD, port.read(PORT_CMD) & !CMD_FIS_RECEIVE); while port.read(PORT_CMD) & CMD_FIS_RUNNING != 0 && crate::timer::now_ms() < deadline {} let list = physical(page) as u64; let fis = list + 1024; port.write(PORT_CLB, list as u32); port.write(PORT_CLB + 4, (list >> 32) as u32); port.write(PORT_FB, fis as u32); port.write(PORT_FB + 4, (fis >> 32) as u32); port.write(PORT_SERR, u32::MAX); port.write(PORT_IS, u32::MAX); // Receiving, spun up and powered on: with no firmware before it (ARM), // the link comes up and the drive says what it is only now. port.write( PORT_CMD, port.read(PORT_CMD) | CMD_FIS_RECEIVE | CMD_SPIN_UP | CMD_POWER_ON, ); let deadline = crate::timer::now_ms() + 1_000; while port.read(PORT_SSTS) & 0xf != 3 && crate::timer::now_ms() < deadline { core::hint::spin_loop(); } // A device present, its link up, its first status in, and a disk's // signature. let present = port.read(PORT_SSTS) & 0xf == 3 && port.wait_idle(); if !present || port.read(PORT_SIG) != SIGNATURE_DISK { port.write(PORT_CMD, port.read(PORT_CMD) & !CMD_FIS_RECEIVE); pages::free(page, 1); for d in data { pages::free(d, 0); } return None; } port.write(PORT_CMD, port.read(PORT_CMD) | CMD_START); // IDENTIFY DEVICE, polled: interrupts are not on yet. let identify = data[0]; port.prepare(0, ATA_IDENTIFY, 0, 0, Some((identify, 512, false))); port.issue(1); let deadline = crate::timer::now_ms() + 2_000; while !port.collect() { if crate::timer::now_ms() > deadline { return None; } core::hint::spin_loop(); } if port.error { return None; } // SAFETY: the 512 bytes the disk wrote. let id = unsafe { core::slice::from_raw_parts(identify as *const u16, 256) }; let word = |i: usize| u64::from(id[i]); let sectors = word(100) | word(101) << 16 | word(102) << 32 | word(103) << 48; // Word 106: valid (bit 14, not 15), and bit 12 for a logical sector of // more than 256 words, its size in words 117–118. let sector = if id[106] & 0xc000 == 0x4000 && id[106] & (1 << 12) != 0 { (word(117) | word(118) << 16) * 2 } else { 512 }; // The model, its bytes swapped in pairs. let model: Vec = id[27..47].iter().flat_map(|w| w.to_be_bytes()).collect(); let model = String::from(String::from_utf8_lossy(&model).trim()); if sectors == 0 || !matches!(sector, 512 | 4096) { println!("ahci: a disk without 48-bit addressing, or of {sector}-byte sectors, left alone"); return None; } port.write(PORT_IE, IS_D2H | IS_TASK_FILE_ERROR); Some(Disk { port: Arc::new(SpinLock::new(port)), sectors, sector, name: alloc::format!("sata{n}"), model, }) } /// A controller's interrupt: its ports' completions taken. False if `intid` /// is no controller's. pub fn interrupt(intid: u32) -> bool { let ports: Vec<_> = PORTS .lock() .iter() .filter(|(i, ..)| *i == intid) .map(|(_, hba, n, p)| (*hba, *n, p.clone())) .collect(); for (hba, n, port) in &ports { let waiter = { let mut p = port.lock(); if p.collect() { p.waiter.take() } else { None } }; // The controller's own bit for the port, cleared once the port's are. // SAFETY: the controller's interrupt status register. unsafe { ((hba + HBA_IS) as *mut u32).write_volatile(1 << n) }; block::wake(waiter); } !ports.is_empty() }