Skip to main content

strat9_kernel/hardware/storage/
virtio_block.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//! VirtIO Block Device driver
24//!
25//! Provides disk I/O via VirtIO-blk protocol for QEMU/KVM environments.
26//! Implements the BlockDevice trait for integration with filesystem layers.
27//!
28//! Reference: VirtIO spec v1.2, Section 5.2 (Block Device)
29
30use crate::{
31    dma::{DmaBuffer, DmaMapper},
32    hardware::{
33        iommu::{DmaProt, Sbdf},
34        pci_client::{self as pci, PciDevice},
35        virtio::{
36            common::{VirtioDevice, Virtqueue},
37            status,
38        },
39    },
40    memory,
41    sync::SpinLock,
42};
43use alloc::{boxed::Box, vec::Vec};
44use core::{mem, ptr, sync::atomic::Ordering};
45
46/// Block device sector size
47pub const SECTOR_SIZE: usize = 512;
48
49/// VirtIO block device features
50pub mod features {
51    pub const VIRTIO_BLK_F_SIZE_MAX: u32 = 1 << 1;
52    pub const VIRTIO_BLK_F_SEG_MAX: u32 = 1 << 2;
53    pub const VIRTIO_BLK_F_GEOMETRY: u32 = 1 << 4;
54    pub const VIRTIO_BLK_F_RO: u32 = 1 << 5;
55    pub const VIRTIO_BLK_F_BLK_SIZE: u32 = 1 << 6;
56    pub const VIRTIO_BLK_F_FLUSH: u32 = 1 << 9;
57    pub const VIRTIO_BLK_F_TOPOLOGY: u32 = 1 << 10;
58    pub const VIRTIO_BLK_F_CONFIG_WCE: u32 = 1 << 11;
59    pub const VIRTIO_BLK_F_DISCARD: u32 = 1 << 13;
60    pub const VIRTIO_BLK_F_WRITE_ZEROES: u32 = 1 << 14;
61}
62
63/// VirtIO block request types
64#[allow(dead_code)]
65#[repr(u32)]
66pub enum RequestType {
67    /// Read from device
68    In = 0,
69    /// Write to device
70    Out = 1,
71    /// Flush write cache
72    Flush = 4,
73    /// Get device ID
74    GetId = 8,
75    /// Discard sectors
76    Discard = 11,
77    /// Write zeroes
78    WriteZeroes = 13,
79}
80
81/// VirtIO block request header
82#[repr(C)]
83#[derive(Debug, Clone, Copy)]
84pub struct BlockRequestHeader {
85    pub request_type: u32,
86    pub reserved: u32,
87    pub sector: u64,
88}
89
90/// VirtIO block request status
91#[repr(u8)]
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum BlockStatus {
94    Ok = 0,
95    IoError = 1,
96    Unsupported = 2,
97}
98
99/// Block device configuration space
100#[repr(C)]
101#[allow(dead_code)]
102struct BlockConfig {
103    capacity: u64,
104    size_max: u32,
105    seg_max: u32,
106    geometry_cylinders: u16,
107    geometry_heads: u8,
108    geometry_sectors: u8,
109    blk_size: u32,
110    // ... other fields omitted for brevity
111}
112
113/// Block device trait (implemented by VirtIO-blk and AHCI drivers)
114pub trait BlockDevice {
115    /// Read a single sector from the device.
116    fn read_sector(&self, sector: u64, buf: &mut [u8]) -> Result<(), BlockError>;
117
118    /// Write a single sector to the device.
119    fn write_sector(&self, sector: u64, buf: &[u8]) -> Result<(), BlockError>;
120
121    /// Read multiple contiguous sectors in a single I/O operation.
122    ///
123    /// The default implementation falls back to calling `read_sector` in a loop.
124    /// Drivers that support multi-sector commands (AHCI, NVMe, VirtIO with large
125    /// descriptors) SHOULD override this for bulk throughput.
126    fn read_sectors(&self, sector: u64, count: u16, buf: &mut [u8]) -> Result<(), BlockError> {
127        let sector_size = SECTOR_SIZE;
128        for i in 0..count as u64 {
129            let off = (i as usize) * sector_size;
130            if off + sector_size > buf.len() {
131                return Err(BlockError::BufferTooSmall);
132            }
133            self.read_sector(sector + i, &mut buf[off..off + sector_size])?;
134        }
135        Ok(())
136    }
137
138    /// Write multiple contiguous sectors in a single I/O operation.
139    ///
140    /// The default implementation falls back to calling `write_sector` in a loop.
141    /// Drivers that support multi-sector commands SHOULD override this.
142    fn write_sectors(&self, sector: u64, count: u16, buf: &[u8]) -> Result<(), BlockError> {
143        let sector_size = SECTOR_SIZE;
144        for i in 0..count as u64 {
145            let off = (i as usize) * sector_size;
146            if off + sector_size > buf.len() {
147                return Err(BlockError::BufferTooSmall);
148            }
149            self.write_sector(sector + i, &buf[off..off + sector_size])?;
150        }
151        Ok(())
152    }
153
154    /// Get the total number of sectors on the device.
155    fn sector_count(&self) -> u64;
156
157    /// Flush the device's volatile write cache.
158    ///
159    /// A successful return must guarantee that every write which completed
160    /// before this call is durable on the medium. Returning `Ok(())` without
161    /// a device acknowledgement makes `fsync` lie, so this method has no
162    /// default implementation: every driver must state its durability policy
163    /// explicitly. A device with no volatile cache returns `Ok(())`.
164    fn flush(&self) -> Result<(), BlockError>;
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
168pub enum BlockError {
169    #[error("device I/O error")]
170    IoError,
171    #[error("invalid sector number")]
172    InvalidSector,
173    #[error("buffer too small")]
174    BufferTooSmall,
175    #[error("device not ready")]
176    NotReady,
177}
178
179/// Size of the pre-allocated bounce buffer pool (64 KB = 128 sectors).
180/// Requests up to this size avoid per-I/O buddy allocator calls.
181const BOUNCE_POOL_SIZE: usize = 64 * 1024;
182
183/// Pre-allocated DMA buffer used for all data transfers.
184///
185/// Eliminates per-I/O frame allocation/free for the common case.
186/// Large requests (> BOUNCE_POOL_SIZE) fall back to on-demand allocation.
187struct BouncePool {
188    buffer: DmaBuffer,
189}
190
191impl BouncePool {
192    /// Allocate a single physically-contiguous bounce buffer.
193    unsafe fn allocate(sbdf: Sbdf) -> Result<Self, BlockError> {
194        let buffer = DmaBuffer::alloc_for(sbdf, BOUNCE_POOL_SIZE, DmaProt::READ_WRITE)
195            .map_err(|_| BlockError::NotReady)?;
196        Ok(Self { buffer })
197    }
198
199    fn virt(&self) -> u64 {
200        self.buffer.virt_addr()
201    }
202
203    fn device(&self) -> u64 {
204        self.buffer.device_addr()
205    }
206}
207
208/// Pre-allocated metadata frame: [Header (16 B)] + padding + [Status (1 B)].
209/// Reused for every request : never alloc/freed per I/O.
210struct MetaPool {
211    buffer: DmaBuffer,
212}
213
214impl MetaPool {
215    unsafe fn allocate(sbdf: Sbdf) -> Result<Self, BlockError> {
216        let buffer = DmaBuffer::alloc_for(sbdf, 4096, DmaProt::READ_WRITE)
217            .map_err(|_| BlockError::NotReady)?;
218        Ok(Self { buffer })
219    }
220
221    fn virt(&self) -> u64 {
222        self.buffer.virt_addr()
223    }
224
225    fn device(&self) -> u64 {
226        self.buffer.device_addr()
227    }
228
229    /// Layout offset for the status byte (right after the header).
230    fn status_offset(&self) -> u64 {
231        mem::size_of::<BlockRequestHeader>() as u64
232    }
233}
234
235/// VirtIO Block Device driver
236pub struct VirtioBlockDevice {
237    device: VirtioDevice,
238    queue: SpinLock<Virtqueue>,
239    capacity: u64,
240    #[allow(dead_code)] // Retained negotiated device block size.
241    block_size: u32,
242    /// `VIRTIO_BLK_F_FLUSH` was offered by the device and negotiated, so a
243    /// `VIRTIO_BLK_T_FLUSH` request is legal and meaningful.
244    has_flush: bool,
245    /// Physical -> device address translator.
246    dma: DmaMapper,
247    /// Pre-allocated DMA resources : no per-I/O alloc/free for common requests.
248    bounce_pool: BouncePool,
249    meta_pool: MetaPool,
250}
251
252// Send and Sync are safe because we use SpinLocks
253unsafe impl Send for VirtioBlockDevice {}
254unsafe impl Sync for VirtioBlockDevice {}
255
256/// WaitQueue used for IRQ-driven completion (see `handle_interrupt` / `do_request`).
257static VIRTIO_BLK_WQ: crate::sync::WaitQueue = crate::sync::WaitQueue::new();
258
259/// Atomic flag set by the IRQ handler to signal request completion.
260static VIRTIO_BLK_DONE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
261
262/// Atomic flag set by the IRQ handler on error.
263static VIRTIO_BLK_ERROR: core::sync::atomic::AtomicBool =
264    core::sync::atomic::AtomicBool::new(false);
265
266impl VirtioBlockDevice {
267    /// Initialize a VirtIO block device from a PCI device
268    ///
269    /// # Safety
270    /// The PCI device must be a valid VirtIO block device
271    pub unsafe fn new(pci_dev: PciDevice) -> Result<Self, &'static str> {
272        log::info!("VirtIO-blk: Initializing device at {:?}", pci_dev.address);
273        let sbdf = Sbdf::new(
274            0,
275            pci_dev.address.bus,
276            pci_dev.address.device,
277            pci_dev.address.function,
278        );
279        let dma = DmaMapper::for_sbdf(sbdf);
280
281        // Pre-allocate DMA resources before touching the device.
282        let bounce_pool =
283            BouncePool::allocate(sbdf).map_err(|_| "Failed to allocate bounce pool")?;
284        let meta_pool = MetaPool::allocate(sbdf).map_err(|_| "Failed to allocate meta pool")?;
285
286        // Create VirtIO device
287        let device = VirtioDevice::new(pci_dev)?;
288
289        // Reset device
290        device.reset();
291
292        // Acknowledge device
293        device.add_status(status::ACKNOWLEDGE as u8);
294
295        // Indicate we know how to drive it
296        device.add_status(status::DRIVER as u8);
297
298        // Read and negotiate features
299        let device_features = device.read_device_features();
300        log::debug!("VirtIO-blk: Device features: 0x{:08x}", device_features);
301
302        // Negotiate useful block-device features (legacy PCI : all u32).
303        //   VIRTIO_BLK_F_BLK_SIZE  (1 << 6)  : honour device block size
304        //   VIRTIO_BLK_F_FLUSH     (1 << 9)  : write cache flush
305        //   VIRTIO_F_RING_EVENT_IDX(1 << 29) : suppress needless notifications
306        let dev_feat = device_features;
307        let mut guest_features: u32 = 0;
308        let has_blk_size = dev_feat & (1 << 6) != 0;
309        if has_blk_size {
310            guest_features |= 1 << 6;
311        }
312        let has_flush = dev_feat & (1 << 9) != 0;
313        if has_flush {
314            guest_features |= 1 << 9; // VIRTIO_BLK_F_FLUSH
315        }
316        if dev_feat & (1 << 29) != 0 {
317            guest_features |= 1 << 29; // VIRTIO_F_RING_EVENT_IDX
318        }
319        log::info!("VirtIO-blk: Negotiated features: 0x{:08x}", guest_features);
320        device.write_guest_features(guest_features);
321
322        // Features OK
323        device.add_status(status::FEATURES_OK as u8);
324
325        // Verify features OK
326        if device.get_status() & (status::FEATURES_OK as u8) == 0 {
327            return Err("Device doesn't support our feature set");
328        }
329
330        // Legacy PCI VirtIO exposes a fixed queue size in QUEUE_NUM.
331        // The vring layout must match exactly what the device expects.
332        let queue_size = device.queue_max_size(0);
333        if queue_size == 0 {
334            return Err("VirtIO-blk queue 0 is unavailable");
335        }
336        log::info!("VirtIO-blk: queue 0 size = {}", queue_size);
337
338        // Create virtqueue (queue 0 is the request queue)
339        let mut queue = Virtqueue::new(queue_size)?;
340
341        // Map the contiguous vring into the device domain (identity when the
342        // IOMMU is inactive).
343        {
344            let phys = queue.ring_phys();
345            let iova = dma.translate(phys, queue.ring_size(), DmaProt::READ_WRITE);
346            let delta = iova.wrapping_sub(phys);
347            queue.set_device_addresses(
348                queue.desc_area().wrapping_add(delta),
349                queue.avail_area().wrapping_add(delta),
350                queue.used_area().wrapping_add(delta),
351            );
352        }
353
354        // Setup queue with device
355        device.setup_queue(0, &queue);
356
357        // Driver ready
358        device.add_status(status::DRIVER_OK as u8);
359
360        // Read device capacity from config space (offset 0 in device-specific config)
361        // For legacy devices, device-specific config starts at offset 20 (after header)
362        let capacity_low = device.read_reg_u32(20);
363        let capacity_high = device.read_reg_u32(24);
364        let capacity = ((capacity_high as u64) << 32) | (capacity_low as u64);
365
366        // Read device block size if the feature was negotiated (offset 28).
367        let blk_size = if has_blk_size {
368            let sz = device.read_reg_u32(28);
369            if sz == 0 {
370                SECTOR_SIZE as u32
371            } else {
372                sz
373            }
374        } else {
375            SECTOR_SIZE as u32
376        };
377
378        log::info!(
379            "VirtIO-blk: Capacity: {} sectors ({} MB), block_size={}",
380            capacity,
381            (capacity * SECTOR_SIZE as u64) / (1024 * 1024),
382            blk_size,
383        );
384
385        log::info!("VirtIO-blk: Device initialized successfully");
386
387        Ok(Self {
388            device,
389            queue: SpinLock::new(queue),
390            capacity,
391            block_size: blk_size,
392            has_flush,
393            dma,
394            bounce_pool,
395            meta_pool,
396        })
397    }
398
399    /// Determine the DMA buffer strategy: use the pre-allocated pool when the
400    /// request fits; fall back to a per-I/O allocation for large transfers.
401    fn acquire_dma_buffer(
402        &self,
403        buf_size: usize,
404        is_write: bool,
405        src: Option<&[u8]>,
406    ) -> Result<(u64, u64, Option<(memory::PhysFrame, u8, u64, usize)>), BlockError> {
407        if buf_size <= BOUNCE_POOL_SIZE {
408            let virt = self.bounce_pool.virt();
409            if is_write {
410                if let Some(s) = src {
411                    unsafe {
412                        ptr::copy_nonoverlapping(s.as_ptr(), virt as *mut u8, buf_size);
413                    }
414                }
415            }
416            Ok((self.bounce_pool.device(), virt, None))
417        } else {
418            // Large request: fall back to per-I/O allocation.
419            let buf_pages = (buf_size + 4095) / 4096;
420            let buf_order = buf_pages.next_power_of_two().trailing_zeros() as u8;
421            let buf_frame = crate::sync::with_irqs_disabled(|token| {
422                memory::allocate_phys_contiguous(token, buf_order)
423            })
424            .map_err(|_| BlockError::NotReady)?;
425            let buf_phys = buf_frame.start_address.as_u64();
426            let buf_virt = crate::memory::phys_to_virt(buf_phys);
427            let buf_device = self.dma.translate(buf_phys, buf_size, DmaProt::READ_WRITE);
428            if is_write {
429                if let Some(s) = src {
430                    unsafe {
431                        ptr::copy_nonoverlapping(s.as_ptr(), buf_virt as *mut u8, buf_size);
432                    }
433                }
434            }
435            Ok((
436                buf_device,
437                buf_virt,
438                Some((buf_frame, buf_order, buf_device, buf_size)),
439            ))
440        }
441    }
442
443    fn release_dma_buffer(&self, allocated: Option<(memory::PhysFrame, u8, u64, usize)>) {
444        if let Some((frame, order, device, len)) = allocated {
445            self.dma.release(device, len);
446            crate::sync::with_irqs_disabled(|token| {
447                memory::free_phys_contiguous(token, frame, order);
448            });
449        }
450    }
451
452    /// Submit a block request and wait for completion
453    fn do_request(
454        &self,
455        request_type: RequestType,
456        sector: u64,
457        mut data_buf: Option<(&mut [u8], bool)>, // (buffer, is_write)
458    ) -> Result<(), BlockError> {
459        // ── Metadata (pre-allocated, reused : no per-I/O alloc) ──────────
460        let meta_phys = self.meta_pool.device();
461        let meta_virt = self.meta_pool.virt();
462        let status_off = self.meta_pool.status_offset();
463
464        let header_ptr = meta_virt as *mut BlockRequestHeader;
465        let status_ptr = (meta_virt + status_off) as *mut u8;
466        unsafe {
467            ptr::write(
468                header_ptr,
469                BlockRequestHeader {
470                    request_type: request_type as u32,
471                    reserved: 0,
472                    sector,
473                },
474            );
475            ptr::write(status_ptr, 0xFF);
476        }
477
478        // ── Data buffer (pool => fallback alloc) ──────────────────────────
479        let mut data_alloc: Option<(memory::PhysFrame, u8, u64, usize)> = None;
480        let mut dma_buf_virt: u64 = 0;
481
482        let mut buffers = Vec::with_capacity(3);
483        buffers.push((
484            meta_phys,
485            mem::size_of::<BlockRequestHeader>() as u32,
486            false,
487        ));
488
489        if let Some((buf, is_write)) = data_buf.as_mut() {
490            let buf_size = buf.len();
491            let (dma_phys, dma_virt, alloc) =
492                self.acquire_dma_buffer(buf_size, *is_write, Some(buf))?;
493            data_alloc = alloc;
494            dma_buf_virt = dma_virt;
495
496            let device_writable = !*is_write;
497            buffers.push((dma_phys, buf_size as u32, device_writable));
498        }
499
500        // 3. Status (Device Writable)
501        buffers.push((meta_phys + status_off, 1, true));
502
503        // ── Submit ────────────────────────────────────────────────────────
504        let mut queue = self.queue.lock();
505        let token = match queue.add_buffer(&buffers) {
506            Ok(t) => t,
507            Err(e) => {
508                drop(queue);
509                self.release_dma_buffer(data_alloc);
510                log::error!("VirtIO-blk: add_buffer failed: {}", e);
511                return Err(BlockError::IoError);
512            }
513        };
514        if queue.should_notify() {
515            self.device.notify_queue(0);
516        }
517        drop(queue);
518
519        // ── Completion ────────────────────────────────────────────────────
520        let has_data = data_buf.is_some();
521
522        if has_data && crate::process::current_task_id().is_some() {
523            // Task context: IRQ-driven via WaitQueue (avoids busy-polling).
524            VIRTIO_BLK_DONE.store(false, Ordering::Release);
525            VIRTIO_BLK_ERROR.store(false, Ordering::Release);
526            VIRTIO_BLK_WQ.wait_until(|| {
527                if VIRTIO_BLK_DONE.load(Ordering::Acquire) {
528                    VIRTIO_BLK_DONE.store(false, Ordering::Release);
529                    Some(())
530                } else {
531                    None
532                }
533            });
534            if VIRTIO_BLK_ERROR.load(Ordering::Acquire) {
535                VIRTIO_BLK_ERROR.store(false, Ordering::Release);
536                self.release_dma_buffer(data_alloc);
537                return Err(BlockError::IoError);
538            }
539        } else {
540            // Boot / no-task context: busy-poll.
541            let mut spins = 0u32;
542            loop {
543                let q = self.queue.lock();
544                if q.has_used() {
545                    if let Some((t, _)) = q.peek_used() {
546                        if t == token {
547                            drop(q);
548                            let mut q = self.queue.lock();
549                            q.get_used();
550                            break;
551                        }
552                    }
553                    // Used entry exists but not ours : drop lock and retry.
554                }
555                drop(q);
556                spins = spins.saturating_add(1);
557                if spins >= 5_000_000 {
558                    let isr = self.device.read_isr_status();
559                    log::error!(
560                        "VirtIO-blk: timeout sector={} token={} isr={}",
561                        sector,
562                        token,
563                        isr
564                    );
565                    self.release_dma_buffer(data_alloc);
566                    return Err(BlockError::IoError);
567                }
568                core::hint::spin_loop();
569            }
570        }
571
572        // ── Post-processing ──────────────────────────────────────────────
573        let status_byte = unsafe { ptr::read(status_ptr) };
574
575        if let Some((buf, is_write)) = data_buf {
576            if !is_write && status_byte == BlockStatus::Ok as u8 {
577                unsafe {
578                    ptr::copy_nonoverlapping(
579                        dma_buf_virt as *const u8,
580                        buf.as_mut_ptr(),
581                        buf.len(),
582                    );
583                }
584            }
585        }
586
587        self.release_dma_buffer(data_alloc);
588
589        if status_byte == BlockStatus::Ok as u8 {
590            Ok(())
591        } else {
592            log::error!("VirtIO-blk: Request failed with status {}", status_byte);
593            Err(BlockError::IoError)
594        }
595    }
596}
597
598impl BlockDevice for VirtioBlockDevice {
599    /// Reads sector.
600    fn read_sector(&self, sector: u64, buf: &mut [u8]) -> Result<(), BlockError> {
601        if sector >= self.capacity {
602            return Err(BlockError::InvalidSector);
603        }
604        if buf.len() < SECTOR_SIZE {
605            return Err(BlockError::BufferTooSmall);
606        }
607        self.do_request(RequestType::In, sector, Some((buf, false)))
608    }
609
610    /// Writes sector.
611    fn write_sector(&self, sector: u64, buf: &[u8]) -> Result<(), BlockError> {
612        if sector >= self.capacity {
613            return Err(BlockError::InvalidSector);
614        }
615        if buf.len() < SECTOR_SIZE {
616            return Err(BlockError::BufferTooSmall);
617        }
618        // Use the writable alias path: do_request copies the data into the DMA
619        // bounce buffer before issuing the command, so the const-to-mut cast is safe
620        // (the buffer is never written from the CPU side during a write request).
621        let buf_mut = buf.as_ptr() as *mut u8;
622        let buf_slice = unsafe { core::slice::from_raw_parts_mut(buf_mut, buf.len()) };
623        self.do_request(RequestType::Out, sector, Some((buf_slice, true)))
624    }
625
626    /// Read multiple sectors in a single I/O.
627    ///
628    /// VirtIO block uses a single descriptor whose length encodes the transfer
629    /// size, so `do_request` naturally handles multi-sector transfers when given
630    /// a large enough buffer.
631    fn read_sectors(&self, sector: u64, count: u16, buf: &mut [u8]) -> Result<(), BlockError> {
632        let nbytes = (count as usize) * SECTOR_SIZE;
633        if sector.saturating_add(count as u64) > self.capacity {
634            return Err(BlockError::InvalidSector);
635        }
636        if buf.len() < nbytes {
637            return Err(BlockError::BufferTooSmall);
638        }
639        self.do_request(RequestType::In, sector, Some((buf, false)))
640    }
641
642    /// Write multiple sectors in a single I/O.
643    fn write_sectors(&self, sector: u64, count: u16, buf: &[u8]) -> Result<(), BlockError> {
644        let nbytes = (count as usize) * SECTOR_SIZE;
645        if sector.saturating_add(count as u64) > self.capacity {
646            return Err(BlockError::InvalidSector);
647        }
648        if buf.len() < nbytes {
649            return Err(BlockError::BufferTooSmall);
650        }
651        let buf_mut = buf.as_ptr() as *mut u8;
652        let buf_slice = unsafe { core::slice::from_raw_parts_mut(buf_mut, buf.len()) };
653        self.do_request(RequestType::Out, sector, Some((buf_slice, true)))
654    }
655
656    /// Performs the sector count operation.
657    fn sector_count(&self) -> u64 {
658        self.capacity
659    }
660
661    /// Issues `VIRTIO_BLK_T_FLUSH` and waits for the device status byte.
662    ///
663    /// Without `VIRTIO_BLK_F_FLUSH` the device is specified to have no
664    /// volatile write-back cache, so there is nothing to make durable and the
665    /// call succeeds without touching the device.
666    fn flush(&self) -> Result<(), BlockError> {
667        if !self.has_flush {
668            return Ok(());
669        }
670        self.do_request(RequestType::Flush, 0, None)
671    }
672}
673
674/// Global VirtIO block device reference (leaked Box, never freed).
675static VIRTIO_BLOCK_PTR: core::sync::atomic::AtomicPtr<VirtioBlockDevice> =
676    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());
677
678/// VirtIO block IRQ line (will be set during init)
679static VIRTIO_BLOCK_IRQ: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0xFF);
680
681/// Initialize VirtIO block device
682///
683/// Scans PCI bus for VirtIO block devices and initializes the first one found.
684///
685/// Idempotent: `hardware::init()` and the component `storage_init` both call
686/// this, and a second probe would reset a live device.
687pub fn init() {
688    if !VIRTIO_BLOCK_PTR.load(Ordering::Acquire).is_null() {
689        return;
690    }
691    log::info!("VirtIO-blk: Scanning for devices...");
692
693    // Prefer strict class-based probe (mass storage), with fallback to
694    // vendor+device for odd firmware/virtual setups.
695    let pci_dev = match pci::probe_first(pci::ProbeCriteria {
696        vendor_id: Some(pci::vendor::VIRTIO),
697        device_id: Some(pci::device::VIRTIO_BLOCK),
698        class_code: Some(pci::class::MASS_STORAGE),
699        subclass: None,
700        prog_if: None,
701    })
702    .or_else(|| pci::find_virtio_device(pci::device::VIRTIO_BLOCK))
703    {
704        Some(dev) => dev,
705        None => {
706            log::warn!("VirtIO-blk: No block device found");
707            return;
708        }
709    };
710
711    // Read interrupt line from PCI config
712    let irq_line = pci_dev.read_config_u8(pci::config::INTERRUPT_LINE);
713
714    // Initialize device
715    match unsafe { VirtioBlockDevice::new(pci_dev) } {
716        Ok(device) => {
717            // Leak the Box to get a 'static reference : safe because the device
718            // lives for the entire kernel lifetime.
719            let leaked: &'static mut VirtioBlockDevice = Box::leak(Box::new(device));
720            VIRTIO_BLOCK_PTR.store(leaked as *mut VirtioBlockDevice, Ordering::Release);
721            VIRTIO_BLOCK_IRQ.store(irq_line, Ordering::Relaxed);
722
723            // Register IRQ handler in IDT
724            crate::arch::idt::register_virtio_block_irq(irq_line);
725
726            log::info!("VirtIO-blk: Device initialized on IRQ {}", irq_line);
727        }
728        Err(e) => {
729            log::error!("VirtIO-blk: Failed to initialize device: {}", e);
730        }
731    }
732}
733
734/// Handle VirtIO block device interrupt
735///
736/// Called from the IDT IRQ handler when the VirtIO device signals completion.
737/// Acknowledges the interrupt and wakes any task waiting in `do_request`.
738pub fn handle_interrupt() {
739    let ptr = VIRTIO_BLOCK_PTR.load(Ordering::Acquire);
740    if ptr.is_null() {
741        return;
742    }
743
744    // SAFETY: ptr is a valid leaked Box that lives forever.
745    let device = unsafe { &*ptr };
746
747    let isr_status = device.device.read_isr_status();
748    if isr_status == 0 {
749        return; // spurious
750    }
751
752    // Acknowledge the interrupt (legacy PCI: reading ISR acks it).
753    device.device.ack_interrupt();
754
755    // Signal completion to the waiting task.
756    // A real implementation would check which token(s) completed and signal
757    // the correct ones. For the current single-in-flight design, we just
758    // set the global flag and wake the first waiter.
759    VIRTIO_BLK_DONE.store(true, Ordering::Release);
760
761    // TODO: check task-file error status for proper VIRTIO_BLK_ERROR signalling.
762    VIRTIO_BLK_WQ.wake_one();
763
764    log::trace!("VirtIO-blk: Interrupt handled (ISR={})", isr_status);
765}
766
767/// Get the global VirtIO block device
768///
769/// Returns a `'static` reference that is valid for the entire kernel lifetime.
770/// The device is initialised once during boot and never removed.
771pub fn get_device() -> Option<&'static VirtioBlockDevice> {
772    let ptr = VIRTIO_BLOCK_PTR.load(Ordering::Acquire);
773    if ptr.is_null() {
774        None
775    } else {
776        // SAFETY: ptr was obtained from Box::leak, so it is valid for 'static.
777        Some(unsafe { &*ptr })
778    }
779}
780
781/// Get the VirtIO block IRQ line
782pub fn get_irq() -> u8 {
783    VIRTIO_BLOCK_IRQ.load(Ordering::Relaxed)
784}