garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/serial.rs

raw

//! Serial ports to the device's radios: the Bluetooth controller, the
//! cellular modem and the Wi-Fi radio. On QEMU each is a virtio-console
//! (`virtconsole`, one port) whose other end `cargo xtask` holds, in that
//! order: the first console found is the Bluetooth controller's, the
//! second the modem's, the third the Wi-Fi radio's; on a board, the UARTs
//! they hang off. Bytes both ways, as a channel to the one program that
//! opens a port (the `bluetooth` service, the `phone` service, the `wifi`
//! service): what the program sends goes out, what comes in arrives as
//! messages. Framing (H4, AT lines) is the program's business.

use super::virtio::{self, Buffer, Queue, Transport};
use crate::mm::pages;
use crate::object::{Endpoint, Message};
use crate::sync::SpinLock;
use alloc::sync::Arc;
use alloc::vec::Vec;

/// Buffers offered for what comes in, and pages for what goes out.
const RX_BUFFERS: usize = 16;
const RX_BUFFER: usize = 2048;
const TX_PAGES: usize = 8;

struct Device {
    transport: Transport,
    rx: Queue,
    tx: Queue,
    rx_pages: [usize; RX_BUFFERS / 2],
    tx_pages: [usize; TX_PAGES],
    tx_heads: [Option<u16>; TX_PAGES],
    /// The kernel's end of the open program's channel.
    subscriber: Option<Arc<Endpoint>>,
}

impl Device {
    fn rx_buffer(&self, i: usize) -> usize {
        self.rx_pages[i / 2] + (i % 2) * RX_BUFFER
    }

    fn offer_rx(&mut self, i: usize) {
        self.rx.offer(&[Buffer {
            address: self.rx_buffer(i),
            len: RX_BUFFER,
            device_writes: true,
        }]);
    }
}
/// Which port: the order their consoles are found in.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Port {
    Bluetooth = 0,
    Modem = 1,
    Wifi = 2,
}

const PORTS: usize = 3;

static SERIAL: [SpinLock<Option<Device>>; PORTS] = [const { SpinLock::new(None) }; PORTS];

/// Sets up the first three virtio-consoles. Returns how many there are.
pub fn init() -> usize {
    let mut found = 0;
    for transport in virtio::find(virtio::device::CONSOLE).take(PORTS) {
        let Some(device) = setup(transport) else { break };
        let intid = transport.intid;
        *SERIAL[found].lock() = Some(device);
        crate::gic::enable_shared(intid);
        found += 1;
    }
    found
}

fn setup(transport: Transport) -> Option<Device> {
    transport.begin(0)?;
    let rx = Queue::new(transport, 0);
    let tx = Queue::new(transport, 1);
    let mut rx_pages = [0; RX_BUFFERS / 2];
    let mut tx_pages = [0; TX_PAGES];
    for page in rx_pages.iter_mut().chain(tx_pages.iter_mut()) {
        *page = pages::alloc(0)?;
    }
    let mut device = Device {
        transport,
        rx,
        tx,
        rx_pages,
        tx_pages,
        tx_heads: [None; TX_PAGES],
        subscriber: None,
    };
    for i in 0..RX_BUFFERS {
        device.offer_rx(i);
    }
    transport.ready();
    Some(device)
}

/// The port as a channel: the program's end. What arrived before is not
/// kept; an earlier opener's channel closes.
pub fn open(port: Port) -> Option<Arc<Endpoint>> {
    let mut guard = SERIAL[port as usize].lock();
    let device = guard.as_mut()?;
    let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Serial(port));
    let old = device.subscriber.replace(kernel);
    drop(guard);
    drop(old);
    Some(program)
}

/// A device's interrupt: bytes arrived, or sent. False if `intid` is no
/// port's.
pub fn interrupt(intid: u32) -> bool {
    SERIAL.iter().any(|port| port_interrupt(port, intid))
}

fn port_interrupt(port: &SpinLock<Option<Device>>, intid: u32) -> bool {
    let mut guard = port.lock();
    let Some(device) = guard.as_mut() else {
        return false;
    };
    if device.transport.intid != intid {
        return false;
    }
    device.transport.acknowledge();
    let mut out = Vec::new();
    while let Some((head, len)) = device.rx.take_used() {
        // Offered in order, one descriptor each: the head is the buffer.
        let i = head as usize % RX_BUFFERS;
        let at = device.rx_buffer(i);
        let len = (len as usize).min(RX_BUFFER);
        // SAFETY: the device wrote `len` bytes into this buffer.
        let bytes = unsafe { core::slice::from_raw_parts(at as *const u8, len) }.to_vec();
        if !bytes.is_empty() {
            out.push(bytes);
        }
        device.offer_rx(i);
    }
    while let Some((head, _)) = device.tx.take_used() {
        if let Some(slot) = device.tx_heads.iter().position(|h| *h == Some(head)) {
            device.tx_heads[slot] = None;
        }
    }
    let subscriber = device.subscriber.clone();
    drop(guard);
    if let Some(subscriber) = subscriber {
        for bytes in out {
            for chunk in bytes.chunks(pinnacle_abi::MAX_MESSAGE) {
                subscriber.send(Message {
                    bytes: chunk.to_vec(),
                    handles: Vec::new(),
                });
            }
        }
    }
    true
}

/// The program sent bytes: out they go, a page at a time. With every page
/// in flight they are dropped, as a UART with a full buffer would.
pub fn sink_send(port: Port, bytes: &[u8]) {
    let mut guard = SERIAL[port as usize].lock();
    let Some(device) = guard.as_mut() else { return };
    while let Some((head, _)) = device.tx.take_used() {
        if let Some(slot) = device.tx_heads.iter().position(|h| *h == Some(head)) {
            device.tx_heads[slot] = None;
        }
    }
    for chunk in bytes.chunks(crate::mm::PAGE) {
        let Some(slot) = device.tx_heads.iter().position(Option::is_none) else {
            return;
        };
        let page = device.tx_pages[slot];
        // SAFETY: a tx page the device does not hold.
        unsafe { core::ptr::copy_nonoverlapping(chunk.as_ptr(), page as *mut u8, chunk.len()) };
        device.tx_heads[slot] = device.tx.offer(&[Buffer {
            address: page,
            len: chunk.len(),
            device_writes: false,
        }]);
    }
}

/// The program let go of the port.
pub fn sink_close(port: Port) {
    let old = SERIAL[port as usize]
        .lock()
        .as_mut()
        .and_then(|d| d.subscriber.take());
    drop(old);
}

/// Whether `port` was set up.
pub fn present(port: Port) -> bool {
    SERIAL[port as usize].lock().is_some()
}