Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Microkit-releated improvements #154

Merged
merged 7 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions crates/sel4-microkit/base/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::MessageInfo;
const BASE_OUTPUT_NOTIFICATION_SLOT: usize = 10;
const BASE_ENDPOINT_SLOT: usize = BASE_OUTPUT_NOTIFICATION_SLOT + 64;
const BASE_IRQ_SLOT: usize = BASE_ENDPOINT_SLOT + 64;
const BASE_TCB_SLOT: usize = BASE_IRQ_SLOT + 64;

const MAX_CHANNELS: usize = 63;

Expand Down Expand Up @@ -79,3 +80,20 @@ impl fmt::Display for IrqAckError {
write!(f, "irq ack error: {:?}", self.inner())
}
}

/// A handle to a child protection domain, identified by a child protection domain index.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ProtectionDomain {
index: usize,
}

impl ProtectionDomain {
pub const fn new(index: usize) -> Self {
Self { index }
}

#[doc(hidden)]
pub fn tcb(&self) -> sel4::cap::Tcb {
sel4::Cap::from_bits((BASE_TCB_SLOT + self.index) as sel4::CPtrBits)
}
}
112 changes: 112 additions & 0 deletions crates/sel4-microkit/base/src/handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

use core::fmt;

use crate::{
defer::{DeferredAction, PreparedDeferredAction},
ipc::{self, Event},
pd_is_passive, Channel, MessageInfo, ProtectionDomain,
};

pub use core::convert::Infallible;

/// Trait for the application-specific part of a protection domain's main loop.
pub trait Handler {
/// Error type returned by this protection domain's entrypoints.
type Error: fmt::Display;

/// This method has the same meaning and type as its analog in `libmicrokit`.
///
/// The default implementation just panics.
fn notified(&mut self, channel: Channel) -> Result<(), Self::Error> {
panic!("unexpected notification from channel {channel:?}")
}

/// This method has the same meaning and type as its analog in `libmicrokit`.
///
/// The default implementation just panics.
fn protected(
&mut self,
channel: Channel,
msg_info: MessageInfo,
) -> Result<MessageInfo, Self::Error> {
panic!("unexpected protected procedure call from channel {channel:?} with msg_info={msg_info:?}")
}

fn fault(
&mut self,
pd: ProtectionDomain,
msg_info: MessageInfo,
) -> Result<MessageInfo, Self::Error> {
panic!("unexpected fault from protection domain {pd:?} with msg_info={msg_info:?}")
}

/// An advanced feature for use by protection domains which seek to coalesce syscalls when
/// possible.
///
/// This method is used by the main loop to fuse a queued `seL4_Send` call with the next
/// `seL4_Recv` using `seL4_NBSendRecv`. Its default implementation just returns `None`.
fn take_deferred_action(&mut self) -> Option<DeferredAction> {
None
}

#[doc(hidden)]
fn run(&mut self) -> Result<Never, Self::Error> {
let mut reply_tag: Option<MessageInfo> = None;

let mut prepared_deferred_action: Option<PreparedDeferredAction> = if pd_is_passive() {
Some(ipc::forfeit_sc())
} else {
None
};

loop {
let event = match (reply_tag.take(), prepared_deferred_action.take()) {
(Some(msg_info), None) => ipc::reply_recv(msg_info),
(None, Some(action)) => ipc::nb_send_recv(action),
(None, None) => ipc::recv(),
_ => panic!("handler yielded deferred action after call to 'protected()'"),
};

match event {
Event::Notified(notified_event) => {
for channel in notified_event.iter() {
self.notified(channel)?;
}
}
Event::Protected(channel, msg_info) => {
reply_tag = Some(self.protected(channel, msg_info)?);
}
Event::Fault(pd, msg_info) => {
reply_tag = Some(self.fault(pd, msg_info)?);
}
};

prepared_deferred_action = self
.take_deferred_action()
.as_ref()
.map(DeferredAction::prepare);
}
}
}

#[doc(hidden)]
pub enum Never {}

/// A [`Handler`] implementation which does not override any of the default method implementations.
pub struct NullHandler(());

impl NullHandler {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self(())
}
}

impl Handler for NullHandler {
type Error = Infallible;
}
111 changes: 111 additions & 0 deletions crates/sel4-microkit/base/src/ipc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

use crate::MessageInfo;

use crate::{defer::PreparedDeferredAction, Channel, ProtectionDomain};

const INPUT_CAP: sel4::cap::Endpoint = sel4::Cap::from_bits(1);
const REPLY_CAP: sel4::cap::Reply = sel4::Cap::from_bits(4);
const MONITOR_EP_CAP: sel4::cap::Endpoint = sel4::Cap::from_bits(5);

const CHANNEL_BADGE_BIT: usize = 63;
const PD_BADGE_BIT: usize = 62;

fn strip_flag(badge: sel4::Badge, bit: usize) -> Option<sel4::Word> {
let mask = 1 << bit;
if badge & mask != 0 {
Some(badge & !mask)
} else {
None
}
}

#[doc(hidden)]
#[derive(Debug, Clone)]
pub enum Event {
Notified(NotifiedEvent),
Protected(Channel, MessageInfo),
Fault(ProtectionDomain, MessageInfo),
}

