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