Skip to main content

strat9_kernel/hardware/storage/
nvme.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// NVMe block device driver
24// Reference: NVM Express Base Specification 2.0
25//
26// Features:
27// - Controller initialization and admin queue
28// - I/O queue pair with IRQ-driven completion
29// - NVMe read (opcode 0x02) and write (opcode 0x01) commands
30// - WaitQueue-based synchronous I/O
31// - Namespace identification
32
33#![allow(dead_code)]
34
35use crate::{
36    arch::boot_timestamp,
37    hardware::pci_client::{self as pci, Bar, ProbeCriteria},
38    memory::{allocate_zeroed_frame, paging, phys_to_virt},
39    sync::{waitqueue::WaitQueue, SpinLock},
40};
41use alloc::{boxed::Box, format, string::String, sync::Arc, vec::Vec};
42use core::{
43    ptr,
44    sync::atomic::{AtomicBool, AtomicU8, Ordering},
45};
46
47const NVME_PAGE_SIZE: usize = 4096;
48const IO_QUEUE_SIZE: usize = 64;
49const MAX_IO_COMMANDS: usize = IO_QUEUE_SIZE;
50/// Upper bound on blocks per I/O command, bounding the contiguous DMA
51/// allocation (128 blocks = 64 KiB at 512 B, 512 KiB at 4 KiB).
52const MAX_TRANSFER_BLOCKS: usize = 128;
53const MAX_PRP_ENTRIES: usize = NVME_PAGE_SIZE / 8; // 512 entries per PRP list page
54
55const ADMIN_CQE_ERROR: u16 = (0x1 << 14) | (0x1 << 10);
56
57// =========================================================================
58// TSC-based timeout helpers
59// =========================================================================
60
61/// Read the TSC (Time Stamp Counter).
62#[inline]
63fn rdtsc() -> u64 {
64    crate::arch::rdtsc()
65}
66
67/// Return the calibrated TSC frequency in KHz, or a fallback (3 GHz).
68fn tsc_khz() -> u64 {
69    let khz = boot_timestamp::tsc_khz();
70    if khz > 0 {
71        khz
72    } else {
73        3_000_000
74    }
75}
76
77/// Convert TSC ticks to approximate milliseconds using calibrated frequency.
78fn tsc_to_ms(ticks: u64) -> u64 {
79    ticks / tsc_khz()
80}
81
82/// Get a TSC deadline for `ms` milliseconds from now.
83fn tsc_deadline_ms(ms: u32) -> u64 {
84    rdtsc().wrapping_add((ms as u64) * tsc_khz())
85}
86
87/// Check if a TSC deadline has expired.
88fn tsc_expired(deadline: u64) -> bool {
89    rdtsc() >= deadline
90}
91
92/// Read a 64-bit register from the NVMe controller.
93unsafe fn regs_read64(base: usize, offset: u64) -> u64 {
94    let low = core::ptr::read_volatile((base + offset as usize) as *const u32) as u64;
95    let high = core::ptr::read_volatile((base + offset as usize + 4) as *const u32) as u64;
96    low | (high << 32)
97}
98
99/// Build PRP (Physical Region Page) list for a physically contiguous buffer.
100///
101/// Returns `(prp1, prp2, owned)`:
102/// - If the buffer fits in a single page: `prp1 = buf_phys, prp2 = 0`, `owned = None`
103/// - If the buffer spans multiple pages: `prp2 = PRP list phys`, and `owned`
104///   carries the PRP list frame + its device address so the caller can free
105///   and unmap it once the command has completed.
106///
107/// The caller must ensure `buf_phys` is page-aligned and the buffer is physically
108/// contiguous for multi-page transfers.
109unsafe fn build_prp_list(
110    dma: &crate::dma::DmaMapper,
111    buf_device: u64,
112    byte_count: usize,
113) -> (u64, u64, Option<(crate::memory::PhysFrame, u64)>) {
114    let first_page_remaining = NVME_PAGE_SIZE - (buf_device as usize % NVME_PAGE_SIZE);
115    if byte_count <= first_page_remaining {
116        return (buf_device, 0, None);
117    }
118
119    // Allocate a PRP list page
120    let prp_frame = allocate_zeroed_frame().expect("NVMe: failed to allocate PRP list");
121    let prp_phys = prp_frame.start_address.as_u64();
122    let prp_device = dma.translate(
123        prp_phys,
124        NVME_PAGE_SIZE,
125        crate::hardware::iommu::DmaProt::READ_WRITE,
126    );
127    paging::ensure_identity_map_range(prp_phys, NVME_PAGE_SIZE as u64);
128    let prp_virt = phys_to_virt(prp_phys) as *mut u64;
129
130    // First page covers buf_device..end_of_first_page
131    let mut remaining = byte_count - first_page_remaining;
132    let mut next_phys = (buf_device & !0xFFF) + NVME_PAGE_SIZE as u64;
133    let mut idx = 0;
134
135    while remaining > 0 && idx < MAX_PRP_ENTRIES {
136        core::ptr::write_volatile(prp_virt.add(idx), next_phys);
137        idx += 1;
138        next_phys += NVME_PAGE_SIZE as u64;
139        remaining = remaining.saturating_sub(NVME_PAGE_SIZE);
140    }
141
142    (buf_device, prp_device, Some((prp_frame, prp_device)))
143}
144
145#[repr(transparent)]
146struct VolatileCell<T> {
147    value: T,
148}
149
150impl<T> VolatileCell<T> {
151    fn read(&self) -> T
152    where
153        T: Copy,
154    {
155        unsafe { ptr::read_volatile(&self.value) }
156    }
157    fn write(&self, val: T) {
158        unsafe { ptr::write_volatile(core::ptr::addr_of!(self.value) as *mut T, val) }
159    }
160}
161
162unsafe impl<T: Send> Send for VolatileCell<T> {}
163unsafe impl<T: Sync> Sync for VolatileCell<T> {}
164
165#[repr(C)]
166struct Capability {
167    value: VolatileCell<u64>,
168}
169
170impl Capability {
171    fn max_queue_entries(&self) -> u16 {
172        (self.value.read() & 0xFFFF) as u16
173    }
174    fn doorbell_stride(&self) -> u64 {
175        (self.value.read() >> 32) & 0xF
176    }
177}
178
179#[repr(transparent)]
180struct Version {
181    value: VolatileCell<u32>,
182}
183
184#[repr(C)]
185struct ControllerConfig {
186    value: VolatileCell<u32>,
187}
188
189impl ControllerConfig {
190    fn clear_io_fields(&self) {
191        let mut val = self.value.read();
192        val &= !(((0xF) << 16) | ((0xF) << 20) | ((0x7) << 4));
193        self.value.write(val);
194    }
195    fn set_iosqes(&self, size: u32) {
196        let mut val = self.value.read();
197        val |= (size & 0xF) << 16;
198        self.value.write(val);
199    }
200    fn set_iocqes(&self, size: u32) {
201        let mut val = self.value.read();
202        val |= (size & 0xF) << 20;
203        self.value.write(val);
204    }
205    fn set_css(&self, css: u32) {
206        let mut val = self.value.read();
207        val |= (css & 0x7) << 4;
208        self.value.write(val);
209    }
210    fn set_enable(&self, enable: bool) {
211        let mut val = self.value.read();
212        if enable {
213            val |= 1;
214        } else {
215            val &= !1;
216        }
217        self.value.write(val);
218    }
219    fn is_enabled(&self) -> bool {
220        (self.value.read() & 1) != 0
221    }
222}
223
224#[repr(transparent)]
225struct ControllerStatus {
226    value: VolatileCell<u32>,
227}
228
229impl ControllerStatus {
230    fn is_ready(&self) -> bool {
231        (self.value.read() & 1) != 0
232    }
233    fn is_fatal(&self) -> bool {
234        (self.value.read() >> 1) & 1 != 0
235    }
236}
237
238#[repr(C)]
239struct Registers {
240    capability: Capability,
241    version: Version,
242    _intms: VolatileCell<u32>,
243    _intmc: VolatileCell<u32>,
244    cc: ControllerConfig,
245    _reserved1: VolatileCell<u32>,
246    csts: ControllerStatus,
247    _reserved2: VolatileCell<u32>,
248    aqa: VolatileCell<u32>,
249    asq_low: VolatileCell<u32>,
250    asq_high: VolatileCell<u32>,
251    acq_low: VolatileCell<u32>,
252    acq_high: VolatileCell<u32>,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum NvmeError {
257    ControllerFatal,
258    Timeout,
259    InvalidNamespace,
260    /// Offset/length does not describe a whole number of namespace blocks.
261    InvalidParameter,
262    OutOfMemory,
263    IoError,
264}
265
266#[derive(Debug, Clone)]
267pub struct NvmeNamespace {
268    pub nsid: u32,
269    pub size: u64,
270    pub block_size: u32,
271}
272
273/// LBA Format descriptor (4 bytes each, starting at byte 128 of Identify Namespace).
274#[repr(C)]
275#[derive(Copy, Clone)]
276struct LbaFormat {
277    _metadata_size: u16,
278    lbads: u8,
279    _relative_perf: u8,
280}
281
282/// Identify Namespace data (first 384 bytes needed).
283/// Layout per NVMe spec: bytes 0-73 are explicit fields, 74-127 reserved, 128-383 LBAF[0..64].
284#[repr(C)]
285#[derive(Copy, Clone)]
286struct IdentifyNamespaceData {
287    nsze: u64,
288    _ncap: u64,
289    _nuse: u64,
290    _nsfeat: u8,
291    _nlbaf: u8,
292    flbas: u8,
293    _mc: u8,
294    _dpc: u8,
295    _dps: u8,
296    _nmic: u8,
297    _rescap: u8,
298    _fpi: u8,
299    _dlfeat: u8,
300    _nawun: u16,
301    _nawupf: u16,
302    _nacwu: u16,
303    _nabsn: u16,
304    _nabo: u16,
305    _nabspf: u16,
306    _noiob: u16,
307    _nvmcap: [u64; 2],
308    _npwg: u16,
309    _npwa: u16,
310    _npdg: u16,
311    _npda: u16,
312    _nows: u16,
313    _reserved: [u8; 54], // bytes 74-127
314    /// LBA Format Support : 64 entries × 4 bytes at offset 128
315    lbaf: [LbaFormat; 64],
316}
317
318/// Identify Controller data (partial : fields we need).
319#[repr(C)]
320#[derive(Copy, Clone)]
321struct IdentifyControllerData {
322    _vid: u16,
323    _ssvid: u16,
324    _sn: [u8; 20],
325    _mn: [u8; 40],
326    _fr: [u8; 8],
327    _rab: u8,
328    _ieee: [u8; 3],
329    _cmic: u8,
330    mdts: u8,
331    _cntlid: u16,
332    _ver: u32,
333    _rtd3r: u32,
334    _rtd3e: u32,
335    _oaes: u32,
336    _ctratt: u32,
337    _reserved0: [u8; 100],
338    _oacs: u16,
339    _acl: u8,
340    _aerl: u8,
341    _frmw: u8,
342    _lpa: u8,
343    _elpe: u8,
344    _npss: u8,
345    _avscc: u8,
346    _apsta: u8,
347    _wctemp: u16,
348    _cctemp: u16,
349    _reserved1: [u8; 242],
350    sqes: u8,
351    cqes: u8,
352    _maxcmd: u16,
353    nn: u32,
354    _oncs: u16,
355    _fuses: u16,
356    _fna: u8,
357    _vwc: u8,
358    _awun: u16,
359    _awupf: u16,
360    _icsvscc: u8,
361    _nwpc: u8,
362    _acwu: u16,
363    _cdfs: u16,
364    _sgls: u32,
365    _reserved2: [u8; 228],
366    _subnqn: [u8; 256],
367    _reserved3: [u8; 1024],
368    _psd: [[u8; 32]; 32],
369    _vs: [u8; 1024],
370}
371
372struct IoQueuePair {
373    submission: IoQueue<Submission>,
374    completion: IoQueue<Completion>,
375    command_id: u16,
376    size: usize,
377}
378
379struct IoQueue<T: QueueType> {
380    doorbell: *const VolatileCell<u32>,
381    entries: *mut T::EntryType,
382    size: usize,
383    index: usize,
384    phase: bool,
385    phys_addr: u64,
386}
387
388unsafe impl<T: QueueType> Send for IoQueue<T> {}
389unsafe impl<T: QueueType> Sync for IoQueue<T> {}
390
391impl<T: QueueType> IoQueue<T> {
392    fn new(
393        registers_base: usize,
394        size: usize,
395        queue_id: u16,
396        dstrd: usize,
397        dma: &crate::dma::DmaMapper,
398    ) -> Self {
399        let doorbell_offset =
400            0x1000 + ((((queue_id as usize) * 2) + T::DOORBELL_OFFSET) * (4 << dstrd));
401        let doorbell =
402            unsafe { &*((registers_base + doorbell_offset) as *const VolatileCell<u32>) };
403
404        let frame = allocate_zeroed_frame().expect("NVMe: failed to allocate I/O queue frame");
405        let phys_addr = frame.start_address.as_u64();
406        paging::ensure_identity_map_range(phys_addr, NVME_PAGE_SIZE as u64);
407        let virt_addr = phys_to_virt(phys_addr);
408
409        unsafe {
410            ptr::write_bytes(
411                virt_addr as *mut u8,
412                0,
413                size * core::mem::size_of::<T::EntryType>(),
414            );
415        }
416
417        let phys_addr = dma.translate(
418            phys_addr,
419            NVME_PAGE_SIZE,
420            crate::hardware::iommu::DmaProt::READ_WRITE,
421        );
422
423        Self {
424            doorbell,
425            entries: virt_addr as *mut T::EntryType,
426            size,
427            index: 0,
428            phase: true,
429            phys_addr,
430        }
431    }
432}
433
434#[derive(Debug, Clone, Copy)]
435pub struct NvmeCompletionResult {
436    pub command_id: u16,
437    pub status: u16,
438}
439
440pub struct NvmeController {
441    registers: usize,
442    admin_queue: SpinLock<QueuePair>,
443    io_queue: SpinLock<IoQueuePair>,
444    namespaces: Vec<NvmeNamespace>,
445    pub name: String,
446    irq_line: u8,
447    io_done: Box<[AtomicBool]>,
448    io_error: Box<[AtomicBool]>,
449    io_wq: WaitQueue,
450    dma: crate::dma::DmaMapper,
451}
452
453unsafe impl Send for NvmeController {}
454unsafe impl Sync for NvmeController {}
455
456impl NvmeController {
457    unsafe fn new(
458        registers: usize,
459        name: String,
460        sbdf: crate::hardware::iommu::Sbdf,
461    ) -> Result<Self, NvmeError> {
462        let regs = &*(registers as *const Registers);
463        let dstrd = regs.capability.doorbell_stride() as usize;
464        let max_entries = regs.capability.max_queue_entries();
465        let queue_size = core::cmp::min(max_entries as usize, 1024);
466
467        let dma = crate::dma::DmaMapper::for_sbdf(sbdf);
468        let admin_queue = QueuePair::new(registers, queue_size, dstrd, &dma);
469
470        let io_sub = IoQueue::new(registers, IO_QUEUE_SIZE, 1, dstrd, &dma);
471        let io_comp = IoQueue::new(registers, IO_QUEUE_SIZE, 1, dstrd, &dma);
472        let io_queue = IoQueuePair {
473            submission: io_sub,
474            completion: io_comp,
475            command_id: 0,
476            size: IO_QUEUE_SIZE,
477        };
478
479        let io_done: Box<[AtomicBool]> = (0..MAX_IO_COMMANDS)
480            .map(|_| AtomicBool::new(false))
481            .collect();
482        let io_error: Box<[AtomicBool]> = (0..MAX_IO_COMMANDS)
483            .map(|_| AtomicBool::new(false))
484            .collect();
485
486        let mut controller = Self {
487            registers,
488            admin_queue: SpinLock::new(admin_queue),
489            io_queue: SpinLock::new(io_queue),
490            namespaces: Vec::new(),
491            name,
492            irq_line: 0,
493            io_done,
494            io_error,
495            io_wq: WaitQueue::new(),
496            dma,
497        };
498
499        controller.init_admin_queue()?;
500        controller.create_io_queues()?;
501        controller.identify_namespaces()?;
502        Ok(controller)
503    }
504
505    fn submit_admin_command(&self, command: Command) -> Result<CompletionEntry, NvmeError> {
506        let mut admin = self.admin_queue.lock();
507        admin.submit_command(command).ok_or(NvmeError::IoError)
508    }
509
510    fn init_admin_queue(&mut self) -> Result<(), NvmeError> {
511        let regs = unsafe { &*(self.registers as *const Registers) };
512        let (admin_sq_phys, admin_cq_phys, queue_size) = {
513            let q = self.admin_queue.lock();
514            (q.submission_phys(), q.completion_phys(), q.size)
515        };
516
517        if queue_size == 0 {
518            return Err(NvmeError::IoError);
519        }
520        let qsz = ((queue_size as u32).saturating_sub(1)) & 0x0FFF;
521
522        log::info!("NVMe init: queue_size={} qsz={}", queue_size, qsz);
523        log::info!(
524            "NVMe init: ASQ phys={:#x} ACQ phys={:#x}",
525            admin_sq_phys,
526            admin_cq_phys
527        );
528
529        // Step 1: Disable controller if it's already enabled
530        let cc_val = regs.cc.value.read();
531        let csts_val = regs.csts.value.read();
532        log::info!("NVMe init: CC={:#010x} CSTS={:#010x}", cc_val, csts_val);
533
534        if cc_val & 1 != 0 {
535            log::info!("NVMe init: controller enabled, disabling...");
536
537            // Some AMD NVMe controllers (e.g. on Lenovo X13) hang if we send
538            // SHN (shutdown notification) before clearing CC.EN.  The safe
539            // approach for re-initialisation is to skip SHN and just write
540            // CC.EN=0 directly.  This matches Linux's nvme_disable_ctrl().
541            regs.cc.set_enable(false);
542            log::info!("NVMe init: wrote CC.EN=0 (no SHN), waiting for CSTS.RDY...");
543
544            // Wait for CSTS.RDY (bit 0) to clear : up to 5.5 s per NVMe spec.
545            // Use a generous timeout; some AMD controllers are slow to respond.
546            let deadline = tsc_deadline_ms(5500);
547            let mut log_count = 0u32;
548            loop {
549                let csts = regs.csts.value.read();
550                if csts & 1 == 0 {
551                    log::info!("NVMe init: controller disabled, CSTS={:#x}", csts);
552                    break;
553                }
554                if tsc_expired(deadline) {
555                    log::warn!("NVMe init: RDY timeout, CSTS={:#x} : forcing CC=0", csts);
556
557                    // Last resort: write CC=0x00000000
558                    regs.cc.value.write(0x0000_0000);
559                    log::info!("NVMe init: wrote CC=0x00000000 (full reset)");
560                    let force_deadline = tsc_deadline_ms(3000);
561                    while !tsc_expired(force_deadline) {
562                        let c = regs.csts.value.read();
563                        if c & 1 == 0 {
564                            log::info!("NVMe init: forced disable OK, CSTS={:#x}", c);
565                            break;
566                        }
567                        core::hint::spin_loop();
568                    }
569                    break;
570                }
571                core::hint::spin_loop();
572                log_count += 1;
573                if log_count % 2_000_000 == 0 {
574                    log::info!(
575                        "NVMe init: still waiting... CSTS={:#x}",
576                        regs.csts.value.read()
577                    );
578                }
579            }
580        } else {
581            log::info!("NVMe init: controller already disabled");
582        }
583
584        // Small delay after disable ; some AMD controllers need this before
585        // admin queue registers become writable.
586        let settle = tsc_deadline_ms(2);
587        while !tsc_expired(settle) {
588            core::hint::spin_loop();
589        }
590
591        // Step 2: Verify CSTS
592        let csts = regs.csts.value.read();
593        log::info!("NVMe init: CSTS={:#x}", csts);
594        if csts & 2 != 0 {
595            log::error!("NVMe init: CSTS.CFS (fatal) set!");
596            return Err(NvmeError::ControllerFatal);
597        }
598
599        // Step 3: Write admin queue registers (32-bit writes, like Redox/MaestroOS)
600        log::info!("NVMe init: writing AQA={:#x}...", qsz | (qsz << 16));
601        regs.aqa.write(qsz | (qsz << 16));
602        log::info!("NVMe init: writing ASQ={:#x}...", admin_sq_phys);
603        regs.asq_low.write(admin_sq_phys as u32);
604        regs.asq_high.write((admin_sq_phys >> 32) as u32);
605        log::info!("NVMe init: writing ACQ={:#x}...", admin_cq_phys);
606        regs.acq_low.write(admin_cq_phys as u32);
607        regs.acq_high.write((admin_cq_phys >> 32) as u32);
608
609        // Step 4: Configure CC
610        log::info!("NVMe init: configuring CC...");
611        regs.cc.clear_io_fields();
612        regs.cc.set_css(0); // NVM Command Set
613        regs.cc.set_iosqes(6); // 2^6 = 64 byte submission queue entries
614        regs.cc.set_iocqes(6); // 2^6 = 64 byte completion queue entries
615        log::info!("NVMe init: CC={:#010x} (configured)", regs.cc.value.read());
616
617        // Step 5: Enable controller
618        log::info!("NVMe init: enabling controller...");
619        regs.cc.set_enable(true);
620        log::info!("NVMe init: CC={:#010x} (EN=1)", regs.cc.value.read());
621
622        // Step 6: Wait for CSTS.RDY (up to 5.5s per NVMe spec)
623        let deadline = tsc_deadline_ms(5500);
624        let mut log_interval = 0u32;
625        loop {
626            let csts = regs.csts.value.read();
627            if csts & 1 != 0 {
628                log::info!("NVMe init: controller ready, CSTS={:#x}", csts);
629                break;
630            }
631            if tsc_expired(deadline) {
632                log::error!("NVMe init: enable timeout! CSTS={:#x}", csts);
633                return Err(NvmeError::Timeout);
634            }
635            core::hint::spin_loop();
636            log_interval += 1;
637            if log_interval % 500_000 == 0 {
638                log::info!("NVMe init: waiting for ready... CSTS={:#x}", csts);
639            }
640        }
641
642        let csts = regs.csts.value.read();
643        log::info!("NVMe init: final CSTS={:#x}", csts);
644
645        if csts & 2 != 0 {
646            log::error!("NVMe init: controller fatal error!");
647            return Err(NvmeError::ControllerFatal);
648        }
649
650        log::info!(
651            "NVMe: Controller v{}.{}.{} ready",
652            regs.version.value.read() >> 16,
653            (regs.version.value.read() >> 8) & 0xFF,
654            regs.version.value.read() & 0xFF
655        );
656        Ok(())
657    }
658
659    fn create_io_queues(&mut self) -> Result<(), NvmeError> {
660        let (io_sq_phys, io_cq_phys, queue_size) = {
661            let q = self.io_queue.lock();
662            (q.submission.phys_addr, q.completion.phys_addr, q.size)
663        };
664
665        let qsz = ((queue_size as u32).saturating_sub(1)) & 0xFFF;
666
667        log::info!(
668            "NVMe I/O queues: size={} qsz={} SQ={:#x} CQ={:#x}",
669            queue_size,
670            qsz,
671            io_sq_phys,
672            io_cq_phys
673        );
674
675        log::info!("NVMe I/O: sending Set Features (IRQ coalescing)...");
676        let set_feature_cmd = Command {
677            opcode: 0x09,
678            cdw10: 0x07,
679            cdw11: 0x0100_0000,
680            ..Default::default()
681        };
682        self.submit_admin_command(set_feature_cmd).ok();
683
684        log::info!("NVMe I/O: creating I/O CQ...");
685        // NVMe spec CDW10: bits 15:0=QID, bits 31:16=QSIZE(0-based)
686        // NVMe spec CDW11: bit 0=PCIE, bit 1=IEN, bits 31:16=IV
687        let cq_cmd = Command {
688            opcode: 0x05,
689            cdw10: qsz << 16,   // QID=0 in bits 15:0, QSIZE in bits 31:16
690            cdw11: 0x0000_0003, // PCIE=1, IEN=1
691            prp1: io_cq_phys,
692            ..Default::default()
693        };
694        match self.submit_admin_command(cq_cmd) {
695            Ok(c) => {
696                if c.status_code() != 0 {
697                    log::warn!("NVMe: Create I/O CQ failed: status={}", c.status_code());
698                } else {
699                    log::info!("NVMe I/O: CQ created OK");
700                }
701            }
702            Err(e) => {
703                log::warn!("NVMe: Create I/O CQ error: {:?}", e);
704                return Err(e);
705            }
706        }
707
708        log::info!("NVMe I/O: creating I/O SQ...");
709        // NVMe spec CDW10: bits 15:0=QID, bits 31:16=QSIZE(0-based)
710        // NVMe spec CDW11: bit 0=PCIE, bits 31:16=CQID
711        let sq_cmd = Command {
712            opcode: 0x01,
713            cdw10: (qsz << 16) | 1, // QID=1 in bits 15:0, QSIZE in bits 31:16
714            cdw11: (1 << 16) | 0x0000_0001, // CQID=1 in bits 31:16, PCIE=1
715            prp1: io_sq_phys,
716            ..Default::default()
717        };
718        match self.submit_admin_command(sq_cmd) {
719            Ok(c) => {
720                if c.status_code() != 0 {
721                    log::warn!("NVMe: Create I/O SQ failed: status={}", c.status_code());
722                } else {
723                    log::info!("NVMe I/O: SQ created OK");
724                }
725            }
726            Err(e) => {
727                log::warn!("NVMe: Create I/O SQ error: {:?}", e);
728                return Err(e);
729            }
730        }
731
732        log::info!("NVMe: I/O queues created (size={})", queue_size);
733        Ok(())
734    }
735
736    fn identify(&self, cns: u8, nsid: u32) -> Result<Vec<u8>, NvmeError> {
737        let frame = allocate_zeroed_frame().ok_or(NvmeError::IoError)?;
738        let phys = frame.start_address.as_u64();
739        paging::ensure_identity_map_range(phys, NVME_PAGE_SIZE as u64);
740        let virt = phys_to_virt(phys) as *mut u8;
741        unsafe {
742            ptr::write_bytes(virt, 0, NVME_PAGE_SIZE);
743        }
744        let device = self.dma.translate(
745            phys,
746            NVME_PAGE_SIZE,
747            crate::hardware::iommu::DmaProt::READ_WRITE,
748        );
749
750        let cmd = Command {
751            opcode: 0x06,
752            nsid,
753            prp1: device,
754            cdw10: cns as u32,
755            ..Default::default()
756        };
757
758        let completion = self.submit_admin_command(cmd)?;
759        if completion.status_code() != 0 {
760            return Err(NvmeError::IoError);
761        }
762
763        // Copy data to owned Vec before the DMA frame is freed.
764        let mut data = Vec::with_capacity(NVME_PAGE_SIZE);
765        unsafe {
766            for i in 0..NVME_PAGE_SIZE {
767                data.push(ptr::read_volatile(virt.add(i)));
768            }
769        }
770        // frame dropped here => physical memory freed
771        Ok(data)
772    }
773
774    fn identify_namespaces(&mut self) -> Result<(), NvmeError> {
775        // Step 1: Identify Controller : get NN, MDTS, SQES, CQES, and info
776        let ctrl_data = self.identify(0x01, 0)?;
777        let ctrl = unsafe { core::ptr::read(ctrl_data.as_ptr() as *const IdentifyControllerData) };
778        let nn = ctrl.nn;
779        let mdts = ctrl.mdts;
780
781        // Validate SQES/CQES (like MaestroOS)
782        let min_sqes = ctrl.sqes & 0xF;
783        let max_sqes = (ctrl.sqes >> 4) & 0xF;
784        let min_cqes = ctrl.cqes & 0xF;
785        let max_cqes = (ctrl.cqes >> 4) & 0xF;
786        let our_sqes = 6u8; // 2^6 = 64 bytes
787        let our_cqes = 4u8; // 2^4 = 16 bytes
788
789        if our_sqes < min_sqes || our_sqes > max_sqes {
790            log::warn!(
791                "NVMe: SQES {} not in range [{}..{}] : controller may reject commands",
792                our_sqes,
793                min_sqes,
794                max_sqes
795            );
796        }
797        if our_cqes < min_cqes || our_cqes > max_cqes {
798            log::warn!(
799                "NVMe: CQES {} not in range [{}..{}] : controller may reject completions",
800                our_cqes,
801                min_cqes,
802                max_cqes
803            );
804        }
805
806        // Validate page size against CAP (like MaestroOS)
807        let cap = unsafe { regs_read64(self.registers, 0x00) };
808        let mpsmin = ((cap >> 48) & 0xF) as u32 + 12; // log2 of min page size
809        let mpsmax = ((cap >> 52) & 0xF) as u32 + 12; // log2 of max page size
810        let our_mps = 12u32; // 4096 bytes
811        if our_mps < mpsmin || our_mps > mpsmax {
812            log::warn!(
813                "NVMe: Page size {} not in range [{}..{}] bytes",
814                1 << our_mps,
815                1 << mpsmin,
816                1 << mpsmax
817            );
818        }
819
820        log::info!(
821            "NVMe: Controller NN={} MDTS={} SQES={:#x} CQES={:#x} MPS=[{}..{}]",
822            nn,
823            mdts,
824            ctrl.sqes,
825            ctrl.cqes,
826            1 << mpsmin,
827            1 << mpsmax
828        );
829
830        if nn == 0 {
831            return Err(NvmeError::InvalidNamespace);
832        }
833
834        // Step 2: Identify Active Namespace ID List (CNS=2)
835        let ns_list = self.identify(0x02, 0)?;
836        let ns_list_words = unsafe {
837            core::slice::from_raw_parts(ns_list.as_ptr() as *const u32, ns_list.len() / 4)
838        };
839        let mut active_nsids: Vec<u32> = Vec::new();
840        for &word in ns_list_words.iter() {
841            if word == 0 {
842                break;
843            }
844            active_nsids.push(word);
845        }
846        log::info!("NVMe: {} active namespace(s)", active_nsids.len());
847
848        // Step 3: Identify each active namespace
849        for nsid in &active_nsids {
850            if let Ok(ns_data) = self.identify(0x00, *nsid) {
851                let ns =
852                    unsafe { core::ptr::read(ns_data.as_ptr() as *const IdentifyNamespaceData) };
853
854                let flbas = ns.flbas as usize;
855                let lbaf_idx = flbas & 0xF;
856                let lbads = ns.lbaf[lbaf_idx].lbads;
857                let block_size = 1u32 << lbads;
858
859                self.namespaces.push(NvmeNamespace {
860                    nsid: *nsid,
861                    size: ns.nsze,
862                    block_size,
863                });
864                log::info!(
865                    "NVMe: NSID {} - {} blocks @ {} bytes (LBADS={}, FLBAS={:#x})",
866                    nsid,
867                    ns.nsze,
868                    block_size,
869                    lbads,
870                    flbas
871                );
872            }
873        }
874        Ok(())
875    }
876
877    fn submit_io_command(&self, command: &mut Command) -> Result<u16, NvmeError> {
878        let mut io = self.io_queue.lock();
879        let cmd_id = io.command_id;
880        command.command_id = cmd_id;
881        io.command_id = io.command_id.wrapping_add(1);
882
883        let slot = cmd_id as usize % io.size;
884
885        let idx = cmd_id as usize % MAX_IO_COMMANDS;
886        self.io_done[idx].store(false, Ordering::SeqCst);
887        self.io_error[idx].store(false, Ordering::SeqCst);
888
889        unsafe {
890            ptr::write(io.submission.entries.add(slot), *command);
891            core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
892            (*io.submission.doorbell).write(((slot + 1) % io.size) as u32);
893        }
894
895        Ok(cmd_id)
896    }
897
898    /// Reads `block_count` namespace blocks of `block_size` bytes.
899    ///
900    /// `buf_device` is the device address of a physically contiguous buffer;
901    /// use [`Self::read_bytes`] for the safe CPU-buffer wrapper.
902    pub fn read_blocks(
903        &self,
904        nsid: u32,
905        lba: u64,
906        block_count: u32,
907        block_size: u32,
908        buf_device: u64,
909    ) -> Result<(), NvmeError> {
910        self.submit_data_command(0x02, nsid, lba, block_count, block_size, buf_device)
911    }
912
913    /// Writes `block_count` namespace blocks of `block_size` bytes.
914    ///
915    /// `buf_device` is the device address of a physically contiguous buffer;
916    /// use [`Self::write_bytes`] for the safe CPU-buffer wrapper.
917    pub fn write_blocks(
918        &self,
919        nsid: u32,
920        lba: u64,
921        block_count: u32,
922        block_size: u32,
923        buf_device: u64,
924    ) -> Result<(), NvmeError> {
925        self.submit_data_command(0x01, nsid, lba, block_count, block_size, buf_device)
926    }
927
928    fn submit_data_command(
929        &self,
930        opcode: u8,
931        nsid: u32,
932        lba: u64,
933        block_count: u32,
934        block_size: u32,
935        buf_device: u64,
936    ) -> Result<(), NvmeError> {
937        if block_count == 0 || block_size == 0 {
938            return Err(NvmeError::InvalidParameter);
939        }
940        let byte_count = (block_count as usize)
941            .checked_mul(block_size as usize)
942            .ok_or(NvmeError::InvalidParameter)?;
943        let (prp1, prp2, prp_owned) = unsafe { build_prp_list(&self.dma, buf_device, byte_count) };
944
945        let result = (|| {
946            let cmd_id = {
947                let mut cmd = Command {
948                    opcode,
949                    nsid,
950                    prp1,
951                    prp2,
952                    cdw10: (lba & 0xFFFF_FFFF) as u32,
953                    cdw11: ((lba >> 32) & 0xFFFF_FFFF) as u32,
954                    cdw12: block_count - 1,
955                    ..Default::default()
956                };
957                self.submit_io_command(&mut cmd)?
958            };
959
960            let idx = cmd_id as usize % MAX_IO_COMMANDS;
961            self.wait_io(idx)?;
962
963            if self.io_error[idx].load(Ordering::Acquire) {
964                return Err(NvmeError::IoError);
965            }
966            Ok(())
967        })();
968
969        // The PRP list is only referenced by the command descriptor, so it can
970        // be unmapped and returned to the buddy allocator once the command has
971        // completed (or failed).
972        if let Some((frame, device)) = prp_owned {
973            self.dma.release(device, NVME_PAGE_SIZE);
974            crate::sync::with_irqs_disabled(|token| {
975                crate::memory::free_frame(token, frame);
976            });
977        }
978
979        result
980    }
981
982    /// Waits for the completion of command slot `idx`.
983    ///
984    /// In task context this blocks on the completion WaitQueue (IRQ driven);
985    /// before the scheduler exists it falls back to a bounded poll so that
986    /// probing/mount paths cannot panic on `wait_until` without a task.
987    fn wait_io(&self, idx: usize) -> Result<(), NvmeError> {
988        if crate::process::current_task_id().is_some() {
989            self.io_wq.wait_until(|| {
990                if self.io_done[idx].load(Ordering::Acquire) {
991                    Some(())
992                } else {
993                    None
994                }
995            });
996            return Ok(());
997        }
998
999        let deadline = tsc_deadline_ms(5_000);
1000        while !self.io_done[idx].load(Ordering::Acquire) {
1001            if tsc_expired(deadline) {
1002                return Err(NvmeError::Timeout);
1003            }
1004            core::hint::spin_loop();
1005        }
1006        Ok(())
1007    }
1008
1009    /// Flushes the namespace's volatile write cache (`NVMe Flush`, opcode 0x00).
1010    ///
1011    /// The command transfers no data (PRPs stay zero) and completion is only
1012    /// reported once the controller posts a completion queue entry, so a
1013    /// successful return means the namespace cache was actually flushed.
1014    pub fn flush(&self, nsid: u32) -> Result<(), NvmeError> {
1015        let cmd_id = {
1016            let mut cmd = Command {
1017                opcode: 0x00,
1018                nsid,
1019                ..Default::default()
1020            };
1021            self.submit_io_command(&mut cmd)?
1022        };
1023
1024        let idx = cmd_id as usize % MAX_IO_COMMANDS;
1025        self.wait_io(idx)?;
1026
1027        if self.io_error[idx].load(Ordering::Acquire) {
1028            return Err(NvmeError::IoError);
1029        }
1030        Ok(())
1031    }
1032
1033    /// Reads `buf.len()` bytes at `offset` through a DMA bounce buffer.
1034    ///
1035    /// The namespace block size is honoured: unaligned ranges are handled with
1036    /// a block-granular read, so a 512-byte sector read works on both 512-byte
1037    /// and 4 KiB native namespaces.
1038    pub fn read_bytes(&self, nsid: u32, offset: u64, buf: &mut [u8]) -> Result<(), NvmeError> {
1039        self.transfer_bytes(nsid, offset, buf.as_mut_ptr(), buf.len(), false)
1040    }
1041
1042    /// Writes `data` at `offset` through a DMA bounce buffer.
1043    ///
1044    /// Like [`Self::read_bytes`], partial namespace blocks are completed with
1045    /// a read-modify-write so the surrounding bytes are preserved.
1046    pub fn write_bytes(&self, nsid: u32, offset: u64, data: &[u8]) -> Result<(), NvmeError> {
1047        self.transfer_bytes(nsid, offset, data.as_ptr() as *mut u8, data.len(), true)
1048    }
1049
1050    /// Returns `(block_count, block_size)` for a namespace.
1051    pub fn namespace_layout(&self, nsid: u32) -> Result<(u64, u32), NvmeError> {
1052        let namespace = self
1053            .namespaces
1054            .iter()
1055            .find(|namespace| namespace.nsid == nsid)
1056            .ok_or(NvmeError::InvalidNamespace)?;
1057        if namespace.block_size == 0 {
1058            return Err(NvmeError::InvalidNamespace);
1059        }
1060        Ok((namespace.size, namespace.block_size))
1061    }
1062
1063    /// Shared byte-range engine for [`Self::read_bytes`]/[`Self::write_bytes`].
1064    ///
1065    /// # Safety
1066    /// `cpu` must be valid for `len` bytes of read access (and write access
1067    /// when `write == false`); every modification of the buffer only happens
1068    /// through this function.
1069    fn transfer_bytes(
1070        &self,
1071        nsid: u32,
1072        offset: u64,
1073        cpu: *mut u8,
1074        len: usize,
1075        write: bool,
1076    ) -> Result<(), NvmeError> {
1077        if len == 0 {
1078            return Ok(());
1079        }
1080        let (blocks, block_size) = self.namespace_layout(nsid)?;
1081        let bs = block_size as usize;
1082        let capacity = blocks
1083            .checked_mul(block_size as u64)
1084            .ok_or(NvmeError::InvalidParameter)?;
1085        let end = offset
1086            .checked_add(len as u64)
1087            .ok_or(NvmeError::InvalidParameter)?;
1088        if end > capacity {
1089            return Err(NvmeError::InvalidParameter);
1090        }
1091
1092        let mut pos = 0usize;
1093        let mut scratch = Vec::new();
1094        while pos < len {
1095            let byte_offset = offset + pos as u64;
1096            let lba = byte_offset / block_size as u64;
1097            let in_block = (byte_offset % block_size as u64) as usize;
1098            let remaining = len - pos;
1099
1100            if in_block == 0 && remaining >= bs {
1101                // Full blocks: one command up to MAX_TRANSFER_BLOCKS.
1102                let count = (remaining / bs).min(MAX_TRANSFER_BLOCKS as usize);
1103                let bytes = count * bs;
1104                self.dma_transfer(nsid, lba, count as u32, block_size, cpu, pos, bytes, write)?;
1105                pos += bytes;
1106            } else {
1107                // Partial block on either edge: block-granular read-modify-write.
1108                let n = (bs - in_block).min(remaining);
1109                if scratch.len() < bs {
1110                    scratch.resize(bs, 0);
1111                }
1112                let scratch_ptr = scratch.as_mut_ptr();
1113                if write {
1114                    self.dma_transfer(nsid, lba, 1, block_size, scratch_ptr, 0, bs, false)?;
1115                    // SAFETY: `cpu` is readable for `len` bytes and `pos + n <= len`.
1116                    unsafe {
1117                        ptr::copy_nonoverlapping(cpu.add(pos), scratch_ptr.add(in_block), n);
1118                    }
1119                    self.dma_transfer(nsid, lba, 1, block_size, scratch_ptr, 0, bs, true)?;
1120                } else {
1121                    self.dma_transfer(nsid, lba, 1, block_size, scratch_ptr, 0, bs, false)?;
1122                    // SAFETY: `cpu` is writable for `len` bytes and `pos + n <= len`.
1123                    unsafe {
1124                        ptr::copy_nonoverlapping(scratch_ptr.add(in_block), cpu.add(pos), n);
1125                    }
1126                }
1127                pos += n;
1128            }
1129        }
1130        Ok(())
1131    }
1132
1133    /// Copies `len` bytes between `cpu + cpu_offset` and a DMA bounce buffer and
1134    /// issues a single NVMe I/O command.
1135    #[allow(clippy::too_many_arguments)]
1136    fn dma_transfer(
1137        &self,
1138        nsid: u32,
1139        lba: u64,
1140        block_count: u32,
1141        block_size: u32,
1142        cpu: *mut u8,
1143        cpu_offset: usize,
1144        len: usize,
1145        write: bool,
1146    ) -> Result<(), NvmeError> {
1147        let pages = len.div_ceil(4096);
1148        let order = pages.next_power_of_two().trailing_zeros() as u8;
1149        let frame = crate::sync::with_irqs_disabled(|token| {
1150            crate::memory::allocate_phys_contiguous(token, order)
1151        })
1152        .map_err(|_| NvmeError::OutOfMemory)?;
1153        let phys = frame.start_address.as_u64();
1154        let virt = crate::memory::phys_to_virt(phys);
1155        let device = self
1156            .dma
1157            .translate(phys, len, crate::hardware::iommu::DmaProt::READ_WRITE);
1158
1159        // SAFETY: the bounce frame was allocated with `len` bytes of capacity
1160        // and `cpu + cpu_offset` is valid for `len` bytes from the caller.
1161        let result = unsafe {
1162            if write {
1163                ptr::copy_nonoverlapping(cpu.add(cpu_offset), virt as *mut u8, len);
1164                self.write_blocks(nsid, lba, block_count, block_size, device)
1165            } else {
1166                self.read_blocks(nsid, lba, block_count, block_size, device)
1167                    .map(|()| {
1168                        ptr::copy_nonoverlapping(virt as *const u8, cpu.add(cpu_offset), len);
1169                    })
1170            }
1171        };
1172
1173        self.dma.release(device, len);
1174        crate::sync::with_irqs_disabled(|token| {
1175            crate::memory::free_phys_contiguous(token, frame, order);
1176        });
1177        result
1178    }
1179
1180    pub fn handle_interrupt(&self) {
1181        let mut io = self.io_queue.lock();
1182
1183        loop {
1184            let entry = unsafe { &*io.completion.entries.add(io.completion.index) };
1185            let status = entry.status;
1186            if ((status & 0x1) != 0) == io.completion.phase {
1187                let cmd_id = entry.command_id;
1188                let sc = (entry.status >> 1) & 0xFF;
1189                let dnr = (entry.status >> 14) & 1;
1190
1191                io.completion.index = (io.completion.index + 1) % io.completion.size;
1192                if io.completion.index == 0 {
1193                    io.completion.phase = !io.completion.phase;
1194                }
1195                unsafe {
1196                    (*io.completion.doorbell).write(io.completion.index as u32);
1197                }
1198
1199                let idx = cmd_id as usize % MAX_IO_COMMANDS;
1200                if sc != 0 && dnr == 0 {
1201                    log::warn!("NVMe: I/O error cmd_id={} sc={}", cmd_id, sc);
1202                }
1203                self.io_error[idx].store(sc != 0, Ordering::Release);
1204                self.io_done[idx].store(true, Ordering::Release);
1205                self.io_wq.wake_all();
1206            } else {
1207                break;
1208            }
1209        }
1210    }
1211
1212    pub fn namespace_count(&self) -> usize {
1213        self.namespaces.len()
1214    }
1215
1216    pub fn get_namespace(&self, index: usize) -> Option<&NvmeNamespace> {
1217        self.namespaces.get(index)
1218    }
1219
1220    pub fn set_irq_line(&mut self, irq: u8) {
1221        self.irq_line = irq;
1222    }
1223
1224    pub fn irq_line(&self) -> u8 {
1225        self.irq_line
1226    }
1227}
1228
1229#[repr(C)]
1230#[derive(Default, Copy, Clone)]
1231struct Command {
1232    opcode: u8,
1233    flags: u8,
1234    command_id: u16,
1235    nsid: u32,
1236    cdw2: u32,
1237    cdw3: u32,
1238    prp1: u64,
1239    prp2: u64,
1240    cdw10: u32,
1241    cdw11: u32,
1242    cdw12: u32,
1243    cdw13: u32,
1244    cdw14: u32,
1245    cdw15: u32,
1246}
1247
1248#[repr(C)]
1249#[derive(Copy, Clone)]
1250struct CompletionEntry {
1251    dw0: u32,
1252    dw1: u32,
1253    sq_head: u16,
1254    sq_id: u16,
1255    command_id: u16,
1256    status: u16,
1257}
1258
1259impl CompletionEntry {
1260    fn status_code(&self) -> u8 {
1261        ((self.status >> 1) & 0xFF) as u8
1262    }
1263}
1264
1265struct QueuePair {
1266    #[allow(dead_code)]
1267    id: u16,
1268    size: usize,
1269    command_id: u16,
1270    submission: Queue<Submission>,
1271    completion: Queue<Completion>,
1272}
1273
1274struct Submission;
1275struct Completion;
1276
1277trait QueueType {
1278    type EntryType;
1279    const DOORBELL_OFFSET: usize;
1280}
1281
1282impl QueueType for Submission {
1283    type EntryType = Command;
1284    const DOORBELL_OFFSET: usize = 0;
1285}
1286
1287impl QueueType for Completion {
1288    type EntryType = CompletionEntry;
1289    const DOORBELL_OFFSET: usize = 1;
1290}
1291
1292struct Queue<T: QueueType> {
1293    doorbell: *const VolatileCell<u32>,
1294    entries: *mut T::EntryType,
1295    size: usize,
1296    index: usize,
1297    phase: bool,
1298    phys_addr: u64,
1299}
1300
1301impl<T: QueueType> Queue<T> {
1302    fn new(
1303        registers_base: usize,
1304        size: usize,
1305        queue_id: u16,
1306        dstrd: usize,
1307        dma: &crate::dma::DmaMapper,
1308    ) -> Self {
1309        let doorbell_offset =
1310            0x1000 + ((((queue_id as usize) * 2) + T::DOORBELL_OFFSET) * (4 << dstrd));
1311        let doorbell =
1312            unsafe { &*((registers_base + doorbell_offset) as *const VolatileCell<u32>) };
1313
1314        let frame = allocate_zeroed_frame().expect("NVMe: failed to allocate queue frame");
1315        let phys_addr = frame.start_address.as_u64();
1316        paging::ensure_identity_map_range(phys_addr, NVME_PAGE_SIZE as u64);
1317        let virt_addr = phys_to_virt(phys_addr);
1318
1319        unsafe {
1320            ptr::write_bytes(
1321                virt_addr as *mut u8,
1322                0,
1323                size * core::mem::size_of::<T::EntryType>(),
1324            );
1325        }
1326
1327        // Program the device-visible address (identity when IOMMU is off).
1328        let phys_addr = dma.translate(
1329            phys_addr,
1330            NVME_PAGE_SIZE,
1331            crate::hardware::iommu::DmaProt::READ_WRITE,
1332        );
1333
1334        Self {
1335            doorbell,
1336            entries: virt_addr as *mut T::EntryType,
1337            size,
1338            index: 0,
1339            phase: true,
1340            phys_addr,
1341        }
1342    }
1343
1344    fn phys_addr(&self) -> u64 {
1345        self.phys_addr
1346    }
1347}
1348
1349impl Queue<Completion> {
1350    fn poll_completion(&mut self) -> Option<CompletionEntry> {
1351        unsafe {
1352            let entry = &*self.entries.add(self.index);
1353            let status = entry.status;
1354            if ((status & 0x1) != 0) == self.phase {
1355                let completion = ptr::read(entry);
1356                self.index = (self.index + 1) % self.size;
1357                if self.index == 0 {
1358                    self.phase = !self.phase;
1359                }
1360                (*self.doorbell).write(self.index as u32);
1361                Some(completion)
1362            } else {
1363                None
1364            }
1365        }
1366    }
1367}
1368
1369impl Queue<Submission> {
1370    fn submit_command(&mut self, command: Command, idx: usize) {
1371        unsafe {
1372            ptr::write(self.entries.add(idx), command);
1373            (*self.doorbell).write(((idx + 1) % self.size) as u32);
1374        }
1375        core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
1376    }
1377}
1378
1379impl QueuePair {
1380    fn new(registers_base: usize, size: usize, dstrd: usize, dma: &crate::dma::DmaMapper) -> Self {
1381        static NEXT_ID: AtomicU8 = AtomicU8::new(0);
1382        let id = NEXT_ID.fetch_add(1, Ordering::SeqCst) as u16;
1383        Self {
1384            id,
1385            size,
1386            command_id: 0,
1387            submission: Queue::new(registers_base, size, id, dstrd, dma),
1388            completion: Queue::new(registers_base, size, id, dstrd, dma),
1389        }
1390    }
1391
1392    fn submission_phys(&self) -> u64 {
1393        self.submission.phys_addr()
1394    }
1395    fn completion_phys(&self) -> u64 {
1396        self.completion.phys_addr()
1397    }
1398
1399    fn submit_command(&mut self, command: Command) -> Option<CompletionEntry> {
1400        let slot = self.command_id as usize % self.size;
1401        let mut cmd = command;
1402        unsafe {
1403            ptr::write(&mut cmd.command_id as *mut u16, self.command_id);
1404        }
1405        self.command_id = self.command_id.wrapping_add(1);
1406        self.submission.submit_command(cmd, slot);
1407        let deadline = tsc_deadline_ms(5500); // NVMe spec: up to 5.5s for admin commands
1408        loop {
1409            if let Some(c) = self.completion.poll_completion() {
1410                return Some(c);
1411            }
1412            if tsc_expired(deadline) {
1413                log::error!("NVMe: admin command timeout");
1414                return None;
1415            }
1416            core::hint::spin_loop();
1417        }
1418    }
1419}
1420
1421static NVME_CONTROLLERS: SpinLock<Vec<Arc<SpinLock<NvmeController>>>> = SpinLock::new(Vec::new());
1422static NVME_INITIALIZED: AtomicBool = AtomicBool::new(false);
1423
1424pub static NVME_IRQ_LINE: AtomicU8 = AtomicU8::new(0);
1425
1426pub fn init() {
1427    if NVME_INITIALIZED.load(Ordering::Relaxed) {
1428        return;
1429    }
1430    log::info!("[NVMe] Scanning for NVMe controllers...");
1431
1432    let candidates = pci::probe_all(ProbeCriteria {
1433        vendor_id: None,
1434        device_id: None,
1435        class_code: Some(pci::class::MASS_STORAGE),
1436        subclass: Some(pci::storage_subclass::NVM),
1437        prog_if: None,
1438    });
1439
1440    for (i, pci_dev) in candidates.into_iter().enumerate() {
1441        log::info!(
1442            "NVMe: Found controller at {:?} (VEN:{:04x} DEV:{:04x})",
1443            pci_dev.address,
1444            pci_dev.vendor_id,
1445            pci_dev.device_id
1446        );
1447
1448        pci_dev.enable_bus_master();
1449        pci_dev.enable_memory_space();
1450
1451        // Try MSI/MSI-X first; fall back to INTx line.
1452        #[cfg(target_arch = "x86_64")]
1453        let (irq, vector) = crate::arch::x86_64::msi::probe_and_enable(&pci_dev, true);
1454        #[cfg(target_arch = "riscv64")]
1455        let (irq, vector) = (0, 0);
1456
1457        let bar = match pci_dev.read_bar(0) {
1458            Some(Bar::Memory64 { addr, .. }) => addr,
1459            _ => {
1460                log::warn!("NVMe: Invalid BAR0");
1461                continue;
1462            }
1463        };
1464
1465        paging::ensure_identity_map_range(bar, 0x10000);
1466        let registers = phys_to_virt(bar) as usize;
1467        let name = format!("nvme{}", i);
1468
1469        match unsafe {
1470            NvmeController::new(
1471                registers,
1472                name.clone(),
1473                crate::hardware::iommu::Sbdf::new(
1474                    0,
1475                    pci_dev.address.bus,
1476                    pci_dev.address.device,
1477                    pci_dev.address.function,
1478                ),
1479            )
1480        } {
1481            Ok(mut controller) => {
1482                controller.set_irq_line(irq);
1483                NVME_IRQ_LINE.store(vector, Ordering::Relaxed);
1484                log::info!(
1485                    "NVMe: {} initialized, IRQ={} vector={:#x}",
1486                    name,
1487                    irq,
1488                    vector
1489                );
1490                NVME_CONTROLLERS
1491                    .lock()
1492                    .push(Arc::new(SpinLock::new(controller)));
1493                #[cfg(target_arch = "x86_64")]
1494                crate::arch::x86_64::idt::register_nvme_irq_vector(vector);
1495            }
1496            Err(e) => {
1497                log::warn!("NVMe: Failed to initialize controller: {:?}", e);
1498            }
1499        }
1500    }
1501
1502    NVME_INITIALIZED.store(true, Ordering::SeqCst);
1503    log::info!(
1504        "[NVMe] Found {} controller(s)",
1505        NVME_CONTROLLERS.lock().len()
1506    );
1507}
1508
1509pub fn get_first_controller() -> Option<Arc<SpinLock<NvmeController>>> {
1510    NVME_CONTROLLERS.lock().first().cloned()
1511}
1512
1513pub fn is_available() -> bool {
1514    NVME_INITIALIZED.load(Ordering::Relaxed) && !NVME_CONTROLLERS.lock().is_empty()
1515}
1516
1517pub fn handle_interrupt() {
1518    if let Some(ctrl) = get_first_controller() {
1519        let controller = ctrl.lock();
1520        controller.handle_interrupt();
1521    }
1522}
1523
1524pub fn list_controllers() -> Vec<String> {
1525    NVME_CONTROLLERS
1526        .lock()
1527        .iter()
1528        .map(|c| c.lock().name.clone())
1529        .collect()
1530}