1use crate::{File, Status};
2use alloc::vec::Vec;
3use core::{
4 ffi::c_void,
5 future::{Future, poll_fn},
6 pin::{Pin, pin},
7 slice,
8 task::{Context, Poll, Waker},
9};
10use embassy_time::{Instant, Timer};
11use file_system::{IoErrorKind, ReadinessWaiter, ReadyEvents};
12use virtual_file_system::FileReadiness;
13
14pub const XILA_POLL_IGNORE: u32 = 0;
15pub const XILA_POLL_FILE: u32 = 1;
16pub const XILA_POLL_DIRECTORY: u32 = 2;
17pub const XILA_POLL_TCP: u32 = 3;
18pub const XILA_POLL_TCP_LISTENER: u32 = 4;
19pub const XILA_POLL_UDP: u32 = 5;
20
21pub const XILA_POLL_IN: u16 = 1;
22pub const XILA_POLL_OUT: u16 = 2;
23pub const XILA_POLL_ERR: u16 = 4;
24pub const XILA_POLL_HUP: u16 = 8;
25pub const XILA_POLL_NVAL: u16 = 16;
26
27#[repr(C)]
31pub struct PollEntry {
32 pub handle: *const c_void,
34 pub kind: u32,
35 pub events: u16,
36 pub revents: u16,
37}
38
39enum Source<'a> {
40 Ignore,
41 Invalid,
42 File(FileReadiness),
43 Directory,
44 #[cfg(feature = "network")]
45 Tcp(&'a ::network::TcpSocket, Option<&'a crate::TcpListener>),
46 #[cfg(feature = "network")]
47 Udp(&'a crate::Udp),
48 #[cfg(not(feature = "network"))]
50 Disabled(core::marker::PhantomData<&'a ()>),
51}
52
53impl<'a> Source<'a> {
54 unsafe fn from_entry(entry: &PollEntry) -> Self {
56 if entry.kind == XILA_POLL_IGNORE {
57 return Self::Ignore;
58 }
59 if entry.handle.is_null() {
60 return Self::Invalid;
61 }
62 match entry.kind {
63 XILA_POLL_FILE => {
64 Self::File(unsafe { &(*entry.handle.cast::<File>()).readiness }.clone())
65 }
66 XILA_POLL_DIRECTORY => Self::Directory,
67 #[cfg(feature = "network")]
68 XILA_POLL_TCP => {
69 Self::Tcp(unsafe { &(*entry.handle.cast::<crate::Tcp>()).inner }, None)
70 }
71 #[cfg(feature = "network")]
72 XILA_POLL_TCP_LISTENER => {
73 let listener = unsafe { &*entry.handle.cast::<crate::TcpListener>() };
74 Self::Tcp(&listener.inner, Some(listener))
75 }
76 #[cfg(feature = "network")]
77 XILA_POLL_UDP => Self::Udp(unsafe { &*entry.handle.cast() }),
78 #[cfg(not(feature = "network"))]
79 XILA_POLL_TCP | XILA_POLL_TCP_LISTENER | XILA_POLL_UDP => {
80 Self::Disabled(core::marker::PhantomData)
81 }
82 _ => Self::Invalid,
83 }
84 }
85
86 fn events(&self, _cx: &mut Context<'_>, wanted: u16) -> (u16, bool) {
88 let interests = ReadyEvents::from_bits_truncate(wanted & (XILA_POLL_IN | XILA_POLL_OUT));
89 let result = match self {
90 Self::Ignore => return (0, true),
91 Self::Invalid => return (XILA_POLL_NVAL, true),
92 Self::Directory => return (wanted & XILA_POLL_IN, true),
93 Self::File(file) => file.events(interests),
94 #[cfg(not(feature = "network"))]
95 Self::Disabled(_) => return (XILA_POLL_NVAL, true),
96 #[cfg(feature = "network")]
97 Self::Tcp(socket, listener) => {
98 return (
99 crate::network::tcp_readiness(socket, _cx, *listener, wanted),
100 true,
101 );
102 }
103 #[cfg(feature = "network")]
104 Self::Udp(socket) => return (crate::network::udp_readiness(socket, _cx, wanted), true),
105 };
106 match result {
107 Ok((events, precise)) => (
108 events.bits() & (wanted | XILA_POLL_ERR | XILA_POLL_HUP),
109 precise,
110 ),
111 Err(IoErrorKind::BadDescriptor) => (XILA_POLL_NVAL, true),
112 Err(_) => (XILA_POLL_ERR, true),
113 }
114 }
115}
116
117#[derive(Default)]
118struct Ready {
119 count: usize,
120 precise: bool,
121}
122
123impl Ready {
124 fn record(&mut self, events: u16, precise: bool) {
125 if events != 0 {
126 self.count += 1;
127 self.precise |= precise;
128 }
129 }
130}
131
132pub unsafe extern "C" fn xila_poll_wait(
142 entries: *mut PollEntry,
143 count: usize,
144 timeout_ms: i32,
145 ready_count: *mut usize,
146) -> Status {
147 if ready_count.is_null()
148 || (count != 0 && entries.is_null())
149 || count > isize::MAX as usize / size_of::<PollEntry>()
150 {
151 return Status::InvalidArgument;
152 }
153 let entries = if count == 0 {
154 &mut []
155 } else {
156 unsafe { slice::from_raw_parts_mut(entries, count) }
157 };
158
159 let in_coroutine = crate::is_in_coroutine();
161 let ready = if timeout_ms == 0 {
162 let mut ready = Ready::default();
163 let mut cx = Context::from_waker(Waker::noop());
164 for entry in entries {
165 let (events, precise) =
166 unsafe { Source::from_entry(entry) }.events(&mut cx, entry.events);
167 entry.revents = events;
168 ready.record(events, precise);
169 }
170 ready
171 } else {
172 let mut sources = Vec::new();
173 if sources.try_reserve_exact(count).is_err() {
174 return Status::OutOfMemory;
175 }
176 for entry in entries.iter() {
177 sources.push((unsafe { Source::from_entry(entry) }, 0));
178 }
179 let deadline = (timeout_ms > 0)
180 .then(|| task::deadline_after_nanoseconds(timeout_ms as u64 * 1_000_000));
181
182 let result = if in_coroutine {
183 crate::suspend_on_cancellable(wait(entries, sources, deadline))
184 } else {
185 let ready = scan(
186 entries,
187 &mut sources,
188 &mut Context::from_waker(Waker::noop()),
189 );
190 if ready.count == 0 {
191 Err(Status::WouldBlock)
192 } else {
193 publish(entries, &sources);
194 Ok(ready)
195 }
196 };
197 match result {
198 Ok(ready) => ready,
199 Err(error) => return error,
200 }
201 };
202 if in_coroutine && ready.count != 0 && !ready.precise {
203 crate::yield_once();
206 }
207 unsafe { ready_count.write(ready.count) };
208 Status::Ok
209}
210
211fn scan(entries: &[PollEntry], sources: &mut [(Source<'_>, u16)], cx: &mut Context<'_>) -> Ready {
212 let mut ready = Ready::default();
213 for (entry, (source, events)) in entries.iter().zip(sources.iter_mut()) {
214 let (reported, precise) = source.events(cx, entry.events);
215 *events = reported;
216 ready.record(reported, precise);
217 }
218 ready
219}
220
221fn publish(entries: &mut [PollEntry], sources: &[(Source<'_>, u16)]) {
222 for (entry, (_, events)) in entries.iter_mut().zip(sources) {
223 entry.revents = *events;
224 }
225}
226
227async fn wait(
228 entries: &mut [PollEntry],
229 mut sources: Vec<(Source<'_>, u16)>,
230 deadline: Option<Instant>,
231) -> Result<Ready, Status> {
232 let waiter = pin!(ReadinessWaiter::default());
233 let mut timer = deadline.map(Timer::at);
234 poll_fn(|cx| {
235 if !sources.is_empty() {
236 waiter.as_ref().register(cx.waker())?;
237 }
238 let ready = scan(entries, &mut sources, cx);
239 if ready.count != 0
240 || timer
241 .as_mut()
242 .is_some_and(|timer| Pin::new(timer).poll(cx).is_ready())
243 {
244 publish(entries, &sources);
245 Poll::Ready(Ok(ready))
246 } else {
247 Poll::Pending
248 }
249 })
250 .await
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use core::ptr::null_mut;
257
258 #[test]
259 fn poll_distinguishes_invalid_and_ignored_entries() {
260 let mut entries = [
261 PollEntry {
262 handle: null_mut(),
263 kind: XILA_POLL_FILE,
264 events: 0,
265 revents: 0,
266 },
267 PollEntry {
268 handle: null_mut(),
269 kind: XILA_POLL_IGNORE,
270 events: XILA_POLL_IN,
271 revents: u16::MAX,
272 },
273 ];
274 let mut ready = 17;
275 assert_eq!(
276 unsafe { xila_poll_wait(entries.as_mut_ptr(), entries.len(), 0, &mut ready) },
277 Status::Ok,
278 );
279 assert_eq!(ready, 1);
280 assert_eq!(entries[0].revents, XILA_POLL_NVAL);
281 assert_eq!(entries[1].revents, 0);
282 }
283
284 #[test]
285 fn synchronous_wait_has_no_side_effects_when_it_would_block() {
286 let mut entry = PollEntry {
287 handle: null_mut(),
288 kind: XILA_POLL_IGNORE,
289 events: 0,
290 revents: u16::MAX,
291 };
292 let mut ready = 17;
293 assert_eq!(
294 unsafe { xila_poll_wait(&mut entry, 1, -1, &mut ready) },
295 Status::WouldBlock
296 );
297 assert_eq!(ready, 17);
298 assert_eq!(entry.revents, u16::MAX);
299 assert_eq!(
300 unsafe { xila_poll_wait(null_mut(), 1, 0, &mut ready) },
301 Status::InvalidArgument
302 );
303 assert_eq!(ready, 17);
304 }
305}