Skip to main content

sel4_microkit_base/
handler.rs

1//
2// Copyright 2023, Colias Group, LLC
3//
4// SPDX-License-Identifier: BSD-2-Clause
5//
6
7use core::fmt;
8
9#[cfg(feature = "alloc")]
10use alloc::boxed::Box;
11
12use crate::{
13    Channel, Child, MessageInfo,
14    defer::{DeferredAction, PreparedDeferredAction},
15    ipc::{self, ChannelSet, Event},
16    pd_is_passive, symbols,
17};
18
19pub use core::convert::Infallible;
20
21#[doc(hidden)]
22pub use sel4_never_polyfill::Never;
23
24/// Trait for the application-specific part of a protection domain's main loop.
25pub trait Handler {
26    /// Error type returned by this protection domain's entrypoints.
27    type Error: fmt::Display;
28
29    /// This method has the same meaning and type as its analog in `libmicrokit`.
30    ///
31    /// The default implementation just panics.
32    fn notified(&mut self, channels: ChannelSet) -> Result<(), Self::Error> {
33        panic!(
34            "unexpected notification from channels {}",
35            channels.display()
36        )
37    }
38
39    /// This method has the same meaning and type as its analog in `libmicrokit`.
40    ///
41    /// The default implementation just panics.
42    fn protected(
43        &mut self,
44        channel: Channel,
45        msg_info: MessageInfo,
46    ) -> Result<MessageInfo, Self::Error> {
47        panic!(
48            "unexpected protected procedure call from channel {channel:?} with msg_info={msg_info:?}"
49        )
50    }
51
52    /// This method has the same meaning and type as its analog in `libmicrokit`.
53    ///
54    /// The default implementation just panics.
55    fn fault(
56        &mut self,
57        child: Child,
58        msg_info: MessageInfo,
59    ) -> Result<Option<MessageInfo>, Self::Error> {
60        panic!("unexpected fault from protection domain {child:?} with msg_info={msg_info:?}")
61    }
62
63    /// An advanced feature for use by protection domains which seek to coalesce syscalls when
64    /// possible.
65    ///
66    /// This method is used by the main loop to fuse a queued `seL4_Send` call with the next
67    /// `seL4_Recv` using `seL4_NBSendRecv`. Its default implementation just returns `None`.
68    fn take_deferred_action(&mut self) -> Option<DeferredAction> {
69        None
70    }
71
72    #[doc(hidden)]
73    fn run(&mut self) -> Result<Never, Self::Error> {
74        let mut reply_tag: Option<MessageInfo> = None;
75
76        let mut prepared_deferred_action: Option<PreparedDeferredAction> = if pd_is_passive() {
77            Some(ipc::forfeit_sc())
78        } else {
79            None
80        };
81
82        // Work around https://github.com/seL4/seL4/issues/1536
83        {
84            let mut bits = symbols::pd_irqs();
85            while bits != 0 {
86                let i = bits.trailing_zeros();
87                Channel::new(i.try_into().unwrap()).irq_ack().unwrap();
88                bits &= bits - 1; // clear lowest bit
89            }
90        }
91
92        loop {
93            let event = match (reply_tag.take(), prepared_deferred_action.take()) {
94                (Some(msg_info), action_opt) => {
95                    if let Some(action) = action_opt {
96                        ipc::send(action);
97                    }
98                    ipc::reply_recv(msg_info)
99                }
100                (None, Some(action)) => ipc::nb_send_recv(action),
101                (None, None) => ipc::recv(),
102            };
103
104            match event {
105                Event::Notified(channels) => {
106                    self.notified(channels)?;
107                }
108                Event::Protected(channel, msg_info) => {
109                    reply_tag = Some(self.protected(channel, msg_info)?);
110                }
111                Event::Fault(child, msg_info) => {
112                    reply_tag = self.fault(child, msg_info)?;
113                }
114            };
115
116            prepared_deferred_action = self
117                .take_deferred_action()
118                .as_ref()
119                .map(DeferredAction::prepare);
120        }
121    }
122}
123
124impl Handler for Never {
125    type Error = Infallible;
126}
127
128/// A [`Handler`] implementation which does not override any of the default method implementations.
129pub struct NullHandler(());
130
131impl NullHandler {
132    #[allow(clippy::new_without_default)]
133    pub fn new() -> Self {
134        Self(())
135    }
136}
137
138impl Handler for NullHandler {
139    type Error = Infallible;
140}
141
142#[cfg(feature = "alloc")]
143impl<T: Handler + ?Sized> Handler for Box<T> {
144    type Error = T::Error;
145
146    fn notified(&mut self, channels: ChannelSet) -> Result<(), Self::Error> {
147        (**self).notified(channels)
148    }
149
150    fn protected(
151        &mut self,
152        channel: Channel,
153        msg_info: MessageInfo,
154    ) -> Result<MessageInfo, Self::Error> {
155        (**self).protected(channel, msg_info)
156    }
157
158    fn fault(
159        &mut self,
160        child: Child,
161        msg_info: MessageInfo,
162    ) -> Result<Option<MessageInfo>, Self::Error> {
163        (**self).fault(child, msg_info)
164    }
165
166    fn take_deferred_action(&mut self) -> Option<DeferredAction> {
167        (**self).take_deferred_action()
168    }
169
170    #[doc(hidden)]
171    fn run(&mut self) -> Result<Never, Self::Error> {
172        (**self).run()
173    }
174}