garage44.eu/jeroen/pinnacle

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

.. /kernel/src/object.rs

raw

//! What programs reach through handles: channels, shared memory, programs
//! and files.
//!
//! A channel is two endpoints, each with an inbox. Sending puts a message in
//! the peer's inbox and wakes whoever waits on it; receiving takes from one's
//! own. A task that finds every inbox it waits on empty registers itself on
//! each and blocks; a send, or the peer closing, wakes it.

use crate::mm::{PAGE, pages};
use crate::sync::SpinLock;
use alloc::collections::VecDeque;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;

#[derive(Clone)]
pub enum Object {
    Channel(Arc<Endpoint>),
    Memory(Arc<Memory>),
    /// A program, as its starter holds it: what may end it (KILL). It does
    /// not keep the program alive.
    Process(Weak<crate::sync::SpinLock<crate::sched::Process>>),
    /// One file, with the rights its opener was given ([`OpenFile`]).
    File(Arc<OpenFile>),
}

/// A file as a handle holds it: its path, checked against the opener's
/// confinement when it was opened and never again, and what may be done to
/// it (`pinnacle_abi::file`). It names the file by its path, not its inode:
/// a file removed and made again under that name is the one it reaches.
pub struct OpenFile {
    pub path: alloc::string::String,
    pub rights: u64,
}

pub struct Message {
    pub bytes: Vec<u8>,
    pub handles: Vec<Object>,
}

#[derive(Default)]
pub struct Inbox {
    pub messages: VecDeque<Message>,
    /// Tasks blocked until something arrives.
    pub waiters: Vec<usize>,
    /// The peer is gone: nothing more will arrive.
    pub closed: bool,
}

/// Where a kernel-held channel end delivers to instead of its inbox: a
/// device the channel stands for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Sink {
    /// A TCP connection or UDP socket.
    Net(crate::drivers::net::Sink),
    /// A playback or capture stream.
    Audio(crate::drivers::sound::Stream),
    /// A serial port to a radio: the Bluetooth controller, the modem or
    /// the Wi-Fi radio.
    Serial(crate::drivers::serial::Port),
    /// A program's context on the 3D GPU.
    Gpu(u32),
}

impl Sink {
    fn send(self, bytes: &[u8]) {
        match self {
            Sink::Net(socket) => crate::drivers::net::sink_send(socket, bytes),
            Sink::Audio(stream) => crate::drivers::sound::sink_send(stream, bytes),
            Sink::Serial(port) => crate::drivers::serial::sink_send(port, bytes),
            Sink::Gpu(ctx) => crate::drivers::gpu3d::sink_send(ctx, bytes),
        }
    }

    fn close(self) {
        match self {
            Sink::Net(socket) => crate::drivers::net::sink_close(socket),
            Sink::Audio(stream) => crate::drivers::sound::sink_close(stream),
            Sink::Serial(port) => crate::drivers::serial::sink_close(port),
            Sink::Gpu(ctx) => crate::drivers::gpu3d::sink_close(ctx),
        }
    }
}

pub struct Endpoint {
    pub inbox: SpinLock<Inbox>,
    peer: SpinLock<Weak<Endpoint>>,
    /// The kernel's end of a channel that stands for a device: what is
    /// delivered here goes to the device instead of into the inbox.
    sink: Option<Sink>,
}

impl Endpoint {
    /// A new channel's two ends.
    pub fn pair() -> (Arc<Endpoint>, Arc<Endpoint>) {
        Self::pair_inner(None)
    }

    /// A channel whose second end feeds a device.
    pub fn pair_with_sink(sink: Sink) -> (Arc<Endpoint>, Arc<Endpoint>) {
        Self::pair_inner(Some(sink))
    }

    fn pair_inner(sink: Option<Sink>) -> (Arc<Endpoint>, Arc<Endpoint>) {
        let a = Arc::new(Endpoint {
            inbox: SpinLock::new(Inbox::default()),
            peer: SpinLock::new(Weak::new()),
            sink: None,
        });
        let b = Arc::new(Endpoint {
            inbox: SpinLock::new(Inbox::default()),
            peer: SpinLock::new(Arc::downgrade(&a)),
            sink,
        });
        *a.peer.lock() = Arc::downgrade(&b);
        (a, b)
    }

    /// Delivers to the peer. False when the peer is gone.
    pub fn send(&self, message: Message) -> bool {
        let Some(peer) = self.peer.lock().upgrade() else {
            return false;
        };
        peer.deliver(message);
        true
    }

    /// Puts a message in this end's own inbox and wakes its waiters.
    pub fn deliver(&self, message: Message) {
        if let Some(sink) = self.sink {
            return sink.send(&message.bytes);
        }
        let waiters = {
            let mut inbox = self.inbox.lock();
            inbox.messages.push_back(message);
            core::mem::take(&mut inbox.waiters)
        };
        for task in waiters {
            crate::sched::wake(task);
        }
    }
}