impl Event {
fn new(tag: sel4::MessageInfo, badge: sel4::Badge) -> Self {
if let Some(channel_index) = strip_flag(badge, CHANNEL_BADGE_BIT) {
Self::Protected(
Channel::new(channel_index.try_into().unwrap()),
MessageInfo::from_inner(tag),
)
} else if let Some(pd_index) = strip_flag(badge, PD_BADGE_BIT) {
Self::Fault(
ProtectionDomain::new(pd_index.try_into().unwrap()),
MessageInfo::from_inner(tag),
)
} else {
Self::Notified(NotifiedEvent(badge))
}
}

fn from_recv(recv: (sel4::MessageInfo, sel4::Badge)) -> Self {
Self::new(recv.0, recv.1)
}
}

#[doc(hidden)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NotifiedEvent(sel4::Badge);

impl NotifiedEvent {
pub fn iter(&self) -> NotifiedEventIter {
NotifiedEventIter(self.0)
}
}

#[doc(hidden)]
pub struct NotifiedEventIter(sel4::Badge);

impl Iterator for NotifiedEventIter {
type Item = Channel;

fn next(&mut self) -> Option<Self::Item> {
let badge_bits = self.0;
match badge_bits {
0 => None,
_ => {
let i = badge_bits.trailing_zeros();
self.0 = badge_bits & !(1 << i);
Some(Channel::new(i.try_into().unwrap()))
}
}
}
}

pub fn reply(msg_info: MessageInfo) {
REPLY_CAP.send(msg_info.into_inner())
}

pub fn recv() -> Event {
Event::from_recv(INPUT_CAP.recv(REPLY_CAP))
}

pub fn reply_recv(msg_info: MessageInfo) -> Event {
Event::from_recv(INPUT_CAP.reply_recv(msg_info.into_inner(), REPLY_CAP))
}

pub(crate) fn nb_send_recv(action: PreparedDeferredAction) -> Event {
Event::from_recv(action.cptr().nb_send_recv(
action.msg_info(),
INPUT_CAP.cast::<sel4::cap_type::Unspecified>(),
REPLY_CAP,
))
}

pub(crate) fn forfeit_sc() -> PreparedDeferredAction {
PreparedDeferredAction::new(
MONITOR_EP_CAP.cast(),
sel4::MessageInfoBuilder::default().length(1).build(),
)
}
9 changes: 8 additions & 1 deletion crates/sel4-microkit/base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@
#![feature(used_with_arg)]

mod channel;
mod defer;
mod handler;
mod message;
mod symbols;

pub use channel::{Channel, IrqAckError};
#[doc(hidden)]
pub mod ipc;

pub use channel::{Channel, IrqAckError, ProtectionDomain};
pub use defer::{DeferredAction, DeferredActionInterface, DeferredActionSlot};
pub use handler::{Handler, Infallible, NullHandler};
pub use message::{
get_mr, set_mr, with_msg_bytes, with_msg_bytes_mut, with_msg_regs, with_msg_regs_mut,
MessageInfo, MessageLabel, MessageRegisterValue,
Expand Down
9 changes: 9 additions & 0 deletions crates/sel4-microkit/base/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ impl MessageInfo {
Self { inner }
}

#[doc(hidden)]
pub fn inner(&self) -> &sel4::MessageInfo {
&self.inner
}

#[doc(hidden)]
pub fn into_inner(self) -> sel4::MessageInfo {
self.inner
Expand All @@ -38,6 +43,10 @@ impl MessageInfo {
pub fn count(&self) -> usize {
self.inner.length()
}

pub fn fault(&self) -> sel4::Fault {
sel4::with_ipc_buffer(|ipc_buffer| sel4::Fault::new(ipc_buffer, self.inner()))
}
}

impl Default for MessageInfo {
Expand Down
2 changes: 1 addition & 1 deletion crates/sel4-microkit/base/src/symbols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ macro_rules! maybe_extern_var {

/// Returns whether this projection domain is a passive server.
pub fn pd_is_passive() -> bool {
*maybe_extern_var!(passive: bool = false)
*maybe_extern_var!(microkit_passive: bool = false)
}

/// Returns the name of this projection domain without converting to unicode.
Expand Down
7 changes: 2 additions & 5 deletions crates/sel4-microkit/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ use sel4_microkit_base::ipc_buffer_ptr;
use sel4_panicking::catch_unwind;
use sel4_panicking_env::abort;

use crate::{
handler::{run_handler, Handler},
panicking::init_panicking,
};
use crate::{panicking::init_panicking, Handler};

#[cfg(target_thread_local)]
#[no_mangle]
Expand Down Expand Up @@ -67,7 +64,7 @@ macro_rules! declare_init {
#[doc(hidden)]
#[allow(clippy::missing_safety_doc)]
pub fn run_main<T: Handler>(init: impl FnOnce() -> T + UnwindSafe) -> ! {
let result = catch_unwind(|| match run_handler(init()) {
let result = catch_unwind(|| match init().run() {
Ok(absurdity) => match absurdity {},
Err(err) => err,
});
Expand Down
Loading
Loading