Skip to main content

abi_application/threads/runtime/
sync.rs

1use super::{Group, current, status};
2use crate::{
3    Condition, Mutex, Status, XILA_CLOCK_MONOTONIC, XILA_CLOCK_REALTIME, XILA_MUTEX_RECURSIVE,
4    XILA_MUTEX_TRY, suspend_dynamic, xila_time_monotonic, xila_time_realtime,
5};
6use core::{
7    ffi::c_void,
8    future::{Future, poll_fn},
9    pin::{Pin, pin},
10    ptr,
11    task::Poll,
12};
13use embassy_time::Timer;
14
15/// Intrusive FIFO wait queue. Nodes live in the suspended calls, so a wait
16/// allocates nothing. Only the process driver ever polls these coroutines. All
17/// of them stop on cancellation; no queue or waker in another task can refer
18/// to these nodes.
19struct Waiter {
20    next: *mut Waiter,
21    owner: usize,
22    notified: bool,
23}
24
25/// Register before suspending (and, for condvars, before unlocking). Each poll
26/// checks notification before the deadline. Neither holds a Rust reference
27/// into the caller's synchronization object across the suspension.
28unsafe fn wait(
29    queue: *mut *mut c_void,
30    owner: usize,
31    mut timer: Option<Timer>,
32    release: impl FnOnce(),
33) -> Result<(), Status> {
34    let mut waiter = Waiter {
35        next: ptr::null_mut(),
36        owner,
37        notified: false,
38    };
39    let node = ptr::from_mut(&mut waiter);
40    let mut tail = queue.cast::<*mut Waiter>();
41    unsafe {
42        while !(*tail).is_null() {
43            tail = &raw mut (**tail).next;
44        }
45        tail.write(node);
46    }
47    release();
48
49    let mut result = Ok(());
50    suspend_dynamic(pin!(poll_fn(|cx| {
51        if unsafe { (*node).notified } {
52            Poll::Ready(())
53        } else if timer
54            .as_mut()
55            .is_some_and(|timer| Pin::new(timer).poll(cx).is_ready())
56        {
57            result = Err(Status::TimedOut);
58            Poll::Ready(())
59        } else {
60            Poll::Pending
61        }
62    })));
63
64    // Notification removes the node from the queue. Only a timeout still
65    // owns a queued node and may access the condition variable.
66    if result.is_err() {
67        let mut link = queue.cast::<*mut Waiter>();
68        unsafe {
69            while *link != node {
70                link = &raw mut (**link).next;
71            }
72            link.write((*node).next);
73        }
74    }
75    result
76}
77
78fn pop_waiter(queue: &mut *mut c_void) -> Option<*mut Waiter> {
79    let waiter = queue.cast::<Waiter>();
80    if waiter.is_null() {
81        return None;
82    }
83    // Queued nodes belong to suspended calls in the current process.
84    *queue = unsafe { (*waiter).next.cast() };
85    Some(waiter)
86}
87
88/// Initialize an uninitialized or destroyed mutex.
89/// # Safety
90/// Mutex must be aligned, writable and unused.
91pub unsafe extern "C" fn xila_mutex_init(mutex: *mut Mutex, flags: u32) -> Status {
92    if mutex.is_null() || flags & !XILA_MUTEX_RECURSIVE != 0 {
93        return Status::InvalidArgument;
94    }
95    unsafe {
96        mutex.write(Mutex {
97            owner: 0,
98            depth: 0,
99            recursive: flags == XILA_MUTEX_RECURSIVE,
100            waiters: ptr::null_mut(),
101        })
102    };
103    Status::Ok
104}
105
106/// Destroy a mutex, returning ResourceBusy while owned or in use by a waiter.
107/// # Safety
108/// Mutex must be live and cannot be used again until reinitialized.
109pub unsafe extern "C" fn xila_mutex_destroy(mutex: *mut Mutex) -> Status {
110    match unsafe { mutex.as_ref() } {
111        Some(mutex) if mutex.owner == 0 && mutex.waiters.is_null() => Status::Ok,
112        Some(_) => Status::ResourceBusy,
113        None => Status::InvalidArgument,
114    }
115}
116
117unsafe fn lock(mutex: *mut Mutex, owner: usize, try_only: bool) -> Result<(), Status> {
118    let state = unsafe { mutex.as_mut() }.ok_or(Status::InvalidArgument)?;
119    match state.owner {
120        0 => {
121            state.owner = owner;
122            state.depth = 1;
123            Ok(())
124        }
125        id if id == owner && state.recursive => {
126            state.depth = state.depth.checked_add(1).ok_or(Status::Overflow)?;
127            Ok(())
128        }
129        _ if try_only => Err(Status::WouldBlock),
130        id if id == owner => Err(Status::Deadlock),
131        // Unlock gives this waiter ownership before waking it.
132        _ => unsafe { wait(&raw mut (*mutex).waiters, owner, None, || {}) },
133    }
134}
135
136fn unlock(group: &Group, mutex: &mut Mutex) {
137    mutex.depth -= 1;
138    if mutex.depth == 0 {
139        if let Some(waiter) = pop_waiter(&mut mutex.waiters) {
140            unsafe {
141                mutex.owner = (*waiter).owner;
142                mutex.depth = 1;
143                (*waiter).notified = true;
144            }
145            group.notify();
146        } else {
147            mutex.owner = 0;
148        }
149    }
150}
151
152/// Acquire a mutex, suspending on contention unless XILA_MUTEX_TRY is set.
153/// # Safety
154/// Mutex must remain live at the same address throughout the call.
155pub unsafe extern "C" fn xila_mutex_lock(mutex: *mut Mutex, flags: u32) -> Status {
156    status((|| {
157        let (_, local) = current()?;
158        if flags & !XILA_MUTEX_TRY != 0 {
159            return Err(Status::InvalidArgument);
160        }
161        unsafe { lock(mutex, local.id, flags == XILA_MUTEX_TRY) }
162    })())
163}
164
165/// Release one level of the caller's ownership.
166/// # Safety
167/// Mutex must be live.
168pub unsafe extern "C" fn xila_mutex_unlock(mutex: *mut Mutex) -> Status {
169    status((|| {
170        let (group, local) = current()?;
171        let mutex = unsafe { mutex.as_mut() }.ok_or(Status::InvalidArgument)?;
172        if mutex.owner != local.id {
173            return Err(Status::OperationNotPermitted);
174        }
175        unlock(group, mutex);
176        Ok(())
177    })())
178}
179
180/// Initialize an uninitialized or destroyed condition variable.
181/// # Safety
182/// Condition must be aligned, writable and unused.
183pub unsafe extern "C" fn xila_condition_init(condition: *mut Condition) -> Status {
184    if condition.is_null() {
185        return Status::InvalidArgument;
186    }
187    unsafe {
188        condition.write(Condition {
189            waiters: ptr::null_mut(),
190        })
191    };
192    Status::Ok
193}
194
195/// Destroy a condition variable, returning ResourceBusy if there are waiters.
196/// # Safety
197/// Condition must be live and cannot be used again until reinitialized.
198pub unsafe extern "C" fn xila_condition_destroy(condition: *mut Condition) -> Status {
199    match unsafe { condition.as_ref() } {
200        Some(condition) if condition.waiters.is_null() => Status::Ok,
201        Some(_) => Status::ResourceBusy,
202        None => Status::InvalidArgument,
203    }
204}
205
206fn deadline_timer(clock: u32, deadline: i64) -> Result<Timer, Status> {
207    let now = match clock {
208        XILA_CLOCK_MONOTONIC => {
209            let mut now = 0;
210            let status = unsafe { xila_time_monotonic(&mut now) };
211            if status != Status::Ok {
212                return Err(status);
213            }
214            i128::from(now)
215        }
216        XILA_CLOCK_REALTIME => {
217            let mut now = 0;
218            let status = unsafe { xila_time_realtime(&mut now) };
219            if status != Status::Ok {
220                return Err(status);
221            }
222            i128::from(now)
223        }
224        _ => return Err(Status::InvalidArgument),
225    };
226    let duration = (i128::from(deadline) - now).max(0) as u64;
227    Ok(Timer::at(task::deadline_after_nanoseconds(duration)))
228}
229
230/// Wait for notification or an absolute clock deadline, reacquiring the mutex
231/// before returning. The caller must own the mutex with depth exactly one.
232/// # Safety
233/// The mutex must remain live at a fixed address until the call returns.
234/// The condition must remain live at a fixed address until this waiter is
235/// notified or times out.
236/// A non-null deadline must be aligned and readable.
237pub unsafe extern "C" fn xila_condition_wait(
238    condition: *mut Condition,
239    mutex: *mut Mutex,
240    clock: u32,
241    deadline: *const i64,
242) -> Status {
243    status((|| {
244        let (group, local) = current()?;
245        if condition.is_null() || mutex.is_null() {
246            return Err(Status::InvalidArgument);
247        }
248        let state = unsafe { &*mutex };
249        if state.owner != local.id {
250            return Err(Status::OperationNotPermitted);
251        }
252        if state.depth != 1 {
253            return Err(Status::InvalidArgument);
254        }
255        let timer = unsafe { deadline.as_ref() }
256            .map(|deadline| deadline_timer(clock, *deadline))
257            .transpose()?;
258        // No suspension point between registration and unlock.
259        let waited = unsafe {
260            wait(&raw mut (*condition).waiters, local.id, timer, || {
261                unlock(group, &mut *mutex)
262            })
263        };
264        unsafe { lock(mutex, local.id, false)? };
265        waited
266    })())
267}
268
269/// Notify one waiter, or all waiters if all is true.
270/// # Safety
271/// Condition must be live.
272pub unsafe extern "C" fn xila_condition_notify(condition: *mut Condition, all: bool) -> Status {
273    status((|| {
274        let (group, _) = current()?;
275        let condition = unsafe { condition.as_mut() }.ok_or(Status::InvalidArgument)?;
276        while let Some(waiter) = pop_waiter(&mut condition.waiters) {
277            unsafe { (*waiter).notified = true };
278            group.notify();
279            if !all {
280                break;
281            }
282        }
283        Ok(())
284    })())
285}