impl Drop for Endpoint {
    /// Tells the peer nothing more will come.
    fn drop(&mut self) {
        let peer = self.peer.lock().upgrade();
        if let Some(peer) = peer {
            if let Some(sink) = peer.sink {
                // The program let go of its connection or stream.
                sink.close();
            }
            let waiters = {
                let mut inbox = peer.inbox.lock();
                inbox.closed = true;
                core::mem::take(&mut inbox.waiters)
            };
            for task in waiters {
                crate::sched::wake(task);
            }
        }
    }
}

/// Physically contiguous pages several programs can map.
pub struct Memory {
    /// Kernel address of the first page.
    pub address: usize,
    pub size: usize,
    /// Whose the pages are, given back with the last hold (handle, mapping,
    /// or the display's, for a framebuffer).
    owner: Owner,
}

enum Owner {
    /// A block of the kernel's pages, of this order.
    Pages(usize),
    /// The host's, shared by the 3D GPU into its window: a blob resource
    /// mapped `offset` bytes in.
    Gpu { resource: u32, offset: u64 },
    /// A block of the kernel's pages, of this order, that the 3D GPU uses as
    /// they are: guest blob `resource`, let go by the host before the pages
    /// are freed.
    GuestGpu { order: usize, resource: u32 },
}

impl Memory {
    pub fn new(size: usize) -> Option<Arc<Memory>> {
        let size = size.next_multiple_of(PAGE);
        let order = pages::order_for(size);
        if order > pages::MAX_ORDER {
            return None;
        }
        let address = pages::alloc(order)?;
        // SAFETY: just allocated, ours alone.
        unsafe { core::ptr::write_bytes(address as *mut u8, 0, PAGE << order) };
        Some(Arc::new(Memory {
            address,
            size,
            owner: Owner::Pages(order),
        }))
    }

    /// The host's memory the 3D GPU shares at kernel address `address`: blob
    /// `resource`, mapped `offset` bytes into the window. Given back to the
    /// host with the last hold.
    pub fn gpu(address: usize, size: usize, resource: u32, offset: u64) -> Arc<Memory> {
        Arc::new(Memory {
            address,
            size,
            owner: Owner::Gpu { resource, offset },
        })
    }

    /// At least `size` bytes of the kernel's pages, zeroed and contiguous (a
    /// block of 2^order pages, 16 KiB at least: the host maps them by its
    /// own pages), made a guest blob by `blob` from their physical address
    /// and size. None when there are no such pages or no blob.
    pub fn guest_gpu(size: usize, blob: impl FnOnce(u64, u64) -> Option<u32>) -> Option<(Arc<Memory>, u32)> {
        let order = pages::order_for(size.next_multiple_of(PAGE)).max(2);
        if order > pages::MAX_ORDER {
            return None;
        }
        let address = pages::alloc(order)?;
        let size = PAGE << order;
        // SAFETY: just allocated, ours alone.
        unsafe { core::ptr::write_bytes(address as *mut u8, 0, size) };
        let Some(resource) = blob(crate::mmu::physical(address) as u64, size as u64) else {
            pages::free(address, order);
            return None;
        };
        let memory = Arc::new(Memory {
            address,
            size,
            owner: Owner::GuestGpu { order, resource },
        });
        Some((memory, resource))
    }
}

impl Drop for Memory {
    fn drop(&mut self) {
        match self.owner {
            Owner::Pages(order) => pages::free(self.address, order),
            Owner::Gpu { resource, offset } => {
                crate::drivers::gpu3d::release_blob(resource, offset, self.size as u64)
            }
            Owner::GuestGpu { order, resource } => {
                crate::drivers::gpu3d::release_guest_blob(resource);
                pages::free(self.address, order);
            }
        }
    }
}

/// Names programs register, each with the endpoint connections arrive on.
static SERVICES: SpinLock<Vec<(Vec<u8>, Arc<Endpoint>)>> = SpinLock::new(Vec::new());

/// Registers `name`: each connection arrives in `server`'s inbox as a
/// message carrying the new channel's server end. False if the name is
/// taken by a server still holding its endpoint.
pub fn register(name: &[u8], server: Arc<Endpoint>) -> bool {
    let mut services = SERVICES.lock();
    services.retain(|(_, endpoint)| Arc::strong_count(endpoint) > 1);
    if services.iter().any(|(n, _)| n == name) {
        return false;
    }
    services.push((name.to_vec(), server));
    true
}

/// The names registered by servers that still hold their endpoints.
pub fn services() -> Vec<Vec<u8>> {
    let mut names: Vec<Vec<u8>> = SERVICES
        .lock()
        .iter()
        .filter(|(_, e)| Arc::strong_count(e) > 1)
        .map(|(n, _)| n.clone())
        .collect();
    names.sort();
    names
}

/// A channel to the service `name`: the caller's end.
pub fn connect(name: &[u8]) -> Option<Arc<Endpoint>> {
    let server = SERVICES
        .lock()
        .iter()
        .find(|(n, e)| n == name && Arc::strong_count(e) > 1)?
        .1
        .clone();
    let (client, ours) = Endpoint::pair();
    server.deliver(Message {
        bytes: Vec::new(),
        handles: alloc::vec![Object::Channel(ours)],
    });
    Some(client)
}