garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/drivers/usb/storage.rs

raw

//! USB sticks and disks (USB Mass Storage, Bulk-Only Transport 1.0): SCSI
//! commands in a wrapper on the bulk out endpoint, the data on the bulk in
//! or out one, the status back on the bulk in one. Each is a disk
//! (`usb0`), whose requests go as runs of up to [`RUN`] blocks a command.
//! One pulled out fails its next request, and is dropped from the disks.

use super::{Controller, Descriptor, Interface, configure_endpoints, watch_storage};
use crate::drivers::block::{self, BLOCK, Data, Op};
use crate::mm::pages;
use crate::println;
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

/// Blocks a command moves at most: 64 KiB, the buffer's size.
const RUN: usize = 16;
const BUFFER_ORDER: usize = 4;
const _: () = assert!(RUN * BLOCK == crate::mm::PAGE << BUFFER_ORDER);

const SCSI_TEST_UNIT_READY: u8 = 0x00;
const SCSI_INQUIRY: u8 = 0x12;
const SCSI_READ_CAPACITY: u8 = 0x25;
const SCSI_READ: u8 = 0x28;
const SCSI_WRITE: u8 = 0x2a;
const SCSI_SYNCHRONIZE_CACHE: u8 = 0x35;

/// The disks found while the controllers were set up at boot, for
/// `block::init` to take.
static FOUND: SpinLock<Vec<Arc<dyn block::Controller>>> = SpinLock::new(Vec::new());
/// Sticks numbered as found.
static NEXT: AtomicUsize = AtomicUsize::new(0);
/// Whether `block::init` has run: a stick found after it is added to the
/// disks then and there.
static BOOTED: AtomicBool = AtomicBool::new(false);

/// The disks found at boot. From now on, a stick plugged in is added as it
/// comes.
pub fn find() -> Vec<Arc<dyn block::Controller>> {
    BOOTED.store(true, Ordering::Relaxed);
    core::mem::take(&mut *FOUND.lock())
}

/// A stick: its controller, slot and endpoints, and a page for the command
/// wrapper and status.
pub struct Stick {
    controller: Arc<Controller>,
    slot: u8,
    out: u8,
    into: u8,
    lun: u8,
    /// The wrapper and status at 0 and 64, and the data buffer.
    scratch: usize,
    buffer: usize,
    tag: SpinLock<u32>,
    sectors: u64,
    sector: u64,
    gone: Arc<AtomicBool>,
    name: String,
    model: String,
}

impl Stick {
    /// Sends SCSI command `cdb`, with `length` bytes of data from or into
    /// the buffer. True when the device says it succeeded. The caller holds
    /// the controller's lock for synchronous work.
    fn command(&self, cdb: &[u8], length: usize, into_host: bool) -> bool {
        if self.gone.load(Ordering::Relaxed) {
            return false;
        }
        let tag = {
            let mut t = self.tag.lock();
            *t = t.wrapping_add(1);
            *t
        };
        // SAFETY: the scratch page, ours while no transfer uses it.
        unsafe {
            let w = self.scratch as *mut u8;
            core::ptr::write_bytes(w, 0, 128);
            core::ptr::copy_nonoverlapping(b"USBC".as_ptr(), w, 4);
            core::ptr::copy_nonoverlapping(tag.to_le_bytes().as_ptr(), w.add(4), 4);
            core::ptr::copy_nonoverlapping((length as u32).to_le_bytes().as_ptr(), w.add(8), 4);
            w.add(12).write(if into_host { 0x80 } else { 0 });
            w.add(13).write(self.lun);
            w.add(14).write(cdb.len() as u8);
            core::ptr::copy_nonoverlapping(cdb.as_ptr(), w.add(15), cdb.len());
        }
        if self.controller.bulk(self.slot, self.out, self.scratch, 31) != Some(31) {
            return false;
        }
        if length > 0 {
            let endpoint = if into_host { self.into } else { self.out };
            if self
                .controller
                .bulk(self.slot, endpoint, self.buffer, length)
                .is_none()
            {
                return false;
            }
        }
        if self.controller.bulk(self.slot, self.into, self.scratch + 64, 13) != Some(13) {
            return false;
        }
        // SAFETY: the status the device wrote.
        let status = unsafe { core::slice::from_raw_parts((self.scratch + 64) as *const u8, 13) };
        &status[..4] == b"USBS" && status[4..8] == tag.to_le_bytes() && status[12] == 0
    }

    /// The first `n` bytes of the data buffer, as the device left them.
    fn buffer(&self, n: usize) -> &[u8] {
        // SAFETY: the data buffer, ours while no transfer uses it; the
        // caller holds the controller's lock for its stick.
        unsafe { core::slice::from_raw_parts(self.buffer as *const u8, n) }
    }

    /// Puts `from` at the data buffer's start, for the device to read.
    fn fill(&self, at: usize, from: &[u8]) {
        // SAFETY: as in `buffer`; within its 64 KiB.
        unsafe { core::ptr::copy_nonoverlapping(from.as_ptr(), (self.buffer + at) as *mut u8, from.len()) }
    }
}

/// A run of `count` blocks from `first`, as READ(10) or WRITE(10) has it.
fn cdb(op: u8, lba: u64, sectors: u16) -> [u8; 10] {
    let l = (lba as u32).to_be_bytes();
    let n = sectors.to_be_bytes();
    [op, 0, l[0], l[1], l[2], l[3], 0, n[0], n[1], 0]
}

