Skip to main content

strat9_kernel/hardware/storage/
ahci.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! AHCI (Advanced Host Controller Interface) driver : AHCI spec 1.3.1
24//!
25//! PCI: class=0x01 (Mass Storage), subclass=0x06 (SATA), prog_if=0x01
26//! MMIO base: BAR5 (ABAR)
27//!
28//! Per-port memory layout (packed into one 4 KB page):
29//!   [0x000..0x3FF]  Command List   (1024 B, 32 × 32-byte headers)
30//!   [0x400..0x4FF]  FIS receive    (256 B)
31//!   [0x500..0x5FF]  Command table  (128 B header + 1 × 16-byte PRDT)
32//!
33//! ## IRQ-driven completion (DRV-02 v2)
34//!
35//! When a task context exists (`current_task_id()` is `Some`), commands are
36//! completed via interrupt + `WaitQueue::wait_until()` so the issuing task
37//! blocks without busy-spinning.  During early boot (no task yet) the legacy
38//! polling path is used as a fallback.
39//!
40//! Per-port statics (indexed by `port_num 0..32`) are used so the IRQ handler
41//! can signal completion without acquiring any slow lock:
42//!   - `PORT_VIRT[n]`       : MMIO virtual address of port n registers
43//!   - `PORT_SLOT0_DONE[n]` : set by IRQ handler when slot-0 completes
44//!   - `PORT_SLOT0_ERROR[n]`: set by IRQ handler when a task-file error fires
45//!   - `PORT_WQ[n]`         : WaitQueue; issuing task blocks here
46
47use crate::{
48    dma::DmaBuffer,
49    hardware::pci_client::{self as pci, ProbeCriteria},
50    memory,
51    memory::{phys_to_virt, UserSliceRead, UserSliceWrite},
52    sync::{SpinLock, WaitQueue},
53};
54use alloc::{boxed::Box, vec::Vec};
55use core::{
56    ptr,
57    sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering},
58};
59
60pub use super::virtio_block::{BlockDevice, BlockError, SECTOR_SIZE};
61
62// ========== HBA generic registers (at ABAR) ======================================================
63const HBA_GHC: u64 = 0x04;
64const HBA_IS: u64 = 0x08;
65const HBA_PI: u64 = 0x0C;
66
67const GHC_AE: u32 = 1 << 31; // AHCI Enable
68const GHC_IE: u32 = 1 << 1; // Global Interrupt Enable
69const GHC_HR: u32 = 1 << 0; // HBA Reset
70
71// ========== Port register offsets (relative to port base = ABAR + 0x100 + n*0x80)
72const PORT_CLB: u64 = 0x00;
73const PORT_CLBU: u64 = 0x04;
74const PORT_FB: u64 = 0x08;
75const PORT_FBU: u64 = 0x0C;
76const PORT_IS: u64 = 0x10;
77const PORT_IE: u64 = 0x14; // PxIE : port interrupt enable
78const PORT_CMD: u64 = 0x18;
79const PORT_TFD: u64 = 0x20;
80const PORT_SIG: u64 = 0x24;
81const PORT_SSTS: u64 = 0x28;
82const PORT_SERR: u64 = 0x30;
83const PORT_CI: u64 = 0x38;
84
85const CMD_ST: u32 = 1 << 0; // Start
86const CMD_FRE: u32 = 1 << 4; // FIS Receive Enable
87const CMD_FR: u32 = 1 << 14; // FIS Receive Running
88const CMD_CR: u32 = 1 << 15; // Command List Running
89
90const TFD_BSY: u32 = 1 << 7;
91const TFD_DRQ: u32 = 1 << 3;
92
93const SSTS_DET_COMM: u32 = 3;
94const SSTS_DET_MASK: u32 = 0xF;
95
96const SIG_SATA: u32 = 0x0000_0101;
97
98// PxIE bits
99const PXIE_DHRE: u32 = 1 << 0; // D2H Register FIS Received Enable (normal DMA completion)
100const PXIE_TFEE: u32 = 1 << 30; // Task File Error Enable
101
102// ========== Per-port memory layout offsets ========================================================
103const CLB_OFF: u64 = 0x000; // Command List (1024 B)
104const FB_OFF: u64 = 0x400; // FIS buffer   (256 B)
105const CTAB_OFF: u64 = 0x500; // Command Table (128 B header + 16 B PRDT)
106
107// Command header field byte offsets within a 32-byte slot
108const CMDH_FLAGS: usize = 0; // u16: cfl[4:0] | a | w | p | r | b | c
109const CMDH_PRDTL: usize = 2; // u16
110const CMDH_CTBA: usize = 8; // u32
111const CMDH_CTBAU: usize = 12; // u32
112
113// Command table FIS and PRDT offsets
114const CTAB_CFIS: usize = 0x00; // H2D FIS (64 B allocated)
115const CTAB_PRDT: usize = 0x80; // PRDT entries
116
117// H2D FIS field offsets (FIS type 0x27, Register Host-to-Device)
118const FIS_TYPE: usize = 0;
119const FIS_FLAGS: usize = 1; // PM port [3:0] | C [7]
120const FIS_CMD: usize = 2;
121const FIS_LBA0: usize = 4;
122const FIS_LBA1: usize = 5;
123const FIS_LBA2: usize = 6;
124const FIS_DEVICE: usize = 7;
125const FIS_LBA3: usize = 8;
126const FIS_LBA4: usize = 9;
127const FIS_LBA5: usize = 10;
128const FIS_CNT_LO: usize = 12;
129const FIS_CNT_HI: usize = 13;
130
131const FIS_TYPE_H2D: u8 = 0x27;
132const FIS_C_BIT: u8 = 0x80; // command (not control)
133const FIS_LBA_MODE: u8 = 1 << 6;
134
135// ATA commands (48-bit LBA)
136const ATA_IDENTIFY: u8 = 0xEC;
137const ATA_READ_DMA_EXT: u8 = 0x25;
138const ATA_WRITE_DMA_EXT: u8 = 0x35;
139const ATA_FLUSH_CACHE_EXT: u8 = 0xEA;
140
141const EFAULT: i32 = -14;
142
143// PxIS bit 30 = Task File Error Status
144const PXIS_TFES: u32 = 1 << 30;
145
146// ========== Error type ==============================
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
149pub enum AhciError {
150    #[error("no AHCI controller on PCI bus")]
151    NoController,
152    #[error("invalid BAR5 (ABAR)")]
153    BadAbar,
154    #[error("physical memory allocation failed")]
155    Alloc,
156    #[error("port BSY/DRQ set")]
157    Busy,
158    #[error("command timed out")]
159    Timeout,
160    #[error("device reported task-file error")]
161    DeviceError,
162    #[error("invalid sector number")]
163    InvalidSector,
164    #[error("buffer too small (need ≥ SECTOR_SIZE bytes)")]
165    BufferTooSmall,
166    #[error("invalid userspace buffer")]
167    InvalidUserBuffer,
168    #[error("no usable SATA port found")]
169    NoPort,
170}
171
172// ========== Internal port handle ======================================================================
173
174struct AhciPort {
175    port_num: u8,
176    port_virt: u64, // virtual address of port registers
177    #[allow(dead_code)]
178    mem_phys: u64, // physical base of the per-port CLB/FB/CTAB frame
179    mem_virt: u64,  // HHDM virtual address of that frame
180    /// Device-visible address of `mem_phys` (IOVA when translated).
181    mem_device: u64,
182    /// PCI function owning this port.
183    sbdf: crate::hardware::iommu::Sbdf,
184    sector_count: u64,
185}
186
187// ========== Controller ==============================
188
189pub struct AhciController {
190    #[allow(dead_code)]
191    abar_virt: u64,
192    ports: Vec<AhciPort>,
193}
194
195// SAFETY: AhciController is only accessed behind SpinLock<Option<...>>
196unsafe impl Send for AhciController {}
197unsafe impl Sync for AhciController {}
198
199// ========== Per-port IRQ completion state ===========================================================
200// These statics are accessed from the IRQ handler without locks.
201// Indexed by port_num (0..32).
202
203/// AHCI ABAR virtual address : written once during init, read by IRQ handler.
204static AHCI_ABAR_VIRT: AtomicU64 = AtomicU64::new(0);
205
206/// PCI interrupt line used by this controller.
207pub static AHCI_IRQ_LINE: AtomicU8 = AtomicU8::new(0xFF);
208
209/// Per-port MMIO virtual addresses : written once during init.
210static PORT_VIRT: [AtomicU64; 32] = {
211    const INIT: AtomicU64 = AtomicU64::new(0);
212    [INIT; 32]
213};
214
215/// Per-port slot-0 completion flags : set by IRQ handler, cleared by consumer.
216static PORT_SLOT0_DONE: [AtomicBool; 32] = {
217    const INIT: AtomicBool = AtomicBool::new(false);
218    [INIT; 32]
219};
220
221/// Per-port slot-0 error flags : set by IRQ handler on task-file error.
222static PORT_SLOT0_ERROR: [AtomicBool; 32] = {
223    const INIT: AtomicBool = AtomicBool::new(false);
224    [INIT; 32]
225};
226
227/// Per-port wait queues : tasks block here while waiting for IRQ completion.
228static PORT_WQ: [WaitQueue; 32] = {
229    const INIT: WaitQueue = WaitQueue::new();
230    [INIT; 32]
231};
232
233// ========== Per-port async operation metadata  ====================================================================
234//
235// These statics bridge AHCI IRQ completions to the async I/O ring
236// subsystem.  Before issuing a command in async mode, the submit path
237// stores the ring_id / user_data / buffer address in the per-port
238// arrays below.  When the IRQ fires, `handle_interrupt()` reads them
239// back, pushes a CQE into the ring, and drops the DMA buffer.
240//
241// Only slot 0 is used (one in-flight op per port).
242
243/// Ring id to push the completion CQE into (0 = no async pending).
244static PORT_ASYNC_RING_ID: [AtomicU64; 32] = {
245    const INIT: AtomicU64 = AtomicU64::new(0);
246    [INIT; 32]
247};
248
249/// User-data token echoed in the completion CQE.
250static PORT_ASYNC_USER_DATA: [AtomicU64; 32] = {
251    const INIT: AtomicU64 = AtomicU64::new(0);
252    [INIT; 32]
253};
254
255/// User virtual address where read data must be copied (0 = write op).
256static PORT_ASYNC_BUF_VADDR: [AtomicU64; 32] = {
257    const INIT: AtomicU64 = AtomicU64::new(0);
258    [INIT; 32]
259};
260
261/// Number of bytes transferred.
262static PORT_ASYNC_LEN: [AtomicU32; 32] = {
263    const INIT: AtomicU32 = AtomicU32::new(0);
264    [INIT; 32]
265};
266
267/// Whether the in-flight async command is a write operation.
268static PORT_ASYNC_IS_WRITE: [AtomicBool; 32] = {
269    const INIT: AtomicBool = AtomicBool::new(false);
270    [INIT; 32]
271};
272
273/// Raw pointer to a leaked `Box<DmaBuffer>` held until IRQ completion.
274/// 0 means no buffer.  Freed inside `handle_interrupt()` via
275/// `Box::from_raw()`.
276static PORT_ASYNC_DMA_PTR: [AtomicU64; 32] = {
277    const INIT: AtomicU64 = AtomicU64::new(0);
278    [INIT; 32]
279};
280
281/// Whether an async operation is in-flight on this port's slot 0.
282static PORT_ASYNC_ACTIVE: [AtomicBool; 32] = {
283    const INIT: AtomicBool = AtomicBool::new(false);
284    [INIT; 32]
285};
286
287struct PendingAsyncReadCompletion {
288    ring_id: u64,
289    user_data: u64,
290    user_buf_vaddr: u64,
291    dma_buf: DmaBuffer,
292    len: usize,
293    result: i32,
294}
295
296static PENDING_ASYNC_READ_COMPLETIONS: SpinLock<Vec<PendingAsyncReadCompletion>> =
297    SpinLock::new(Vec::new());
298
299// ========== MMIO helpers ==============================
300
301/// Performs the rd32 operation.
302#[inline]
303unsafe fn rd32(base: u64, off: u64) -> u32 {
304    ptr::read_volatile((base + off) as *const u32)
305}
306
307/// Performs the wr32 operation.
308#[inline]
309unsafe fn wr32(base: u64, off: u64, val: u32) {
310    ptr::write_volatile((base + off) as *mut u32, val);
311}
312
313// ========== Port start/stop ====================
314
315/// Performs the port stop operation.
316fn port_stop(pvirt: u64) {
317    // SAFETY: pvirt is a valid MMIO virtual address for this port's registers
318    unsafe {
319        let mut cmd = rd32(pvirt, PORT_CMD);
320        cmd &= !(CMD_ST | CMD_FRE);
321        wr32(pvirt, PORT_CMD, cmd);
322        // Spec mandates waiting ≤ 500 ms for FR and CR to clear
323        for _ in 0..500_000u32 {
324            if rd32(pvirt, PORT_CMD) & (CMD_FR | CMD_CR) == 0 {
325                return;
326            }
327            core::hint::spin_loop();
328        }
329        log::warn!("AHCI: port stop timed out (port registers @ {:#x})", pvirt);
330    }
331}
332
333/// Performs the port start operation.
334fn port_start(pvirt: u64) {
335    // SAFETY: pvirt is a valid MMIO virtual address
336    unsafe {
337        // Ensure Command List Running is clear before asserting ST
338        let mut timeout = 500_000u32;
339        while rd32(pvirt, PORT_CMD) & CMD_CR != 0 {
340            timeout = timeout.saturating_sub(1);
341            if timeout == 0 {
342                log::warn!("AHCI: port start wait for CR clear timed out");
343                break;
344            }
345            core::hint::spin_loop();
346        }
347        let mut cmd = rd32(pvirt, PORT_CMD);
348        cmd |= CMD_FRE | CMD_ST;
349        wr32(pvirt, PORT_CMD, cmd);
350    }
351}
352
353/// Rebase port: assign our CLB/FB buffers then start the port.
354fn port_rebase(pvirt: u64, phys: u64) {
355    port_stop(pvirt);
356    // SAFETY: pvirt valid MMIO; phys is our allocated frame
357    unsafe {
358        let clb = phys + CLB_OFF;
359        let fb = phys + FB_OFF;
360        wr32(pvirt, PORT_CLB, (clb & 0xFFFF_FFFF) as u32);
361        wr32(pvirt, PORT_CLBU, (clb >> 32) as u32);
362        wr32(pvirt, PORT_FB, (fb & 0xFFFF_FFFF) as u32);
363        wr32(pvirt, PORT_FBU, (fb >> 32) as u32);
364        // Clear any stale interrupt/error status
365        wr32(pvirt, PORT_IS, 0xFFFF_FFFF);
366        wr32(pvirt, PORT_SERR, 0xFFFF_FFFF);
367    }
368    port_start(pvirt);
369}
370
371/// Enable interrupts for a port (DHRE = DMA completion, TFEE = errors).
372fn port_enable_irq(pvirt: u64) {
373    // SAFETY: pvirt is a valid MMIO port register address
374    unsafe {
375        wr32(pvirt, PORT_IE, PXIE_DHRE | PXIE_TFEE);
376    }
377}
378
379// ========== DMA buffer management ======================================================================
380//
381// Replaced the old `Bounce` hand-rolled struct with the kernel-wide
382// `DmaBuffer` abstraction
383// DmaBuffer pins frames, preventing the buddy allocator from recycling
384// them while a transfer is in flight, and automatically unpins on Drop.
385
386// ========== Command submission ==========
387//
388// Two completion strategies:
389//   1. Task context (current_task_id() is Some): IRQ + WaitQueue : the issuing
390//      task is blocked by the scheduler until the IRQ fires and wakes it.
391//   2. Boot context (no task yet): legacy busy-poll with timeout.
392
393/// Performs the submit cmd operation.
394fn submit_cmd(
395    port: &AhciPort,
396    lba: u64,
397    count: u16,
398    buf: &mut [u8],
399    write: bool,
400    ata_cmd: u8,
401) -> Result<(), AhciError> {
402    let nbytes = (count as usize) * SECTOR_SIZE;
403    if buf.len() < nbytes {
404        return Err(AhciError::BufferTooSmall);
405    }
406
407    // SAFETY: MMIO read to check device readiness
408    let tfd = unsafe { rd32(port.port_virt, PORT_TFD) };
409    if tfd & (TFD_BSY | TFD_DRQ) != 0 {
410        return Err(AhciError::Busy);
411    }
412
413    let dma_buf = DmaBuffer::alloc_for(
414        port.sbdf,
415        nbytes,
416        crate::hardware::iommu::DmaProt::READ_WRITE,
417    )
418    .map_err(|_| AhciError::Alloc)?;
419
420    if write {
421        // SAFETY: dma_buf virtual addr is valid for nbytes; buf.len() >= nbytes
422        unsafe {
423            ptr::copy_nonoverlapping(buf.as_ptr(), dma_buf.virt_addr() as *mut u8, nbytes);
424        }
425    }
426
427    let ctab_phys = port.mem_device + CTAB_OFF;
428    let cmdh_virt = port.mem_virt + CLB_OFF; // slot 0 = first 32 bytes of CLB
429    let ctab_virt = port.mem_virt + CTAB_OFF;
430
431    // SAFETY: cmdh_virt and ctab_virt point to our allocated frame (physically valid)
432    unsafe {
433        // --- Command header (slot 0, 32 bytes) ---
434        let h = cmdh_virt as *mut u8;
435        ptr::write_bytes(h, 0, 32);
436
437        // CFL = 5 (H2D FIS = 20 B = 5 DWORDs); W bit set for writes
438        let flags: u16 = 5u16 | (if write { 1 << 6 } else { 0 });
439        ptr::write_unaligned(h.add(CMDH_FLAGS) as *mut u16, flags.to_le());
440        ptr::write_unaligned(h.add(CMDH_PRDTL) as *mut u16, 1u16.to_le()); // 1 PRDT entry
441        ptr::write_unaligned(
442            h.add(CMDH_CTBA) as *mut u32,
443            (ctab_phys & 0xFFFF_FFFF) as u32,
444        );
445        ptr::write_unaligned(h.add(CMDH_CTBAU) as *mut u32, (ctab_phys >> 32) as u32);
446
447        // --- Command table ---
448        let t = ctab_virt as *mut u8;
449        ptr::write_bytes(t, 0, CTAB_PRDT + 16);
450
451        // H2D Register FIS (20 bytes at CFIS offset)
452        let f = t.add(CTAB_CFIS);
453        *f.add(FIS_TYPE) = FIS_TYPE_H2D;
454        *f.add(FIS_FLAGS) = FIS_C_BIT;
455        *f.add(FIS_CMD) = ata_cmd;
456        *f.add(FIS_LBA0) = (lba & 0xFF) as u8;
457        *f.add(FIS_LBA1) = ((lba >> 8) & 0xFF) as u8;
458        *f.add(FIS_LBA2) = ((lba >> 16) & 0xFF) as u8;
459        *f.add(FIS_DEVICE) = FIS_LBA_MODE; // LBA addressing, device 0
460        *f.add(FIS_LBA3) = ((lba >> 24) & 0xFF) as u8;
461        *f.add(FIS_LBA4) = ((lba >> 32) & 0xFF) as u8;
462        *f.add(FIS_LBA5) = ((lba >> 40) & 0xFF) as u8;
463        *f.add(FIS_CNT_LO) = (count & 0xFF) as u8;
464        *f.add(FIS_CNT_HI) = (count >> 8) as u8;
465
466        // PRDT entry 0 (16 bytes)
467        let p = t.add(CTAB_PRDT);
468        // DBA: device address of DMA buffer
469        let dma_phys = dma_buf.device_addr();
470        ptr::write_unaligned(p.add(0) as *mut u32, (dma_phys & 0xFFFF_FFFF) as u32);
471        ptr::write_unaligned(p.add(4) as *mut u32, (dma_phys >> 32) as u32);
472        ptr::write_unaligned(p.add(8) as *mut u32, 0u32);
473        // DBC: byte_count - 1; bit 31 = interrupt on completion
474        let dbc = ((nbytes as u32).saturating_sub(1)) | (1 << 31);
475        ptr::write_unaligned(p.add(12) as *mut u32, dbc);
476    }
477
478    issue_and_await_slot0(port)?;
479
480    if !write {
481        // SAFETY: dma_buf virtual addr valid, nbytes ≤ allocated
482        unsafe {
483            ptr::copy_nonoverlapping(dma_buf.virt_addr() as *const u8, buf.as_mut_ptr(), nbytes);
484        }
485    }
486    Ok(())
487}
488
489/// Issues the command already staged in slot 0 and waits for completion.
490///
491/// Shared by data commands and `FLUSH CACHE EXT` so both paths use exactly the
492/// same completion/error handling (IRQ wait in task context, bounded poll at
493/// boot).
494fn issue_and_await_slot0(port: &AhciPort) -> Result<(), AhciError> {
495    let idx = port.port_num as usize;
496
497    // Clear any stale completion state before issuing the command
498    PORT_SLOT0_DONE[idx].store(false, Ordering::Release);
499    PORT_SLOT0_ERROR[idx].store(false, Ordering::Release);
500
501    // Issue command in slot 0
502    // SAFETY: MMIO write to PxCI
503    unsafe { wr32(port.port_virt, PORT_CI, 1) };
504
505    // Completion strategy ================================================
506    if crate::process::current_task_id().is_some() {
507        // Task context: block until the IRQ handler signals DONE.
508        // WaitQueue::wait_until() atomically checks the condition under the
509        // waiters SpinLock (which disables IRQs via CLI), so the completion
510        // interrupt cannot be lost between the check and the block.
511        PORT_WQ[idx].wait_until(|| {
512            if PORT_SLOT0_DONE[idx].load(Ordering::Acquire) {
513                // Consume the flag atomically before returning
514                PORT_SLOT0_DONE[idx].store(false, Ordering::Release);
515                Some(())
516            } else {
517                None
518            }
519        });
520
521        // Check whether the IRQ reported an error
522        if PORT_SLOT0_ERROR[idx].load(Ordering::Acquire) {
523            return Err(AhciError::DeviceError);
524        }
525    } else {
526        // Boot context (no task): fall back to busy-poll with ≈5 s timeout.
527        let mut tries = 5_000_000u32;
528        loop {
529            // SAFETY: MMIO reads
530            let ci = unsafe { rd32(port.port_virt, PORT_CI) };
531            let is = unsafe { rd32(port.port_virt, PORT_IS) };
532
533            if is & PXIS_TFES != 0 {
534                // SAFETY: MMIO writes to clear error status
535                unsafe {
536                    wr32(port.port_virt, PORT_IS, 0xFFFF_FFFF);
537                    wr32(port.port_virt, PORT_SERR, 0xFFFF_FFFF);
538                }
539                return Err(AhciError::DeviceError);
540            }
541
542            if ci & 1 == 0 {
543                break; // slot 0 completed
544            }
545
546            tries = tries.saturating_sub(1);
547            if tries == 0 {
548                return Err(AhciError::Timeout);
549            }
550            core::hint::spin_loop();
551        }
552
553        // SAFETY: MMIO write to clear port interrupt status
554        unsafe { wr32(port.port_virt, PORT_IS, 0xFFFF_FFFF) };
555    }
556
557    Ok(())
558}
559
560/// Issues `FLUSH CACHE EXT` (0xEA) and waits for the device acknowledgement.
561///
562/// The command carries no payload, so the PRDT is empty (`PRDTL = 0`) and no
563/// DMA buffer is allocated. `fsync` must not report success before this
564/// returns, otherwise the write-back cache can still lose acknowledged writes.
565fn submit_flush(port: &AhciPort) -> Result<(), AhciError> {
566    // SAFETY: MMIO read to check device readiness
567    let tfd = unsafe { rd32(port.port_virt, PORT_TFD) };
568    if tfd & (TFD_BSY | TFD_DRQ) != 0 {
569        return Err(AhciError::Busy);
570    }
571
572    let ctab_phys = port.mem_device + CTAB_OFF;
573    let cmdh_virt = port.mem_virt + CLB_OFF; // slot 0 = first 32 bytes of CLB
574    let ctab_virt = port.mem_virt + CTAB_OFF;
575
576    // SAFETY: cmdh_virt and ctab_virt point to our allocated frame
577    unsafe {
578        let h = cmdh_virt as *mut u8;
579        ptr::write_bytes(h, 0, 32);
580
581        // CFL = 5 (H2D FIS = 20 B); W = 0: the device reads no data.
582        ptr::write_unaligned(h.add(CMDH_FLAGS) as *mut u16, 5u16.to_le());
583        ptr::write_unaligned(h.add(CMDH_PRDTL) as *mut u16, 0u16.to_le());
584        ptr::write_unaligned(
585            h.add(CMDH_CTBA) as *mut u32,
586            (ctab_phys & 0xFFFF_FFFF) as u32,
587        );
588        ptr::write_unaligned(h.add(CMDH_CTBAU) as *mut u32, (ctab_phys >> 32) as u32);
589
590        let t = ctab_virt as *mut u8;
591        ptr::write_bytes(t, 0, CTAB_PRDT + 16);
592
593        let f = t.add(CTAB_CFIS);
594        *f.add(FIS_TYPE) = FIS_TYPE_H2D;
595        *f.add(FIS_FLAGS) = FIS_C_BIT;
596        *f.add(FIS_CMD) = ATA_FLUSH_CACHE_EXT;
597        *f.add(FIS_DEVICE) = FIS_LBA_MODE;
598    }
599
600    issue_and_await_slot0(port)
601}
602
603// ========== Async command submission =======================================
604//
605// Non-blocking variant of `submit_cmd`.  Stores per-port async metadata
606// before issuing the command, so the IRQ handler can push a CQE directly
607// into the caller's async ring without any further kernel involvement.
608
609/// Submit a command asynchronously ; returns immediately without blocking.
610///
611/// The caller **must** have already set `PORT_ASYNC_ACTIVE[idx]` to `true`
612/// and stored the ring / user-data / buffer info in the per-port statics.
613///
614/// On success the operation is in-flight; the IRQ handler will deliver the
615/// CQE.  On failure (device busy, allocation error) the metadata is cleared
616/// and the caller must push an error CQE itself.
617fn submit_async_cmd(
618    port: &AhciPort,
619    lba: u64,
620    count: u16,
621    write: bool,
622    ata_cmd: u8,
623    dma_buf: DmaBuffer,
624) -> Result<(), AhciError> {
625    let nbytes = (count as usize) * SECTOR_SIZE;
626    let idx = port.port_num as usize;
627
628    // SAFETY: MMIO read to check device readiness
629    let tfd = unsafe { rd32(port.port_virt, PORT_TFD) };
630    if tfd & (TFD_BSY | TFD_DRQ) != 0 {
631        return Err(AhciError::Busy);
632    }
633
634    // For writes: copy user data into the DMA buffer before issuing
635    if write {
636        let user_vaddr = PORT_ASYNC_BUF_VADDR[idx].load(Ordering::Acquire);
637        if user_vaddr != 0 {
638            // SAFETY: user buffer vaddr was validated at dispatch time,
639            // nbytes ≤ allocated DMA buffer capacity.
640            unsafe {
641                ptr::copy_nonoverlapping(
642                    user_vaddr as *const u8,
643                    dma_buf.virt_addr() as *mut u8,
644                    nbytes,
645                );
646            }
647        }
648    }
649
650    let ctab_phys = port.mem_device + CTAB_OFF;
651    let cmdh_virt = port.mem_virt + CLB_OFF;
652    let ctab_virt = port.mem_virt + CTAB_OFF;
653
654    // SAFETY: all addresses point into our pre-allocated per-port frame.
655    unsafe {
656        // --- Command header (slot 0, 32 bytes) ---
657        let h = cmdh_virt as *mut u8;
658        ptr::write_bytes(h, 0, 32);
659
660        let flags: u16 = 5u16 | (if write { 1 << 6 } else { 0 });
661        ptr::write_unaligned(h.add(CMDH_FLAGS) as *mut u16, flags.to_le());
662        ptr::write_unaligned(h.add(CMDH_PRDTL) as *mut u16, 1u16.to_le());
663        ptr::write_unaligned(
664            h.add(CMDH_CTBA) as *mut u32,
665            (ctab_phys & 0xFFFF_FFFF) as u32,
666        );
667        ptr::write_unaligned(h.add(CMDH_CTBAU) as *mut u32, (ctab_phys >> 32) as u32);
668
669        // --- Command table ---
670        let t = ctab_virt as *mut u8;
671        ptr::write_bytes(t, 0, CTAB_PRDT + 16);
672
673        // H2D Register FIS
674        let f = t.add(CTAB_CFIS);
675        *f.add(FIS_TYPE) = FIS_TYPE_H2D;
676        *f.add(FIS_FLAGS) = FIS_C_BIT;
677        *f.add(FIS_CMD) = ata_cmd;
678        *f.add(FIS_LBA0) = (lba & 0xFF) as u8;
679        *f.add(FIS_LBA1) = ((lba >> 8) & 0xFF) as u8;
680        *f.add(FIS_LBA2) = ((lba >> 16) & 0xFF) as u8;
681        *f.add(FIS_DEVICE) = FIS_LBA_MODE;
682        *f.add(FIS_LBA3) = ((lba >> 24) & 0xFF) as u8;
683        *f.add(FIS_LBA4) = ((lba >> 32) & 0xFF) as u8;
684        *f.add(FIS_LBA5) = ((lba >> 40) & 0xFF) as u8;
685        *f.add(FIS_CNT_LO) = (count & 0xFF) as u8;
686        *f.add(FIS_CNT_HI) = (count >> 8) as u8;
687
688        // PRDT entry 0 (16 bytes)
689        let p = t.add(CTAB_PRDT);
690        let dma_phys = dma_buf.device_addr();
691        ptr::write_unaligned(p.add(0) as *mut u32, (dma_phys & 0xFFFF_FFFF) as u32);
692        ptr::write_unaligned(p.add(4) as *mut u32, (dma_phys >> 32) as u32);
693        ptr::write_unaligned(p.add(8) as *mut u32, 0u32);
694        let dbc = ((nbytes as u32).saturating_sub(1)) | (1 << 31);
695        ptr::write_unaligned(p.add(12) as *mut u32, dbc);
696    }
697
698    // Leak the DmaBuffer so it stays alive until the IRQ consumes it.
699    let dma_ptr = Box::into_raw(Box::new(dma_buf));
700    PORT_ASYNC_DMA_PTR[idx].store(dma_ptr as u64, Ordering::Release);
701
702    // Clear stale flags and issue the command
703    PORT_SLOT0_DONE[idx].store(false, Ordering::Release);
704    PORT_SLOT0_ERROR[idx].store(false, Ordering::Release);
705
706    // SAFETY: MMIO write to PxCI issues slot 0
707    unsafe { wr32(port.port_virt, PORT_CI, 1) };
708
709    Ok(())
710}
711
712/// Public entry point called from `async_io::dispatch`.
713///
714/// Validates the port index, looks up the AHCI device, allocates a DMA
715/// buffer, stores async metadata, and issues the command.
716///
717/// On success the caller should increment the ring's in-flight counter.
718/// On failure an error CQE is returned so dispatch can push it immediately.
719#[allow(dead_code)]
720pub(crate) fn submit_async_storage_op(
721    port_idx: u8,
722    lba: u64,
723    byte_count: u32,
724    user_buf_vaddr: u64,
725    write: bool,
726    ring_id: u64,
727    user_data: u64,
728) -> Result<(), AhciError> {
729    let controller = get_device().ok_or(AhciError::NoController)?;
730    let port = controller.port_by_num(port_idx).ok_or(AhciError::NoPort)?;
731
732    if lba >= port.sector_count {
733        return Err(AhciError::InvalidSector);
734    }
735
736    let count = ((byte_count as usize + SECTOR_SIZE - 1) / SECTOR_SIZE) as u16;
737    if count == 0 {
738        return Err(AhciError::BufferTooSmall);
739    }
740    let nbytes = (count as usize) * SECTOR_SIZE;
741
742    if write {
743        UserSliceRead::new(user_buf_vaddr, nbytes).map_err(|_| AhciError::InvalidUserBuffer)?;
744    } else {
745        UserSliceWrite::new(user_buf_vaddr, nbytes).map_err(|_| AhciError::InvalidUserBuffer)?;
746    }
747
748    let dma_buf = DmaBuffer::alloc_for(
749        port.sbdf,
750        nbytes,
751        crate::hardware::iommu::DmaProt::READ_WRITE,
752    )
753    .map_err(|_| AhciError::Alloc)?;
754
755    let idx = port.port_num as usize;
756    let ata_cmd = if write {
757        ATA_WRITE_DMA_EXT
758    } else {
759        ATA_READ_DMA_EXT
760    };
761
762    // Store async metadata *before* issuing the command.
763    PORT_ASYNC_RING_ID[idx].store(ring_id, Ordering::Release);
764    PORT_ASYNC_USER_DATA[idx].store(user_data, Ordering::Release);
765    PORT_ASYNC_BUF_VADDR[idx].store(user_buf_vaddr, Ordering::Release);
766    PORT_ASYNC_LEN[idx].store(nbytes as u32, Ordering::Release);
767    PORT_ASYNC_IS_WRITE[idx].store(write, Ordering::Release);
768    PORT_ASYNC_ACTIVE[idx].store(true, Ordering::Release);
769
770    match submit_async_cmd(port, lba, count, write, ata_cmd, dma_buf) {
771        Ok(()) => Ok(()),
772        Err(e) => {
773            // Roll back async metadata on submission failure.
774            PORT_ASYNC_ACTIVE[idx].store(false, Ordering::Release);
775            PORT_ASYNC_RING_ID[idx].store(0, Ordering::Release);
776            PORT_ASYNC_USER_DATA[idx].store(0, Ordering::Release);
777            PORT_ASYNC_BUF_VADDR[idx].store(0, Ordering::Release);
778            PORT_ASYNC_LEN[idx].store(0, Ordering::Release);
779            PORT_ASYNC_IS_WRITE[idx].store(false, Ordering::Release);
780            PORT_ASYNC_DMA_PTR[idx].store(0, Ordering::Release);
781            Err(e)
782        }
783    }
784}
785
786pub(crate) fn flush_deferred_async_read_completions(ring_id: u64) -> u32 {
787    let Some(task) = crate::process::current_task_clone() else {
788        return 0;
789    };
790    let Some(ring) = crate::async_io::ring::find_ring(ring_id) else {
791        return discard_deferred_async_read_completions(ring_id);
792    };
793    if ring.owner_pid != task.pid {
794        return 0;
795    }
796    // If the ring was destroyed, discard all deferred reads for it rather
797    // than trying to push completions into a dead ring.
798    if ring.destroyed.load(core::sync::atomic::Ordering::Acquire) != 0 {
799        return discard_deferred_async_read_completions(ring_id);
800    }
801
802    let pending = {
803        let mut guard = PENDING_ASYNC_READ_COMPLETIONS.lock();
804        // Extract only entries for this ring_id; leave others in place
805        // (avoids the allocate + deallocate overhead of take + put-back).
806        let mut pending = Vec::new();
807        let mut i = 0;
808        while i < guard.len() {
809            if guard[i].ring_id == ring_id {
810                // swap_remove is O(1); completion ordering across rings
811                // is not guaranteed to userspace.
812                pending.push(guard.swap_remove(i));
813            } else {
814                i += 1;
815            }
816        }
817        pending
818    };
819
820    let mut flushed = 0;
821
822    for mut completion in pending {
823        // All entries in `pending` belong to `ring_id` (extracted by retain above).
824
825        if completion.result >= 0 {
826            completion.result = match UserSliceWrite::new(completion.user_buf_vaddr, completion.len)
827            {
828                Ok(user_buf) => {
829                    /*
830                    Original code before assembly TEST
831                                  let src = unsafe {
832                                            core::slice::from_raw_parts(
833                                                completion.dma_buf.virt_addr() as *const u8,
834                                                completion.len,
835                                            )
836                                        };
837                                        user_buf.copy_from(src);
838
839                    */
840
841                    let src = completion.dma_buf.virt_addr() as *const u8;
842                    let dst = user_buf.as_ptr() as *mut u8;
843                    let n = completion.len;
844
845                    if n >= 128 {
846                        // Fast path for sector-aligned copies: rep movsb on
847                        // x86-64 (ERMSB/FSRM), plain copy elsewhere.
848                        #[cfg(target_arch = "x86_64")]
849                        unsafe {
850                            core::arch::asm!(
851                                "rep movsb",
852                                inout("rcx") n => _,
853                                inout("rsi") src => _,
854                                inout("rdi") dst => _,
855                                options(nostack),
856                            );
857                        }
858                        #[cfg(not(target_arch = "x86_64"))]
859                        user_buf
860                            .copy_from(unsafe { core::slice::from_raw_parts(src, completion.len) });
861                    } else {
862                        user_buf
863                            .copy_from(unsafe { core::slice::from_raw_parts(src, completion.len) });
864                    }
865                    completion.len as i32
866                }
867                Err(_) => EFAULT,
868            };
869        }
870
871        if crate::async_io::complete::push_completion_for_ring(
872            &ring,
873            completion.user_data,
874            completion.result,
875            0,
876        ) {
877            flushed += 1;
878        } else {
879            // Ring was destroyed between our check and the push : drop silently.
880        }
881    }
882
883    flushed
884}
885
886pub(crate) fn discard_deferred_async_read_completions(ring_id: u64) -> u32 {
887    let mut guard = PENDING_ASYNC_READ_COMPLETIONS.lock();
888    let before = guard.len();
889    guard.retain(|completion| completion.ring_id != ring_id);
890    (before - guard.len()) as u32
891}
892
893// ========== IRQ handler ==============================
894
895/// Called from the IDT AHCI IRQ handler.
896///
897/// Reads `HBA_IS` to find which ports raised an interrupt, reads and clears
898/// `PxIS` per port, then signals the per-port `WaitQueue` so that any task
899/// blocked in `submit_cmd` can resume.
900///
901/// # Safety of concurrent access
902/// All per-port statics (`PORT_SLOT0_DONE`, `PORT_SLOT0_ERROR`, `PORT_WQ`) are
903/// accessed via atomics or briefly-held SpinLocks (which disable IRQs).  The
904/// IRQ handler itself is not re-entrant (x86 APIC level-triggered delivery
905/// ensures this for the same vector).
906pub fn handle_interrupt() {
907    let abar = AHCI_ABAR_VIRT.load(Ordering::Relaxed);
908    if abar == 0 {
909        return; // controller not yet initialised
910    }
911
912    // SAFETY: abar is the MMIO-mapped AHCI base set during init
913    let global_is = unsafe { rd32(abar, HBA_IS) };
914    if global_is == 0 {
915        return; // spurious
916    }
917
918    for port_num in 0..32u8 {
919        if global_is & (1 << port_num) == 0 {
920            continue;
921        }
922
923        let pvirt = PORT_VIRT[port_num as usize].load(Ordering::Relaxed);
924        if pvirt == 0 {
925            continue; // port not in use
926        }
927
928        // SAFETY: pvirt is the valid MMIO address for this port, set during init
929        let pxis = unsafe { rd32(pvirt, PORT_IS) };
930
931        // Determine outcome and record in the error flag
932        if pxis & PXIS_TFES != 0 {
933            PORT_SLOT0_ERROR[port_num as usize].store(true, Ordering::Release);
934            // SAFETY: MMIO writes to clear error state
935            unsafe {
936                wr32(pvirt, PORT_IS, pxis);
937                wr32(pvirt, PORT_SERR, 0xFFFF_FFFF);
938            }
939        } else {
940            PORT_SLOT0_ERROR[port_num as usize].store(false, Ordering::Release);
941            // SAFETY: W1C : write back PxIS to clear all set bits
942            unsafe { wr32(pvirt, PORT_IS, pxis) };
943        }
944
945        // Clear this port's bit in global IS (W1C)
946        // SAFETY: MMIO write to HBA_IS
947        unsafe { wr32(abar, HBA_IS, 1 << port_num) };
948
949        // Signal command completion (always, for sync waiters)
950        PORT_SLOT0_DONE[port_num as usize].store(true, Ordering::Release);
951
952        // Async path : if an async operation was in-flight on this port,
953        // push a CQE into the registered ring and drop the DMA buffer.
954        let idx = port_num as usize;
955        if PORT_ASYNC_ACTIVE[idx].load(Ordering::Acquire) {
956            let ring_id = PORT_ASYNC_RING_ID[idx].load(Ordering::Acquire);
957            let user_data = PORT_ASYNC_USER_DATA[idx].load(Ordering::Acquire);
958            let buf_vaddr = PORT_ASYNC_BUF_VADDR[idx].load(Ordering::Acquire);
959            let nbytes = PORT_ASYNC_LEN[idx].load(Ordering::Acquire) as usize;
960            let is_write = PORT_ASYNC_IS_WRITE[idx].load(Ordering::Acquire);
961            let dma_ptr_val = PORT_ASYNC_DMA_PTR[idx].load(Ordering::Acquire);
962
963            // Clear the active flag : this port is now idle.
964            PORT_ASYNC_ACTIVE[idx].store(false, Ordering::Release);
965            PORT_ASYNC_RING_ID[idx].store(0, Ordering::Release);
966            PORT_ASYNC_USER_DATA[idx].store(0, Ordering::Release);
967            PORT_ASYNC_BUF_VADDR[idx].store(0, Ordering::Release);
968            PORT_ASYNC_LEN[idx].store(0, Ordering::Release);
969            PORT_ASYNC_IS_WRITE[idx].store(false, Ordering::Release);
970            PORT_ASYNC_DMA_PTR[idx].store(0, Ordering::Release);
971
972            if dma_ptr_val != 0 {
973                // Take ownership of the leaked DmaBuffer back.
974                let dma_buf = unsafe { *Box::from_raw(dma_ptr_val as *mut DmaBuffer) };
975
976                let result = if PORT_SLOT0_ERROR[idx].load(Ordering::Acquire) {
977                    -5i32 // EIO
978                } else {
979                    nbytes as i32
980                };
981
982                if is_write || result < 0 {
983                    crate::async_io::complete::push_completion(ring_id, user_data, result, 0);
984                } else {
985                    PENDING_ASYNC_READ_COMPLETIONS
986                        .lock()
987                        .push(PendingAsyncReadCompletion {
988                            ring_id,
989                            user_data,
990                            user_buf_vaddr: buf_vaddr,
991                            dma_buf,
992                            len: nbytes,
993                            result,
994                        });
995
996                    if let Some(ring) = crate::async_io::ring::find_ring(ring_id) {
997                        ring.wq.wake_all();
998                    }
999                }
1000            }
1001        } else {
1002            PORT_WQ[idx].wake_one();
1003        }
1004    }
1005}
1006
1007// ========== BlockDevice impl for AhciController ========================================================================================================================
1008
1009impl AhciController {
1010    fn port_by_num(&self, port_num: u8) -> Option<&AhciPort> {
1011        self.ports.iter().find(|port| port.port_num == port_num)
1012    }
1013
1014    /// Probe and initialise an AHCI controller from the PCI bus.
1015    ///
1016    /// # Safety
1017    /// Must be called once during single-threaded kernel init (MMIO mapping).
1018    pub unsafe fn init() -> Result<Self, AhciError> {
1019        // AHCI: class=0x01, subclass=0x06 (SATA), prog_if=0x01 (AHCI 1.0)
1020        let pci_dev = pci::probe_first(ProbeCriteria {
1021            class_code: Some(pci::class::MASS_STORAGE),
1022            subclass: Some(pci::storage_subclass::SATA),
1023            prog_if: Some(pci::sata_progif::AHCI),
1024            ..ProbeCriteria::any()
1025        })
1026        .ok_or(AhciError::NoController)?;
1027
1028        log::info!("AHCI: found controller at {:?}", pci_dev.address);
1029
1030        // Enable bus-mastering and memory-space access (required for DMA)
1031        pci_dev.enable_bus_master();
1032        pci_dev.enable_memory_space();
1033
1034        // Try MSI/MSI-X first; fall back to INTx line.
1035        #[cfg(target_arch = "x86_64")]
1036        let (_irq_line, irq_vector) = crate::arch::x86_64::msi::probe_and_enable(&pci_dev, true);
1037        #[cfg(target_arch = "riscv64")]
1038        let irq_vector = 0;
1039
1040        // BAR5 = ABAR (AHCI Base Memory Register)
1041        let abar_phys = pci_dev.read_bar_raw(5).ok_or(AhciError::BadAbar)?;
1042        if abar_phys == 0 {
1043            return Err(AhciError::BadAbar);
1044        }
1045
1046        // Map the entire HBA register space (0x100 + 32 ports * 0x80 = 0x1100 bytes)
1047        crate::memory::paging::ensure_identity_map_range(abar_phys, 0x1200);
1048        let abar_virt = phys_to_virt(abar_phys);
1049
1050        // SAFETY: abar_virt is now a mapped MMIO virtual address
1051        // Enable AHCI mode
1052        let ghc = rd32(abar_virt, HBA_GHC);
1053        if ghc & GHC_AE == 0 {
1054            wr32(abar_virt, HBA_GHC, ghc | GHC_AE);
1055        }
1056
1057        // Perform HBA reset sequence (HR), then re-enable AHCI.
1058        let mut ghc_after = rd32(abar_virt, HBA_GHC) | GHC_AE;
1059        wr32(abar_virt, HBA_GHC, ghc_after | GHC_HR);
1060        let mut reset_timeout = 1_000_000u32;
1061        while rd32(abar_virt, HBA_GHC) & GHC_HR != 0 {
1062            reset_timeout = reset_timeout.saturating_sub(1);
1063            if reset_timeout == 0 {
1064                log::warn!("AHCI: HBA reset timed out, continuing with current state");
1065                break;
1066            }
1067            core::hint::spin_loop();
1068        }
1069        ghc_after = rd32(abar_virt, HBA_GHC) | GHC_AE;
1070        wr32(abar_virt, HBA_GHC, ghc_after);
1071        // Clear global pending interrupts before per-port setup.
1072        wr32(abar_virt, HBA_IS, 0xFFFF_FFFF);
1073
1074        log::debug!(
1075            "AHCI: ABAR phys={:#x} virt={:#x}  GHC={:#010x}",
1076            abar_phys,
1077            abar_virt,
1078            rd32(abar_virt, HBA_GHC)
1079        );
1080
1081        let pi = rd32(abar_virt, HBA_PI); // bitmask of implemented ports
1082        log::debug!("AHCI: ports implemented mask = {:#010x}", pi);
1083
1084        let mut ports: Vec<AhciPort> = Vec::new();
1085
1086        for port_num in 0..32u8 {
1087            if pi & (1 << port_num) == 0 {
1088                continue;
1089            }
1090
1091            let pvirt = abar_virt + 0x100 + (port_num as u64) * 0x80;
1092
1093            // Check DET: only accept DET=3 (device present + communication)
1094            let ssts = rd32(pvirt, PORT_SSTS);
1095            let det = ssts & SSTS_DET_MASK;
1096            if det != SSTS_DET_COMM {
1097                log::debug!("AHCI: port {} DET={} : no device, skipping", port_num, det);
1098                continue;
1099            }
1100
1101            // Only handle plain SATA (signature 0x00000101)
1102            let sig = rd32(pvirt, PORT_SIG);
1103            if sig != SIG_SATA {
1104                log::debug!(
1105                    "AHCI: port {} sig={:#010x} : not plain SATA, skipping",
1106                    port_num,
1107                    sig
1108                );
1109                continue;
1110            }
1111
1112            // Allocate one 4 KB frame for CLB + FIS + CTAB
1113            let frame = crate::sync::with_irqs_disabled(|token| memory::allocate_frame(token))
1114                .map_err(|_| AhciError::Alloc)?;
1115
1116            let mem_phys = frame.start_address.as_u64();
1117            let mem_virt = phys_to_virt(mem_phys);
1118
1119            // Zero the frame so HBA sees clean structures
1120            // SAFETY: mem_virt is valid HHDM-mapped physical memory, 4096 bytes
1121            ptr::write_bytes(mem_virt as *mut u8, 0, 4096);
1122
1123            let sbdf = crate::hardware::iommu::Sbdf::new(
1124                0,
1125                pci_dev.address.bus,
1126                pci_dev.address.device,
1127                pci_dev.address.function,
1128            );
1129            let mapper = crate::dma::DmaMapper::for_sbdf(sbdf);
1130            let mem_device =
1131                mapper.translate(mem_phys, 4096, crate::hardware::iommu::DmaProt::READ_WRITE);
1132
1133            port_rebase(pvirt, mem_device);
1134
1135            // Enable per-port interrupts (DHRE + TFEE)
1136            port_enable_irq(pvirt);
1137
1138            // Register this port's MMIO address in the per-port static table
1139            // so the IRQ handler can access it without holding the controller lock.
1140            PORT_VIRT[port_num as usize].store(pvirt, Ordering::Relaxed);
1141
1142            // Identify device to read sector count
1143            let mut port = AhciPort {
1144                port_num,
1145                port_virt: pvirt,
1146                mem_phys,
1147                mem_virt,
1148                mem_device,
1149                sbdf,
1150                sector_count: 0,
1151            };
1152
1153            let mut id_buf = [0u8; SECTOR_SIZE];
1154            match submit_cmd(&port, 0, 1, &mut id_buf, false, ATA_IDENTIFY) {
1155                Ok(()) => {
1156                    // Words 100-103 (bytes 200-207): 48-bit LBA native max address
1157                    let w0 = u16::from_le_bytes([id_buf[200], id_buf[201]]) as u64;
1158                    let w1 = u16::from_le_bytes([id_buf[202], id_buf[203]]) as u64;
1159                    let w2 = u16::from_le_bytes([id_buf[204], id_buf[205]]) as u64;
1160                    let w3 = u16::from_le_bytes([id_buf[206], id_buf[207]]) as u64;
1161                    port.sector_count = w0 | (w1 << 16) | (w2 << 32) | (w3 << 48);
1162                    log::info!(
1163                        "AHCI: port {} SATA : {} sectors ({} MiB)",
1164                        port_num,
1165                        port.sector_count,
1166                        (port.sector_count * SECTOR_SIZE as u64) / (1024 * 1024)
1167                    );
1168                }
1169                Err(e) => {
1170                    log::warn!("AHCI: port {} IDENTIFY failed: {}", port_num, e);
1171                }
1172            }
1173
1174            ports.push(port);
1175        }
1176
1177        if ports.is_empty() {
1178            return Err(AhciError::NoPort);
1179        }
1180
1181        // Store the ABAR virtual address and IRQ line in statics so the
1182        // interrupt handler can reach them without going through the controller lock.
1183        AHCI_ABAR_VIRT.store(abar_virt, Ordering::Relaxed);
1184        AHCI_IRQ_LINE.store(irq_vector, Ordering::Relaxed);
1185
1186        // Enable global HBA interrupts (GHC.IE)
1187        // SAFETY: MMIO write : all port interrupts already enabled above
1188        let ghc = rd32(abar_virt, HBA_GHC);
1189        wr32(abar_virt, HBA_GHC, ghc | GHC_IE);
1190
1191        log::info!("AHCI: global interrupts enabled (vector {:#x})", irq_vector);
1192
1193        Ok(AhciController { abar_virt, ports })
1194    }
1195
1196    /// Return sector count of the first port.
1197    pub fn sector_count(&self) -> u64 {
1198        self.ports.first().map(|p| p.sector_count).unwrap_or(0)
1199    }
1200
1201    /// Return the logical port number of the first usable port.
1202    pub fn first_port_num(&self) -> Option<u8> {
1203        self.ports.first().map(|port| port.port_num)
1204    }
1205
1206    /// Performs the first port operation.
1207    fn first_port(&self) -> Option<&AhciPort> {
1208        self.ports.first()
1209    }
1210}
1211
1212#[cfg(test)]
1213mod tests {
1214    use super::{AhciController, AhciPort};
1215    use alloc::vec;
1216
1217    fn fake_port(port_num: u8) -> AhciPort {
1218        AhciPort {
1219            port_num,
1220            port_virt: 0,
1221            mem_phys: 0,
1222            mem_virt: 0,
1223            mem_device: 0,
1224            sbdf: crate::hardware::iommu::Sbdf::from_pci(0, 0, 0),
1225            sector_count: 1024,
1226        }
1227    }
1228
1229    #[test]
1230    fn selects_requested_port_number() {
1231        let controller = AhciController {
1232            abar_virt: 0,
1233            ports: vec![fake_port(2), fake_port(5), fake_port(7)],
1234            dma_pool: None,
1235        };
1236
1237        assert_eq!(controller.port_by_num(5).map(|port| port.port_num), Some(5));
1238        assert_eq!(controller.port_by_num(1).map(|port| port.port_num), None);
1239        assert_eq!(controller.first_port_num(), Some(2));
1240    }
1241}
1242
1243impl BlockDevice for AhciController {
1244    /// Reads sector.
1245    fn read_sector(&self, sector: u64, buf: &mut [u8]) -> Result<(), BlockError> {
1246        let port = self.first_port().ok_or(BlockError::NotReady)?;
1247        if sector >= port.sector_count {
1248            return Err(BlockError::InvalidSector);
1249        }
1250        if buf.len() < SECTOR_SIZE {
1251            return Err(BlockError::BufferTooSmall);
1252        }
1253        submit_cmd(port, sector, 1, buf, false, ATA_READ_DMA_EXT).map_err(|_| BlockError::IoError)
1254    }
1255
1256    /// Writes sector.
1257    fn write_sector(&self, sector: u64, buf: &[u8]) -> Result<(), BlockError> {
1258        let port = self.first_port().ok_or(BlockError::NotReady)?;
1259        if sector >= port.sector_count {
1260            return Err(BlockError::InvalidSector);
1261        }
1262        if buf.len() < SECTOR_SIZE {
1263            return Err(BlockError::BufferTooSmall);
1264        }
1265        // submit_cmd copies the data into a DMA buffer before issuing the
1266        // command, so the const-to-mut cast is safe (the buffer is never
1267        // written from the CPU side during a write request).
1268        let buf_mut = buf.as_ptr() as *mut u8;
1269        let buf_slice = unsafe { core::slice::from_raw_parts_mut(buf_mut, buf.len()) };
1270        submit_cmd(port, sector, 1, buf_slice, true, ATA_WRITE_DMA_EXT)
1271            .map_err(|_| BlockError::IoError)
1272    }
1273
1274    /// Read multiple sectors in a single ATA command.
1275    ///
1276    /// AHCI `submit_cmd` already accepts a `count: u16` parameter;
1277    /// this override uses it directly instead of looping per sector.
1278    fn read_sectors(&self, sector: u64, count: u16, buf: &mut [u8]) -> Result<(), BlockError> {
1279        let port = self.first_port().ok_or(BlockError::NotReady)?;
1280        let nbytes = (count as usize) * SECTOR_SIZE;
1281        if sector.saturating_add(count as u64) > port.sector_count {
1282            return Err(BlockError::InvalidSector);
1283        }
1284        if buf.len() < nbytes {
1285            return Err(BlockError::BufferTooSmall);
1286        }
1287        submit_cmd(port, sector, count, buf, false, ATA_READ_DMA_EXT)
1288            .map_err(|_| BlockError::IoError)
1289    }
1290
1291    /// Write multiple sectors in a single ATA command.
1292    fn write_sectors(&self, sector: u64, count: u16, buf: &[u8]) -> Result<(), BlockError> {
1293        let port = self.first_port().ok_or(BlockError::NotReady)?;
1294        let nbytes = (count as usize) * SECTOR_SIZE;
1295        if sector.saturating_add(count as u64) > port.sector_count {
1296            return Err(BlockError::InvalidSector);
1297        }
1298        if buf.len() < nbytes {
1299            return Err(BlockError::BufferTooSmall);
1300        }
1301        // submit_cmd copies the data into a DMA buffer before issuing the
1302        // command, so the const-to-mut cast is safe.
1303        let buf_mut = buf.as_ptr() as *mut u8;
1304        let buf_slice = unsafe { core::slice::from_raw_parts_mut(buf_mut, buf.len()) };
1305        submit_cmd(port, sector, count, buf_slice, true, ATA_WRITE_DMA_EXT)
1306            .map_err(|_| BlockError::IoError)
1307    }
1308
1309    /// Performs the sector count operation.
1310    fn sector_count(&self) -> u64 {
1311        self.sector_count()
1312    }
1313
1314    /// Flushes the drive's volatile write cache (`FLUSH CACHE EXT`, 0xEA).
1315    fn flush(&self) -> Result<(), BlockError> {
1316        let port = self.first_port().ok_or(BlockError::NotReady)?;
1317        submit_flush(port).map_err(|_| BlockError::IoError)
1318    }
1319}
1320
1321// ========== Global singleton + public API ============================================================================================================================================
1322
1323/// Leaked-Box pointer to the AHCI controller (valid for 'static).
1324static AHCI_PTR: core::sync::atomic::AtomicPtr<AhciController> =
1325    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());
1326
1327/// Set once the bus has been scanned, whether or not a controller was found.
1328static AHCI_PROBED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
1329
1330/// Scan the PCI bus for an AHCI controller and initialise it.
1331///
1332/// Idempotent: the component `storage_init` runs after `hardware::init()`.
1333/// The guard is a flag rather than a check on `AHCI_PTR` because a failed
1334/// probe legitimately leaves the pointer null and must not be retried.
1335pub fn init() {
1336    if AHCI_PROBED.swap(true, core::sync::atomic::Ordering::AcqRel) {
1337        return;
1338    }
1339    log::info!("AHCI: scanning PCI bus...");
1340
1341    match unsafe { AhciController::init() } {
1342        Ok(ctrl) => {
1343            let leaked: &'static mut AhciController = Box::leak(Box::new(ctrl));
1344            AHCI_PTR.store(leaked as *mut AhciController, Ordering::Release);
1345            log::info!("AHCI: controller ready");
1346
1347            // Register IRQ handler in the IDT now that the controller is live.
1348            let vector = AHCI_IRQ_LINE.load(Ordering::Relaxed);
1349            #[cfg(target_arch = "x86_64")]
1350            crate::arch::x86_64::idt::register_ahci_irq(vector);
1351        }
1352        Err(AhciError::NoController) => {
1353            log::info!("AHCI: no controller found (not a SATA system?)");
1354        }
1355        Err(e) => {
1356            log::error!("AHCI: init failed: {}", e);
1357        }
1358    }
1359}
1360
1361/// Return a reference to the first usable AHCI controller, if any.
1362pub fn get_device() -> Option<&'static AhciController> {
1363    let ptr = AHCI_PTR.load(Ordering::Acquire);
1364    if ptr.is_null() {
1365        None
1366    } else {
1367        // SAFETY: ptr was obtained from Box::leak, valid for 'static.
1368        Some(unsafe { &*ptr })
1369    }
1370}