1use std::{cell::Cell, marker, mem, num, ptr, time};
2
3use dope_sys::{engine, kernel, memory::Context as _};
4#[cfg(target_os = "macos")]
5use o3::buffer;
6use o3::{
7 base::{cell::region, marker::ThreadBound},
8 buffer::storage::provided,
9};
10use route::table;
11
12use crate::{
13 Backend, Engine,
14 driver::{
15 life::{domain::runtime::Runtime, native, native::host::Host},
16 retained::flight,
17 route::queues,
18 schedule::{
19 clock,
20 clock::{timer, timer::heap},
21 ready,
22 ready::{task::owner, wake::resident::slot},
23 sequence,
24 },
25 },
26 io::fd::access::Access,
27 random,
28};
29
30pub mod life;
31pub use life::Local;
32pub mod receive;
33pub mod result;
34pub mod retained;
35pub mod route;
36pub mod schedule;
37pub mod settings;
38pub mod storage;
39
40use result::{IoOperation, Opcode, SubmitError};
41
42#[cfg(target_os = "linux")]
43type ReceiveArena = provided::native::Arena<Shared>;
44#[cfg(target_os = "macos")]
45type ReceiveArena = provided::Arena<crate::Buffer, Shared, ()>;
46#[cfg(target_os = "linux")]
47type ReceiveRoot<'d> = provided::native::Root<'d, Shared>;
48#[cfg(target_os = "macos")]
49type ReceiveRoot<'d> = provided::Root<'d, crate::Buffer, Shared, ()>;
50
51#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
53#[repr(transparent)]
54pub(crate) struct Invariant<'d>(marker::PhantomData<(fn(&'d ()) -> &'d (), ThreadBound)>);
55
56#[must_use = "application binding must be consumed during startup"]
57pub struct Binding<'d> {
58 timer: timer::Timer<'d>,
59 owners: owner::Capacity,
60}
61
62impl<'d> Binding<'d> {
63 #[doc(hidden)]
64 pub const fn new(timer: timer::Timer<'d>, owners: owner::Capacity) -> Self {
65 Self { timer, owners }
66 }
67
68 pub const fn timer(&self) -> timer::Timer<'d> {
69 self.timer
70 }
71
72 pub const fn owners(&self) -> owner::Capacity {
73 self.owners
74 }
75
76 pub fn sequence(&self) -> sequence::Block<'d> {
77 sequence::Block::new(self.timer.driver)
78 }
79}
80
81#[repr(transparent)]
82pub struct Driver {
83 runtime: Runtime,
84}
85
86#[derive(Clone, Copy)]
87#[repr(transparent)]
88pub struct Reference<'d> {
89 shared: ReceiveRoot<'d>,
90 pub(crate) brand: Invariant<'d>,
91}
92
93impl<'d> Reference<'d> {
94 pub fn outbound_cap(self) -> table::Capacity {
95 let arena = self.ready().arena();
96 arena.descriptors().outbound_cap()
97 }
98
99 pub fn accept_cap(self) -> table::Capacity {
100 let arena = self.ready().arena();
101 arena.descriptors().accept_cap()
102 }
103
104 fn new(shared: ReceiveRoot<'d>) -> Self {
105 Self {
106 shared,
107 brand: Invariant(marker::PhantomData),
108 }
109 }
110
111 pub const fn ready(self) -> ready::Context<'d> {
112 ready::Context::new(self)
113 }
114
115 pub const fn targets<Tag: route::Tag>(self) -> route::Space<'d, Tag> {
116 route::Space {
117 driver: route::Brand::new(self.brand),
118 }
119 }
120
121 pub const fn scheduler(self) -> schedule::Context<'d> {
122 schedule::Context::new(self)
123 }
124
125 pub fn try_next_id(self) -> Result<sequence::Id<'d>, sequence::Exhausted> {
127 let raw = self
128 .shared
129 .context()
130 .sequence
131 .next()
132 .ok_or(sequence::Exhausted)?;
133 Ok(sequence::Id::new(self, raw))
134 }
135
136 pub fn clock(self) -> clock::Clock<'d, 'd> {
137 self.scheduler().clock()
138 }
139
140 pub const fn timer(self) -> timer::Timer<'d> {
141 timer::Timer::new(self)
142 }
143
144 pub(crate) fn owners(self) -> ReceiveRoot<'d> {
145 self.shared
146 }
147
148 pub(crate) fn exhausted(self) -> &'d crate::Permits {
149 &self.shared.context().receive
150 }
151
152 pub(crate) fn layout(self) -> settings::Receive {
153 self.owners().context().buffer().layout().0
154 }
155
156 pub fn has_deferred(self) -> bool {
157 self.owners().has_returned()
158 || self.descriptors().retirement().has_pending()
159 || self.shared.context().retire.has_pending()
160 }
161
162 pub(crate) const fn descriptors(self) -> Access<'d> {
163 Access::new(self)
164 }
165
166 #[doc(hidden)]
167 pub fn is_same(self, other: Reference<'_>) -> bool {
168 ptr::from_ref(self.shared.context()).addr() == ptr::from_ref(other.shared.context()).addr()
169 }
170
171 #[doc(hidden)]
172 pub fn random_seed(self) -> &'d random::Seed {
173 self.shared.context().random_seed()
174 }
175}
176
177const _: () = {
178 assert!(mem::size_of::<IoOperation>() == 1);
179 assert!(mem::align_of::<IoOperation>() == 1);
180 assert!(mem::size_of::<Opcode>() == mem::size_of::<<crate::Backend as kernel::Source>::Code>());
181 assert!(
182 mem::align_of::<Opcode>() == mem::align_of::<<crate::Backend as kernel::Source>::Code>()
183 );
184 assert!(mem::size_of::<Driver>() == mem::size_of::<Runtime>());
185 assert!(mem::align_of::<Driver>() == mem::align_of::<Runtime>());
186 assert!(mem::size_of::<Reference<'_>>() == mem::size_of::<usize>());
187 assert!(mem::align_of::<Reference<'_>>() == mem::align_of::<usize>());
188 assert!(mem::size_of::<Invariant<'_>>() == 0);
189 assert!(mem::align_of::<Invariant<'_>>() == 1);
190 assert!(mem::size_of::<SubmitError>() == 1 && mem::align_of::<SubmitError>() == 1);
191 assert!(
192 mem::size_of::<Result<flight::Flight<'static>, SubmitError>>()
193 == mem::size_of::<(flight::Flight<'static>, SubmitError)>()
194 );
195 assert!(
196 mem::align_of::<Result<flight::Flight<'static>, SubmitError>>()
197 == mem::align_of::<flight::Flight<'static>>()
198 );
199};
200
201impl<'d> Local<'d> {
202 pub fn storage(&mut self) -> storage::Context<'_, 'd> {
203 storage::Context::new(self)
204 }
205
206 pub(crate) fn native(&mut self) -> native::Access<'_, 'd> {
207 native::Access::new(self)
208 }
209
210 pub fn region_token(&mut self) -> &mut region::Token<region::Identity<'d>> {
211 &mut self.region.0
212 }
213
214 pub fn state_token(&mut self) -> &mut region::Token<region::Identity<'d, 1>> {
215 &mut self.region.1
216 }
217
218 pub fn regions_mut(
219 &mut self,
220 ) -> &mut (
221 region::Token<region::Identity<'d>>,
222 region::Token<region::Identity<'d, 1>>,
223 ) {
224 &mut self.region
225 }
226
227 pub fn regions(
228 &self,
229 ) -> &(
230 region::Token<region::Identity<'d>>,
231 region::Token<region::Identity<'d, 1>>,
232 ) {
233 &self.region
234 }
235
236 pub fn receive(&self) -> settings::Receive {
237 self.driver.layout()
238 }
239
240 pub fn driver_ref(&self) -> Reference<'d> {
241 self.driver
242 }
243}
244
245pub(crate) struct Shared {
246 random_seed: random::Seed,
247 pub(in crate::driver) schedule: schedule::State,
248 pub(in crate::driver) receive: crate::Permits,
249 buffer: <Engine as engine::Buffer>::Context,
250 pub(in crate::driver) retire: queues::Pending,
251 pub(in crate::driver) generations: [Cell<Option<route::Epoch>>; route::CAPACITY],
252 pub(in crate::driver) sequence: sequence::Owner,
253 timer: heap::raw::Store<time::Instant, slot::Slot, timer::Tag>,
254}
255
256impl Shared {
257 pub(in crate::driver) fn try_new<'f>(
258 seed: random::Seed,
259 plan: settings::Plan<'_>,
260 failure: &'f mut Option<result::CreateError>,
261 ) -> Result<(ReceiveArena, Engine), &'f mut result::CreateError> {
262 let config = plan.config();
263 #[cfg(target_os = "linux")]
264 let initialize = match ReceiveArena::try_allocate(config.receive().count()) {
265 Ok(initialize) => initialize,
266 Err(error) => return Err(failure.insert(error.into())),
267 };
268 #[cfg(target_os = "macos")]
269 let initialize = match provided::Arena::<crate::Buffer, Self, ()>::try_allocate(
270 config.receive().count().into(),
271 ) {
272 Ok(initialize) => initialize,
273 Err(error) => return Err(failure.insert(error.into())),
274 };
275 let schedule = match schedule::State::try_new(plan) {
276 Ok(schedule) => schedule,
277 Err(error) => return Err(failure.insert(error.into())),
278 };
279 let timer = match heap::raw::Store::try_new(config.schedule().timers().count().get()) {
280 Ok(timer) => timer,
281 Err(error) => return Err(failure.insert(error.into())),
282 };
283 let (backend, buffer, receive) =
287 match unsafe { <Backend as engine::raw::Create<Host<Backend>, _>>::try_new(config) } {
288 Ok(created) => created,
289 Err(error) => return Err(failure.insert(error.into())),
290 };
291 let shared = Self {
292 random_seed: seed,
293 schedule,
294 receive,
295 buffer,
296 retire: queues::Pending::new(),
297 generations: [const { Cell::new(Some(route::Epoch::INITIAL)) }; route::CAPACITY],
298 sequence: sequence::Owner::new(),
299 timer,
300 };
301 #[cfg(target_os = "linux")]
302 let shared = initialize.initialize(shared);
303 #[cfg(target_os = "macos")]
304 let shared = initialize(shared);
305 Ok((shared, backend))
306 }
307
308 pub(in crate::driver) const fn random_seed(&self) -> &random::Seed {
309 &self.random_seed
310 }
311
312 pub(crate) fn buffer(&self) -> &<Engine as engine::Buffer>::Context {
313 &self.buffer
314 }
315
316 pub(crate) fn into_buffer(self) -> <Engine as engine::Buffer>::Context {
317 self.buffer
318 }
319
320 pub(in crate::driver) fn timer(
321 &self,
322 ) -> &heap::raw::Store<time::Instant, slot::Slot, timer::Tag> {
323 &self.timer
324 }
325}
326
327#[cfg(target_os = "macos")]
328impl buffer::raw::Fixed<crate::Buffer> for Shared {
329 fn resident(&self) -> num::NonZero<u32> {
330 buffer::raw::Fixed::resident(&self.buffer)
331 }
332
333 unsafe fn project<'a, 'id>(
334 &'a self,
335 item: &'a mut crate::Buffer,
336 limit: buffer::raw::Limit<'id>,
337 ) -> buffer::raw::Projection<'a, 'id> {
338 unsafe { buffer::raw::Fixed::project(&self.buffer, item, limit) }
341 }
342}
343
344#[cfg(target_os = "linux")]
347unsafe impl provided::native::Context for Shared {
348 fn resident(&self) -> num::NonZero<u32> {
349 self.buffer.layout().0.buffer_len().into_nonzero()
350 }
351
352 unsafe fn project(&self, bid: u16, len: usize) -> &mut [u8] {
353 unsafe { self.buffer.project(bid, len) }
355 }
356}