impl block::Controller for Stick {
    fn transfer(&self, op: Op, blocks: &[u64], mut data: Data) -> bool {
        let _one = self.controller.ops.lock();
        if op == Op::Flush {
            return self.command(&[SCSI_SYNCHRONIZE_CACHE, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0, false);
        }
        let per_block = BLOCK as u64 / self.sector;
        let mut at = 0;
        while at < blocks.len() {
            // A run of consecutive blocks, as one command.
            let mut n = 1;
            while n < RUN && at + n < blocks.len() && blocks[at + n] == blocks[at] + n as u64 {
                n += 1;
            }
            let lba = blocks[at] * per_block;
            if lba + n as u64 * per_block > u64::from(u32::MAX) {
                return false;
            }
            let sectors = (n as u64 * per_block) as u16;
            let ok = match &mut data {
                Data::Into(into) => {
                    let ok = self.command(&cdb(SCSI_READ, lba, sectors), n * BLOCK, true);
                    let got = self.buffer(n * BLOCK);
                    for k in 0..n {
                        into[at + k].copy_from_slice(&got[k * BLOCK..(k + 1) * BLOCK]);
                    }
                    ok
                }
                Data::From(from) => {
                    for k in 0..n {
                        self.fill(k * BLOCK, &from[at + k]);
                    }
                    self.command(&cdb(SCSI_WRITE, lba, sectors), n * BLOCK, false)
                }
                Data::None => false,
            };
            if !ok {
                return false;
            }
            at += n;
        }
        true
    }

    fn blocks(&self) -> u64 {
        self.sectors * self.sector / BLOCK as u64
    }

    fn sector(&self) -> u64 {
        self.sector
    }

    fn write_cache(&self) -> bool {
        true
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn model(&self) -> &str {
        &self.model
    }

    fn removable(&self) -> bool {
        true
    }
}

/// Takes interface `interface` of the device in `slot` when it is mass
/// storage over Bulk-Only Transport with SCSI commands.
pub fn attach(
    controller: &Arc<Controller>,
    slot: u8,
    port: u8,
    d: &Descriptor,
    interface: &Interface,
) -> bool {
    // SCSI transparent command set (6), Bulk-Only (0x50).
    if interface.subclass != 6 || interface.protocol != 0x50 {
        return false;
    }
    let bulk = |into: bool| {
        interface
            .endpoints
            .iter()
            .find(|e| e.1 & 3 == 2 && (e.0 & 0x80 != 0) == into)
            .copied()
    };
    let (Some(into), Some(out)) = (bulk(true), bulk(false)) else {
        return false;
    };
    let Some(dcis) = configure_endpoints(controller, slot, &[into, out]) else {
        return false;
    };
    let (Some(scratch), Some(buffer)) = (pages::alloc(0), pages::alloc(BUFFER_ORDER)) else {
        return false;
    };
    let gone = Arc::new(AtomicBool::new(false));
    let mut stick = Stick {
        controller: controller.clone(),
        slot,
        into: dcis[0],
        out: dcis[1],
        lun: 0,
        scratch,
        buffer,
        tag: SpinLock::new(0),
        sectors: 0,
        sector: 512,
        gone: gone.clone(),
        name: alloc::format!("usb{}", NEXT.fetch_add(1, Ordering::Relaxed)),
        model: d.product_name.clone(),
    };
    // The device may need a moment after it is configured: asked until ready.
    let deadline = crate::timer::now_ms() + 3_000;
    while !stick.command(&[SCSI_TEST_UNIT_READY, 0, 0, 0, 0, 0], 0, false) {
        if crate::timer::now_ms() > deadline {
            println!(
                "usb{}: port {port}: {} is not ready",
                controller.number, d.product_name
            );
            return false;
        }
    }
    if stick.command(&[SCSI_INQUIRY, 0, 0, 0, 36, 0], 36, true) {
        let inquiry = stick.buffer(36);
        let vendor = String::from(String::from_utf8_lossy(&inquiry[8..16]).trim());
        let product = String::from(String::from_utf8_lossy(&inquiry[16..32]).trim());
        stick.model = alloc::format!("{vendor} {product}").trim().into();
    }
    if !stick.command(&[SCSI_READ_CAPACITY, 0, 0, 0, 0, 0, 0, 0, 0, 0], 8, true) {
        return false;
    }
    let capacity = stick.buffer(8);
    let last = u32::from_be_bytes(capacity[..4].try_into().unwrap());
    let sector = u32::from_be_bytes(capacity[4..8].try_into().unwrap());
    if !matches!(sector, 512 | 4096) || last == 0 {
        println!(
            "usb{}: port {port}: blocks of {sector} bytes, left alone",
            controller.number
        );
        return false;
    }
    stick.sectors = u64::from(last) + 1;
    stick.sector = u64::from(sector);
    watch_storage(controller, slot, gone, stick.name.clone());
    let line = alloc::format!(
        "storage {} ({}, {} MiB)",
        stick.name,
        stick.model,
        (stick.sectors * stick.sector) >> 20
    );
    println!("usb{}: port {port}: {line}", controller.number);
    super::hid::ATTACHED.lock().push(line);
    let stick: Arc<dyn block::Controller> = Arc::new(stick);
    if BOOTED.load(Ordering::Relaxed) {
        block::add_controller(stick);
    } else {
        FOUND.lock().push(stick);
    }
    true
}