Skip to main content

rusty_rtos_kernel_core/
queue.rs

1//! `queue.c`: the queue, and the semaphore and mutex built on it.
2//!
3//! In FreeRTOS a semaphore *is* a queue with a zero-size item, and a mutex
4//! is that plus a holder and priority inheritance. Kairos keeps the same
5//! shape, because the trace does: a semaphore give fires `QUEUE_SEND` and a
6//! mutex take fires `QUEUE_RECEIVE`, and a conformance diff would notice
7//! any tidier arrangement.
8//!
9//! # A blocking call with no stack to block on
10//!
11//! `xQueueReceive( q, &v, 100 )` blocks: the C task stops inside the call,
12//! and when it is woken it loops back to the top, re-checks the queue, and
13//! either returns the item or blocks again. This kernel has no stack to
14//! suspend, so the loop is turned inside out — a blocking call returns
15//! [`Blocked`] and the caller invokes it again, unchanged, when it next
16//! runs:
17//!
18//! ```ignore
19//! // in a task body, at some `pc`:
20//! match k.queue_receive(q, 100)? {
21//!     Blocked => {}                 // stay at this pc; the kernel parked us
22//!     Ready(value) => { ...; self.pc = next; }
23//! }
24//! ```
25//!
26//! The task is off the ready list when `Blocked` comes back, so the runner
27//! will not step it again until the kernel wakes it — which is exactly when
28//! the C thread would have resumed. What the C keeps on its stack across
29//! the block (the timeout, the remaining ticks, whether inheritance
30//! happened) this kernel keeps in the TCB, in [`Wait`], because that *is*
31//! the stack frame.
32
33use rusty_rtos_core::config::Config;
34use rusty_rtos_core::error::{Error, Result};
35use rusty_rtos_core::handle::{QueueHandle, TaskHandle};
36use rusty_rtos_core::hooks::TickHook;
37use rusty_rtos_core::isr::Woken;
38use rusty_rtos_core::port::Port;
39use rusty_rtos_core::trace::{Event, Trace};
40
41use crate::kernel::{Kernel, OwedTrace, QueueResume};
42
43/// What a blocking call answers.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Wait<T> {
46    /// The kernel parked the calling task. Leave the program counter where
47    /// it is and make the same call again when the task next runs.
48    Blocked,
49    /// The call completed.
50    Ready(T),
51}
52
53pub use Wait::{Blocked, Ready};
54
55/// Where an item goes (`xCopyPosition`).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Position {
58    /// `queueSEND_TO_BACK`.
59    Back,
60    /// `queueSEND_TO_FRONT`.
61    Front,
62    /// `queueOVERWRITE`: write to the front of a length-one queue whether
63    /// or not it already holds something, and leave the message count
64    /// where it was rather than raising it.
65    Overwrite,
66}
67
68/// What a queue is underneath (`ucQueueType`).
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70pub enum Kind {
71    // ORDER IS LOAD-BEARING, and only for the two predicates below. The kinds
72    // that carry data are first and the two mutex kinds are last, so
73    // `carries_data` and `is_mutex` are each a range the compiler can test
74    // with one comparison instead of two. Nothing reads a discriminant, so
75    // the order carries no other meaning.
76    /// A queue of values. `#[default]` so a free arena slot holds something
77    /// real without unsafe; the ORDER above is untouched, and nothing reads
78    /// a free slot.
79    #[default]
80    Queue,
81    /// A queue set: a queue whose items are the handles of the queues in
82    /// it. `xQueueSelectFromSet` is a receive from this one.
83    Set,
84    /// A binary or counting semaphore: a queue with a zero-size item, so
85    /// only the count matters.
86    Semaphore,
87    /// A mutex: a one-deep semaphore with a holder and priority
88    /// inheritance.
89    Mutex,
90    /// A recursive mutex: as above, and the holder may take it again.
91    RecursiveMutex,
92}
93
94impl Kind {
95    /// `uxItemSize == 0`: semaphores and mutexes carry a count, not data.
96    pub(crate) const fn carries_data(self) -> bool {
97        matches!(self, Self::Queue | Self::Set)
98    }
99
100    /// The two mutex kinds, which inherit priority.
101    pub(crate) const fn is_mutex(self) -> bool {
102        matches!(self, Self::Mutex | Self::RecursiveMutex)
103    }
104}
105
106/// One queue: the C `Queue_t` minus the byte pointers. Storage is a range
107/// of the kernel's shared slot pool, and the read and write cursors follow
108/// C's `pcReadFrom` / `pcWriteTo` exactly — `pcReadFrom` points at the item
109/// last read, which is what makes `queueSEND_TO_FRONT` a single step back.
110#[derive(Debug, Clone, Copy, Default)]
111pub(crate) struct Queue {
112    pub(crate) base: usize,
113    /// `uxLength`.
114    pub(crate) length: usize,
115    /// `uxMessagesWaiting`.
116    pub(crate) waiting: usize,
117    /// `pcReadFrom`, as an index: the item last read.
118    pub(crate) read_from: usize,
119    /// `pcWriteTo`, as an index: where the next back-send writes.
120    pub(crate) write_to: usize,
121    pub(crate) kind: Kind,
122    /// `u.xSemaphore.xMutexHolder`.
123    pub(crate) holder: TaskHandle,
124    /// `u.xSemaphore.uxRecursiveCallCount`.
125    pub(crate) recursions: u32,
126    /// `cTxLock`: [`UNLOCKED`] when no task holds the queue locked;
127    /// otherwise how many sends an interrupt made while it was locked, and
128    /// therefore how many receivers `prvUnlockQueue` still owes a wake-up.
129    pub(crate) tx_lock: i8,
130    /// `cRxLock`, the same for receives and the tasks waiting to send.
131    pub(crate) rx_lock: i8,
132    /// `pxQueueSetContainer`: the set this queue belongs to, if any. An
133    /// item arriving here is announced there.
134    pub(crate) set_container: QueueHandle,
135}
136
137/// `queueUNLOCKED`.
138pub(crate) const UNLOCKED: i8 = -1;
139/// `queueLOCKED_UNMODIFIED`.
140pub(crate) const LOCKED_UNMODIFIED: i8 = 0;
141
142impl Queue {
143    // A3: ONE caller, so the out-of-line body pays a prologue and epilogue for
144    // a single call. Inlining moves the body rather than duplicating it.
145    #[inline]
146    pub(crate) const fn new(base: usize, length: usize, kind: Kind) -> Self {
147        Self {
148            base,
149            length,
150            waiting: 0,
151            // `xQueueGenericReset`: pcReadFrom = pcHead + (length - 1) * itemSize.
152            read_from: length.saturating_sub(1),
153            write_to: 0,
154            kind,
155            holder: TaskHandle::NULL,
156            recursions: 0,
157            tx_lock: UNLOCKED,
158            rx_lock: UNLOCKED,
159            set_container: QueueHandle::NULL,
160        }
161    }
162}
163
164impl<
165    C: Config,
166    P: Port,
167    T: Trace,
168    H,
169    const TASKS: usize,
170    const ITEMS: usize,
171    const LISTS: usize,
172    const QUEUES: usize,
173    const SLOTS: usize,
174    const BUFFERS: usize,
175    const BYTES: usize,
176    const TIMERS: usize,
177    const GROUPS: usize,
178    const TIMER_CMDS: usize,
179> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
180where
181    H: TickHook<Self>,
182{
183    // ------------------------------------------------------------ create --
184
185    /// `xQueueCreate`.
186    ///
187    /// # Errors
188    /// [`Error::Full`] when the queue arena or the shared slot pool is
189    /// exhausted; [`Error::InvalidArgument`] for a zero length.
190    pub fn queue_create(&mut self, length: usize) -> Result<QueueHandle> {
191        self.new_queue(length, Kind::Queue)
192    }
193
194    /// `vQueueDelete`, and `vSemaphoreDelete`, which the C defines as the
195    /// same function.
196    ///
197    /// # It traces nothing and still costs time
198    ///
199    /// `vQueueDelete` takes no critical section of its own — but it ends in
200    /// `vPortFree( pxQueue )`, and every `heap_N.c` wraps free in
201    /// `vTaskSuspendAll` / `xTaskResumeAll` exactly as it wraps malloc. So
202    /// a delete costs **one outermost critical-section exit**, which under
203    /// the sim contract is one unit of time, while emitting no trace line
204    /// at all (this harness defines no `traceQUEUE_DELETE`).
205    ///
206    /// `AbortDelay`'s remake left the deletes out on the reasoning that an
207    /// event-less call cannot move the trace. Every event still agreed and
208    /// the exit column was one short from the first delete onwards. The
209    /// sibling `event_group_delete` already carried this note; the queue
210    /// had no delete at all.
211    ///
212    /// # Errors
213    /// [`Error::Gone`] for a stale handle.
214    pub fn queue_delete(&mut self, queue: QueueHandle) -> Result<()> {
215        let q = *self.queues.resolve(queue)?;
216        // Give the item storage back when it is the last thing allocated.
217        //
218        // `new_queue` bump-allocates from `slots_used` and, until
219        // 2026-09-21, nothing ever lowered it: the DESCRIPTOR came back and
220        // the storage did not, so a create/delete loop exhausted `SLOTS`
221        // permanently. `AbortDelay` hits it after ~108 passes, which is how
222        // it was found, and any application with a queue per connection or
223        // per job hits it too.
224        //
225        // This is the same move `give_bytes` already makes for the byte
226        // arena — that allocator exists because "a bump allocator would run
227        // out in a few hundred ticks", and the identical argument applies
228        // here and was simply never made.
229        //
230        // Deliberately the END-OF-ARENA case only, and not a free list.
231        // The pattern that needs this is create-then-delete of the same
232        // object, where the deleted extent IS the last one, and it is what
233        // the corpus exercises. An out-of-order delete still strands its
234        // slots; that wants the full `free_blocks` treatment and is a
235        // larger change with more to prove.
236        if q.kind.carries_data() {
237            self.give_slots(q.base, q.length);
238        }
239        let _ = self.queues.discard(queue);
240        // `vPortFree( pxQueue )`.
241        self.account_for_allocation();
242        Ok(())
243    }
244
245    /// `xSemaphoreCreateBinary`: a one-deep semaphore, created empty.
246    ///
247    /// # Errors
248    /// As [`Kernel::queue_create`].
249    pub fn semaphore_create_binary(&mut self) -> Result<QueueHandle> {
250        self.new_queue(1, Kind::Semaphore)
251    }
252
253    /// `xSemaphoreCreateCounting`.
254    ///
255    /// # Errors
256    /// As [`Kernel::queue_create`]; [`Error::InvalidArgument`] if the
257    /// initial count exceeds the maximum.
258    pub fn semaphore_create_counting(&mut self, max: usize, initial: usize) -> Result<QueueHandle> {
259        if initial > max {
260            return Err(Error::InvalidArgument);
261        }
262        let handle = self.new_queue(max, Kind::Semaphore)?;
263        if let Ok(q) = self.queues.resolve_mut(handle) {
264            q.waiting = initial;
265        }
266        Ok(handle)
267    }
268
269    /// `xSemaphoreCreateMutex`: created **available**, unlike a semaphore.
270    ///
271    /// # Errors
272    /// As [`Kernel::queue_create`].
273    pub fn mutex_create(&mut self) -> Result<QueueHandle> {
274        self.new_mutex(Kind::Mutex)
275    }
276
277    /// `xSemaphoreCreateRecursiveMutex`.
278    ///
279    /// # Errors
280    /// As [`Kernel::queue_create`].
281    pub fn mutex_create_recursive(&mut self) -> Result<QueueHandle> {
282        self.new_mutex(Kind::RecursiveMutex)
283    }
284
285    /// `prvInitialiseMutex`: give the mutex once so it starts available.
286    ///
287    /// This goes through the general send for the same reason the C does — and
288    /// the byte count is the argument. Until 2026-09-25 a private `prime_mutex`
289    /// carried a hand-written copy of the send, specialised on the four
290    /// constants supplied below, because inlining the general body here cost
291    /// **534 bytes**. That defence was aimed at the wrong thing: the choice is
292    /// not "specialise or inline", it is *which symbol to call*, and
293    /// [`Self::send_generic_outlined`] — the A4 handle that already existed for
294    /// the cold callers — costs a five-argument frame, not a body.
295    ///
296    /// Calling it instead and deleting the specialisation measured
297    /// **−316 bytes** of flash (19,302 → 18,986), `mv` − 8, `slli` − 5,
298    /// `andi` − 2 and 99 fewer rv32 instructions — every pin down, none up.
299    /// `conform --all` stays at 26/26, which is what proves the trace is
300    /// unchanged: one critical section, `QueueSend` at the same point, the same
301    /// `exits`. A mutex therefore still shows a `QUEUE_SEND` line immediately
302    /// after its `QUEUE_CREATE`, before any task exists.
303    ///
304    /// The law: a specialisation written to escape an unwanted INLINE is only
305    /// worth its bytes if no out-of-line handle on the general body exists.
306    /// Check for the handle first.
307    fn new_mutex(&mut self, kind: Kind) -> Result<QueueHandle> {
308        let handle = self.new_queue(1, kind)?;
309        let _ = self.send_generic_outlined(handle, 0, 0, Position::Back)?;
310        Ok(handle)
311    }
312
313    /// Take `length` slots: first fit from what deleted queues gave back,
314    /// and only then from the untouched end.
315    ///
316    /// First fit rather than best fit for the same reason `take_bytes` uses
317    /// it — the pattern that needs an allocator at all is create-then-delete
318    /// of the *same size*, which first fit serves exactly and without
319    /// fragmenting.
320    fn take_slots(&mut self, length: usize) -> Option<usize> {
321        if length == 0 {
322            return Some(self.slots_used);
323        }
324        for i in 0..self.free_slot_count {
325            let (base, free) = *self.free_slots.get(i)?;
326            if free < length {
327                continue;
328            }
329            if free == length {
330                self.drop_free_slot(i);
331            } else if let Some(slot) = self.free_slots.get_mut(i) {
332                *slot = (base.saturating_add(length), free.wrapping_sub(length));
333            }
334            return Some(base);
335        }
336        let end = self.slots_used.checked_add(length)?;
337        if end > SLOTS {
338            return None;
339        }
340        let base = self.slots_used;
341        self.slots_used = end;
342        Some(base)
343    }
344
345    /// Give an extent back, coalescing with whichever neighbours touch it so
346    /// the list cannot grow past one entry per hole.
347    pub(crate) fn give_slots(&mut self, base: usize, length: usize) {
348        if length == 0 {
349            return;
350        }
351        let mut base = base;
352        let mut length = length;
353        let mut i = 0;
354        while i < self.free_slot_count {
355            let Some(&(other_base, other_len)) = self.free_slots.get(i) else {
356                break;
357            };
358            if other_base.saturating_add(other_len) == base {
359                base = other_base;
360                length = length.saturating_add(other_len);
361                self.drop_free_slot(i);
362                continue;
363            }
364            if base.saturating_add(length) == other_base {
365                length = length.saturating_add(other_len);
366                self.drop_free_slot(i);
367                continue;
368            }
369            i = i.wrapping_add(1);
370        }
371        // An extent at the very end goes back to the bump pointer instead of
372        // the list, which is what keeps a create/delete loop free.
373        if base.saturating_add(length) == self.slots_used {
374            self.slots_used = base;
375            return;
376        }
377        if let Some(slot) = self.free_slots.get_mut(self.free_slot_count) {
378            *slot = (base, length);
379            self.free_slot_count = self.free_slot_count.wrapping_add(1);
380        }
381    }
382
383    fn drop_free_slot(&mut self, index: usize) {
384        let last = self.free_slot_count.saturating_sub(1);
385        if index < last {
386            if let Some(&moved) = self.free_slots.get(last) {
387                if let Some(slot) = self.free_slots.get_mut(index) {
388                    *slot = moved;
389                }
390            }
391        }
392        self.free_slot_count = last;
393    }
394
395    fn new_queue(&mut self, length: usize, kind: Kind) -> Result<QueueHandle> {
396        if length == 0 {
397            return Err(Error::InvalidArgument);
398        }
399        // A zero-item-size queue needs no storage; only real queues do.
400        let slots = if kind.carries_data() { length } else { 0 };
401        let base = self.take_slots(slots).ok_or(Error::Full)?;
402        let handle = match self.queues.try_insert(Queue::new(base, length, kind)) {
403            Ok(handle) => handle,
404            Err(_) => {
405                // The descriptor arena refused after the slots were taken,
406                // so give them straight back rather than stranding them.
407                self.give_slots(base, slots);
408                return Err(Error::Full);
409            }
410        };
411        // `xQueueGenericCreate` takes the queue and its storage from the
412        // heap before it initialises anything.
413        self.account_for_allocation();
414        // `xQueueGenericReset` runs in a critical section before
415        // `traceQUEUE_CREATE` fires at the end of `prvInitialiseNewQueue`.
416        self.enter_critical();
417        self.exit_critical();
418        let tick = self.tick;
419        self.note_exits();
420        self.trace.event(
421            tick,
422            Event::QueueCreate {
423                queue: handle,
424                name: "",
425                length,
426            },
427        );
428        Ok(handle)
429    }
430
431    // ----------------------------------------------------------- getters --
432
433    /// `uxQueueMessagesWaiting`, which takes a critical section.
434    ///
435    /// # Errors
436    /// [`Error::Gone`] for a stale handle.
437    pub fn queue_messages_waiting(&mut self, queue: QueueHandle) -> Result<usize> {
438        self.enter_critical();
439        let n = self.queues.resolve(queue).map(|q| q.waiting);
440        self.exit_critical();
441        n
442    }
443
444    /// `xQueueIsQueueFullFromISR`, which takes NO critical section.
445    ///
446    /// The C compares `uxMessagesWaiting` against `uxLength` and returns,
447    /// with nothing around it — it is meant to be called from an interrupt,
448    /// where a critical section would be the wrong thing. That is why this
449    /// takes `&self` and [`Kernel::queue_messages_waiting`] takes `&mut
450    /// self`: the borrow is the proof that this one cannot charge the
451    /// clock, and on the sim a charged section is a sixteenth of a tick.
452    ///
453    /// # Errors
454    /// [`Error::Gone`] for a stale handle.
455    pub fn queue_is_full_from_isr(&self, queue: QueueHandle) -> Result<bool> {
456        self.queues.resolve(queue).map(|q| q.waiting == q.length)
457    }
458
459    /// `uxSemaphoreGetCount`, which is the same thing.
460    ///
461    /// # Errors
462    /// [`Error::Gone`] for a stale handle.
463    pub fn semaphore_count(&mut self, semaphore: QueueHandle) -> Result<usize> {
464        self.queue_messages_waiting(semaphore)
465    }
466
467    /// `xSemaphoreGetMutexHolderFromISR`, which is
468    /// `xQueueGetMutexHolderFromISR`: the same answer, read without a
469    /// critical section because an ISR is already inside one.
470    ///
471    /// # Errors
472    /// [`Error::Gone`] for a stale handle.
473    pub fn mutex_holder_from_isr(&mut self, mutex: QueueHandle) -> Result<TaskHandle> {
474        self.queues.resolve(mutex).map(|q| q.holder)
475    }
476
477    /// `xSemaphoreGetMutexHolder`, which takes a critical section.
478    ///
479    /// # Errors
480    /// [`Error::Gone`] for a stale handle.
481    pub fn mutex_holder(&mut self, mutex: QueueHandle) -> Result<TaskHandle> {
482        self.enter_critical();
483        let holder = self.queues.resolve(mutex).map(|q| q.holder);
484        self.exit_critical();
485        holder
486    }
487
488    // -------------------------------------------------------------- send --
489
490    /// `xQueueSend` / `xQueueSendToBack`.
491    ///
492    /// # Errors
493    /// [`Error::Full`] when the block time expires with the queue still
494    /// full; [`Error::Gone`] for a stale handle.
495    pub fn queue_send(&mut self, queue: QueueHandle, value: u64, ticks: u64) -> Result<Wait<()>> {
496        self.queue_send_generic(queue, value, ticks, Position::Back)
497    }
498
499    /// `xQueueReset`, which is `xQueueGenericReset( q, pdFALSE )`: empty
500    /// the queue and unlock it, waking one waiting sender if there is one.
501    ///
502    /// The event lists survive — only a brand-new queue re-initialises
503    /// those — so a task blocked on this queue stays blocked, and the one
504    /// woken here is woken because the reset made room.
505    ///
506    /// # Errors
507    /// [`Error::Gone`] for a stale handle.
508    pub fn queue_reset(&mut self, queue: QueueHandle) -> Result<()> {
509        self.enter_critical();
510        let result = (|| {
511            let length = self.queues.resolve(queue)?.length;
512            {
513                let q = self.queues.resolve_mut(queue)?;
514                q.waiting = 0;
515                q.write_to = 0;
516                q.read_from = length.saturating_sub(1);
517                q.rx_lock = UNLOCKED;
518                q.tx_lock = UNLOCKED;
519            }
520            let senders = Self::queue_send_list(queue);
521            if !self.lists.is_empty_of(senders) && self.remove_from_event_list(senders)? {
522                // queueYIELD_IF_USING_PREEMPTION(), inside the section.
523                self.port_yield();
524            }
525            Ok(())
526        })();
527        self.exit_critical();
528        result
529    }
530
531    /// `uxQueueSpacesAvailable`: how many more items would fit.
532    ///
533    /// # Errors
534    /// [`Error::Gone`] for a stale handle.
535    pub fn queue_spaces_available(&mut self, queue: QueueHandle) -> Result<usize> {
536        self.enter_critical();
537        let spaces = self
538            .queues
539            .resolve(queue)
540            .map(|q| q.length.wrapping_sub(q.waiting));
541        self.exit_critical();
542        spaces
543    }
544
545    // --------------------------------------------------- queue sets --
546    //
547    // A queue set is a queue whose items are the handles of the queues in
548    // it. Nothing is *moved* into the set: an item arriving on a member
549    // queue puts that queue's handle on the set, and the task that wakes on
550    // the set reads the handle and then reads the member queue itself. So a
551    // set holds an announcement, not the data — which is why adding a queue
552    // that already has items in it is refused, and why the two counts would
553    // otherwise drift apart forever.
554
555    /// `xQueueCreateSet`: a set that can hold `length` announcements.
556    ///
557    /// # Errors
558    /// As [`Kernel::queue_create`].
559    pub fn queue_create_set(&mut self, length: usize) -> Result<QueueHandle> {
560        self.new_queue(length, Kind::Set)
561    }
562
563    /// `xQueueAddToSet`.
564    ///
565    /// `false` is the C's `pdFAIL`: the target is not a set, the queue is
566    /// already in one, or it has items waiting that the set never saw.
567    ///
568    /// # Errors
569    /// [`Error::Gone`] for a stale handle.
570    pub fn queue_add_to_set(&mut self, queue: QueueHandle, set: QueueHandle) -> Result<bool> {
571        self.enter_critical();
572        let result = (|| {
573            if self.queues.resolve(set)?.kind != Kind::Set {
574                return Ok(false);
575            }
576            let member = self.queues.resolve(queue)?;
577            if !member.set_container.is_null() || member.waiting != 0 {
578                return Ok(false);
579            }
580            self.queues.resolve_mut(queue)?.set_container = set;
581            Ok(true)
582        })();
583        self.exit_critical();
584        result
585    }
586
587    /// `xQueueRemoveFromSet`.
588    ///
589    /// # Errors
590    /// [`Error::Gone`] for a stale handle.
591    pub fn queue_remove_from_set(&mut self, queue: QueueHandle, set: QueueHandle) -> Result<bool> {
592        // Both refusals are tested OUTSIDE the section and only the removal
593        // itself is inside it, which is what the C does -- and it is NOT
594        // what `xQueueAddToSet` does, three functions up, where the whole
595        // body including both refusals is inside one section. The asymmetry
596        // is upstream's and it is load-bearing here: a failing remove costs
597        // the clock nothing, and `QueueSet`'s setup makes one deliberately,
598        // to prove a queue cannot be removed from a set it is not in.
599        // Charging for it put a tick one event early, 30 lines in.
600        let member = *self.queues.resolve(queue)?;
601        if member.set_container != set || member.waiting != 0 {
602            return Ok(false);
603        }
604        self.enter_critical();
605        let result = self
606            .queues
607            .resolve_mut(queue)
608            .map(|q| q.set_container = QueueHandle::NULL);
609        self.exit_critical();
610        result?;
611        Ok(true)
612    }
613
614    /// `xQueueSelectFromSet`: which member queue has something on it.
615    ///
616    /// The C is one line — `xQueueReceive( xQueueSet, &xReturn, xTicksToWait )`
617    /// — so this blocks, traces and costs exactly what a receive does, and
618    /// `None` is the C's `NULL`.
619    ///
620    /// # Errors
621    /// As [`Kernel::queue_receive`].
622    pub fn queue_select_from_set(
623        &mut self,
624        set: QueueHandle,
625        ticks: u64,
626    ) -> Result<Wait<Option<QueueHandle>>> {
627        match self.queue_receive(set, ticks) {
628            Ok(Blocked) => Ok(Blocked),
629            Ok(Ready(raw)) => {
630                let handle = QueueHandle::from_raw(u32::try_from(raw).unwrap_or(0));
631                Ok(Ready((!handle.is_null()).then_some(handle)))
632            }
633            Err(Error::Empty) => Ok(Ready(None)),
634            Err(e) => Err(e),
635        }
636    }
637
638    /// `xQueueSelectFromSetFromISR`: which queue in `set` has data, from
639    /// an interrupt.
640    ///
641    /// The C is three lines -- `xQueueReceiveFromISR` on the set itself,
642    /// with a NULL handle meaning "none" -- because a set IS a queue of
643    /// member handles. This is that, and it takes no critical section for
644    /// the same reason the rest of the FromISR surface does not.
645    ///
646    /// # Errors
647    /// [`Error::Gone`] for a stale handle.
648    pub fn queue_select_from_set_from_isr(
649        &mut self,
650        set: QueueHandle,
651    ) -> Result<Option<QueueHandle>> {
652        match self.queue_receive_from_isr(set) {
653            Ok((raw, _woken)) => {
654                let handle = QueueHandle::from_raw(u32::try_from(raw).unwrap_or(0));
655                Ok((!handle.is_null()).then_some(handle))
656            }
657            // An empty set is "no queue has data", which is what the C's
658            // NULL means; it is not a failure.
659            Err(Error::Empty) => Ok(None),
660            Err(e) => Err(e),
661        }
662    }
663
664    /// `prvNotifyQueueSetContainer`: put `queue`'s handle on the set it
665    /// belongs to. `true` when that woke a task that outranks the current
666    /// one.
667    /// `#[cold]` because the call is GUARDED and reached from many sites on
668    /// one hot path, which is the shape that pays: it lets LLVM keep the
669    /// caller's frame setup out of the likely route. Measured on
670    /// `riscv32-qemu-tick-work`, one attribute at a time.
671    /// Worth queue -1 on its own.
672    #[cold]
673    fn notify_queue_set_container(&mut self, queue: QueueHandle) -> Result<bool> {
674        let set = self.queues.resolve(queue)?.set_container;
675        let container = *self.queues.resolve(set)?;
676        if container.waiting >= container.length {
677            // The C asserts this cannot happen and does nothing if it does.
678            return Ok(false);
679        }
680        let tx_lock = container.tx_lock;
681        let tick = self.tick;
682        self.note_exits();
683        // `traceQUEUE_SET_SEND` is `traceQUEUE_SEND` unless a port says
684        // otherwise, and this port does not.
685        self.trace.event(
686            tick,
687            Event::QueueSend {
688                queue: set,
689                name: "",
690            },
691        );
692        let mut woke =
693            self.copy_data_to_queue(set, &container, u64::from(queue.to_raw()), Position::Back)?;
694        if tx_lock == UNLOCKED {
695            let receivers = Self::queue_receive_list(set);
696            if !self.lists.is_empty_of(receivers)
697                && self.remove_from_event_list(receivers)?
698            {
699                woke = true;
700            }
701        } else {
702            self.increment_tx_lock(set, tx_lock);
703        }
704        Ok(woke)
705    }
706
707    /// `xQueueOverwrite`: write to a length-one queue whether or not it
708    /// already holds something.
709    ///
710    /// The C is `xQueueGenericSend( q, item, 0, queueOVERWRITE )` — a send
711    /// with no block time, because a queue that is always writable can
712    /// never make the caller wait.
713    ///
714    /// # Errors
715    /// As [`Kernel::queue_send`].
716    pub fn queue_overwrite(&mut self, queue: QueueHandle, value: u64) -> Result<Wait<()>> {
717        self.send_generic_outlined(queue, value, 0, Position::Overwrite)
718    }
719
720    // ------------------------------------------------------- from an ISR --
721    //
722    // The `FromISR` half of the API. Three things make it a different
723    // animal from the task half, and all three are visible in a trace:
724    //
725    //   * It never blocks and never yields. It reports that a higher
726    //     priority task woke, by returning a [`Woken`], and the interrupt
727    //     decides what to do about it on the way out.
728    //   * Its critical section is `portSET_INTERRUPT_MASK_FROM_ISR`, not
729    //     `portENTER_CRITICAL`. On the Posix port both are empty, so a call
730    //     here costs no sim time at all — which is exactly what the C does
731    //     and therefore what a matching trace requires.
732    //   * If a task has the queue locked it may not touch the event lists.
733    //     It counts what it did in `cTxLock` / `cRxLock` instead, and
734    //     `prvUnlockQueue` pays the wake-ups back when the task is done.
735
736    /// `xQueueGenericSendFromISR`.
737    ///
738    /// # Errors
739    /// [`Error::Full`] when the queue is full and this is not an overwrite;
740    /// [`Error::Gone`] for a stale handle.
741    pub fn queue_send_generic_from_isr(
742        &mut self,
743        queue: QueueHandle,
744        value: u64,
745        position: Position,
746    ) -> Result<Woken> {
747        let mask = self.port.enter_critical_from_isr();
748        let result = self.send_from_isr_locked(queue, value, position);
749        self.port.exit_critical_from_isr(mask);
750        result
751    }
752
753    fn send_from_isr_locked(
754        &mut self,
755        queue: QueueHandle,
756        value: u64,
757        position: Position,
758    ) -> Result<Woken> {
759        let snapshot = *self.queues.resolve(queue)?;
760        if snapshot.waiting >= snapshot.length && position != Position::Overwrite {
761            // `traceQUEUE_SEND_FROM_ISR_FAILED` is not one of the harness's
762            // hooks, so a full queue says nothing on either side.
763            return Err(Error::Full);
764        }
765        let tx_lock = snapshot.tx_lock;
766        let tick = self.tick;
767        self.note_exits();
768        self.trace
769            .event(tick, Event::QueueSendFromIsr { queue, name: "" });
770        let previously_waiting = snapshot.waiting;
771        let _ = self.copy_data_to_queue(queue, &snapshot, value, position)?;
772        let mut woken = Woken::NO;
773        if tx_lock == UNLOCKED {
774            if C::USE_QUEUE_SETS && !snapshot.set_container.is_null() {
775                let overwrote = position == Position::Overwrite && previously_waiting > 0;
776                if !overwrote && self.notify_queue_set_container(queue)? {
777                    woken = Woken::YES;
778                }
779                return Ok(woken);
780            }
781            let receivers = Self::queue_receive_list(queue);
782            if !self.lists.is_empty_of(receivers)
783                && self.remove_from_event_list(receivers)?
784            {
785                woken = Woken::YES;
786            }
787        } else {
788            self.increment_tx_lock(queue, tx_lock);
789        }
790        Ok(woken)
791    }
792
793    /// `xQueueSendToBackFromISR`.
794    ///
795    /// # Errors
796    /// As [`Kernel::queue_send_generic_from_isr`].
797    pub fn queue_send_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
798        self.queue_send_generic_from_isr(queue, value, Position::Back)
799    }
800
801    /// `xQueueSendToFrontFromISR`.
802    ///
803    /// # Errors
804    /// As [`Kernel::queue_send_generic_from_isr`].
805    pub fn queue_send_to_front_from_isr(
806        &mut self,
807        queue: QueueHandle,
808        value: u64,
809    ) -> Result<Woken> {
810        self.queue_send_generic_from_isr(queue, value, Position::Front)
811    }
812
813    /// `xQueueOverwriteFromISR`. Only for a queue of length one.
814    ///
815    /// # Errors
816    /// As [`Kernel::queue_send_generic_from_isr`].
817    pub fn queue_overwrite_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
818        self.queue_send_generic_from_isr(queue, value, Position::Overwrite)
819    }
820
821    /// `xSemaphoreGiveFromISR`.
822    ///
823    /// # Errors
824    /// As [`Kernel::queue_send_generic_from_isr`].
825    pub fn semaphore_give_from_isr(&mut self, semaphore: QueueHandle) -> Result<Woken> {
826        self.queue_send_generic_from_isr(semaphore, 0, Position::Back)
827    }
828
829    /// `xQueueReceiveFromISR`: the value, and whether a waiting sender that
830    /// this made room for outranks the interrupted task.
831    ///
832    /// # Errors
833    /// [`Error::Empty`] when the queue is empty; [`Error::Gone`] for a
834    /// stale handle.
835    pub fn queue_receive_from_isr(&mut self, queue: QueueHandle) -> Result<(u64, Woken)> {
836        let mask = self.port.enter_critical_from_isr();
837        let result = self.receive_from_isr_locked(queue);
838        self.port.exit_critical_from_isr(mask);
839        result
840    }
841
842    fn receive_from_isr_locked(&mut self, queue: QueueHandle) -> Result<(u64, Woken)> {
843        let snapshot = *self.queues.resolve(queue)?;
844        if snapshot.waiting == 0 {
845            return Err(Error::Empty);
846        }
847        let rx_lock = snapshot.rx_lock;
848        let tick = self.tick;
849        self.note_exits();
850        self.trace
851            .event(tick, Event::QueueReceiveFromIsr { queue, name: "" });
852        let value = self.copy_data_from_queue(
853            queue,
854            snapshot.kind,
855            snapshot.base,
856            snapshot.length,
857            snapshot.read_from,
858            false,
859        )?;
860        let mut woken = Woken::NO;
861        if rx_lock == UNLOCKED {
862            let senders = Self::queue_send_list(queue);
863            if !self.lists.is_empty_of(senders) && self.remove_from_event_list(senders)? {
864                woken = Woken::YES;
865            }
866        } else {
867            self.increment_rx_lock(queue, rx_lock);
868        }
869        Ok((value, woken))
870    }
871
872    /// `xQueuePeekFromISR`: the head without removing it.
873    ///
874    /// It wakes nobody and traces nothing — the C has no hook for it —
875    /// which is why it returns a bare value rather than a [`Woken`].
876    ///
877    /// # Errors
878    /// [`Error::Empty`] when the queue is empty; [`Error::Gone`] for a
879    /// stale handle.
880    pub fn queue_peek_from_isr(&mut self, queue: QueueHandle) -> Result<u64> {
881        let mask = self.port.enter_critical_from_isr();
882        let result = match self.queues.resolve(queue) {
883            Ok(q) if q.waiting > 0 => {
884                let snapshot = *q;
885                self.copy_data_from_queue(
886                    queue,
887                    snapshot.kind,
888                    snapshot.base,
889                    snapshot.length,
890                    snapshot.read_from,
891                    true,
892                )
893            }
894            Ok(_) => Err(Error::Empty),
895            Err(e) => Err(e),
896        };
897        self.port.exit_critical_from_isr(mask);
898        result
899    }
900
901    /// `prvIncrementQueueTxLock`, capped at the task count as the C caps it.
902    fn increment_tx_lock(&mut self, queue: QueueHandle, tx_lock: i8) {
903        let tasks = self.task_count();
904        if let Ok(q) = self.queues.resolve_mut(queue) {
905            // 32-bit throughout. This was `i64::from(lock) < tasks as i64`,
906            // which is a SIXTY-FOUR-bit signed compare on a target whose
907            // registers are 32 -- to order an `i8` against a task count. The
908            // `< 0` arm is what makes the unsigned cast safe and is the
909            // UNLOCKED sentinel's case, which cannot reach the increment.
910            if tx_lock < 0 || (tx_lock as usize) < tasks {
911                q.tx_lock = tx_lock.wrapping_add(1);
912            }
913        }
914    }
915
916    /// `prvIncrementQueueRxLock`.
917    fn increment_rx_lock(&mut self, queue: QueueHandle, rx_lock: i8) {
918        let tasks = self.task_count();
919        if let Ok(q) = self.queues.resolve_mut(queue) {
920            // 32-bit throughout. This was `i64::from(lock) < tasks as i64`,
921            // which is a SIXTY-FOUR-bit signed compare on a target whose
922            // registers are 32 -- to order an `i8` against a task count. The
923            // `< 0` arm is what makes the unsigned cast safe and is the
924            // UNLOCKED sentinel's case, which cannot reach the increment.
925            if rx_lock < 0 || (rx_lock as usize) < tasks {
926                q.rx_lock = rx_lock.wrapping_add(1);
927            }
928        }
929    }
930
931    /// `xQueueSendToFront`.
932    ///
933    /// # Errors
934    /// As [`Kernel::queue_send`].
935    pub fn queue_send_to_front(
936        &mut self,
937        queue: QueueHandle,
938        value: u64,
939        ticks: u64,
940    ) -> Result<Wait<()>> {
941        self.send_generic_outlined(queue, value, ticks, Position::Front)
942    }
943
944    /// `xSemaphoreGive`: a send with no data.
945    ///
946    /// # Errors
947    /// [`Error::Full`] when the semaphore is already at its maximum count.
948    pub fn semaphore_give(&mut self, semaphore: QueueHandle) -> Result<Wait<()>> {
949        self.send_generic_outlined(semaphore, 0, 0, Position::Back)
950    }
951
952    /// The out-of-line handle on [`Kernel::queue_send_generic`]'s body.
953    ///
954    /// One shared copy for the wrappers that are not on a measured hot row --
955    /// `queue_send_to_front`, `queue_overwrite`, `semaphore_give` and the
956    /// timer daemon's post. `queue_send` keeps the inlined body because
957    /// `send_full`, `queue_roundtrip` and `block_cycle` all go through it and
958    /// all three pay for the call.
959    #[inline(never)]
960    pub(crate) fn send_generic_outlined(
961        &mut self,
962        queue: QueueHandle,
963        value: u64,
964        ticks: u64,
965        position: Position,
966    ) -> Result<Wait<()>> {
967        self.queue_send_generic(queue, value, ticks, position)
968    }
969
970    /// `xQueueGenericSend`, one pass of its `for(;;)`.
971    ///
972    /// # Errors
973    /// [`Error::Full`] on timeout; [`Error::Gone`] for a stale handle.
974    /// In line on purpose, for the same reason as
975    /// [`Kernel::queue_take`]: seven instructions of prologue and ten of
976    /// epilogue on every one of khot-ir's 48,000 sends, so that `xQueueSend`
977    /// and its siblings could pass four arguments through unchanged. This
978    /// one pays on every instrument, `kernel-ir` included.
979    ///
980    /// **But only the HOT site wants it.** With the flash probe fixed so that
981    /// real bodies link at all (2026-09-24), this was inlined at five places
982    /// and cost about 1,666 bytes of duplicate.
983    ///
984    /// RE-PRICED 2026-09-25, because that figure was taken at FIVE inline sites
985    /// and there is now one. Dropping the hint today measures:
986    ///
987    /// * flash **19,302 -> 18,704, i.e. -598 B**, with `mv` -31, `andi` -7,
988    ///   `slli` -8 and 221 fewer instructions;
989    /// * rv32 work rows **+118 instructions** over seven of them —
990    ///   `queue_roundtrip` 122 -> 169, `block_cycle` 983 -> 1022,
991    ///   `send_full` 36 -> 62, and +1 or +2 on four more.
992    ///
993    /// That is **5.07 bytes of flash per instruction**, a worse rate than the
994    /// `queue_peek` trade declined at 7.3 and than the 10.7 this hint was
995    /// originally kept at. So it stays — but the K3 flash row is the one
996    /// FAILING its target while the work rows are absolutes with no C
997    /// comparison, so if that priority ever inverts this is the single largest
998    /// item in the send path and the numbers are here. `rusty-compiler-leverage` A4: a function has one
999    /// body, so one inlining decision serves callers who want different
1000    /// things -- give it two names instead of averaging them.
1001    /// [`Kernel::send_generic_outlined`] is the out-of-line handle, and the
1002    /// four colder wrappers call that.
1003    #[inline(always)]
1004    pub fn queue_send_generic(
1005        &mut self,
1006        queue: QueueHandle,
1007        value: u64,
1008        ticks: u64,
1009        position: Position,
1010    ) -> Result<Wait<()>> {
1011        let caller = self.current;
1012        // Resuming below the sampling exit, as the C's thread does. See
1013        // `Kernel::take_queue_resume`: the prologue has already run, and
1014        // repeating it would spend a second critical-section exit that the
1015        // C never spends.
1016        if self.take_queue_resume(caller) != QueueResume::No {
1017            // The send's only resume point is below its sampling exit: its
1018            // timed-out branch has nothing after `resume_all` that costs an
1019            // exit, so being switched away there changes no count.
1020            return self.queue_send_blocking(caller, queue);
1021        }
1022        self.enter_critical();
1023        let snapshot = match self.queues.resolve(queue) {
1024            Ok(q) => *q,
1025            Err(e) => {
1026                self.exit_critical();
1027                return Err(e);
1028            }
1029        };
1030        // The wait frame is set where the C sets it: `xQueueReceive` and
1031        // `xQueueGenericSend` call `vTaskInternalSetTimeOutState` only
1032        // after finding the queue unusable AND the block time non-zero,
1033        // guarded by `xEntryTimeSet`. Setting it up here instead meant
1034        // every *successful* call wrote a six-field frame and then had
1035        // `end_wait` wipe it on the way out.
1036        //
1037        // It also has to be after the resolve, so that a handle naming
1038        // nothing leaves the caller exactly as it found it -- which is
1039        // what `configASSERT( pxQueue )` means in the C.
1040        // `( uxMessagesWaiting < uxLength ) || ( xCopyPosition == queueOVERWRITE )`
1041        if snapshot.waiting < snapshot.length || position == Position::Overwrite {
1042            self.note_exits();
1043            let tick = self.tick;
1044            self.trace.event(tick, Event::QueueSend { queue, name: "" });
1045            let previously_waiting = snapshot.waiting;
1046            let yield_required = self.copy_data_to_queue(queue, &snapshot, value, position)?;
1047            if C::USE_QUEUE_SETS && !snapshot.set_container.is_null() {
1048                // A queue in a set announces the arrival there, not here.
1049                // An overwrite of an item that was already present is not an
1050                // arrival: the count did not change, so the set is not told.
1051                let overwrote = position == Position::Overwrite && previously_waiting > 0;
1052                if !overwrote && self.notify_queue_set_container(queue)? {
1053                    self.port_yield();
1054                }
1055                self.exit_critical();
1056                self.end_wait(caller);
1057                return Ok(Ready(()));
1058            }
1059            let receivers = Self::queue_receive_list(queue);
1060            let woke_higher = if !self.lists.is_empty_of(receivers) {
1061                self.remove_from_event_list(receivers)?
1062            } else {
1063                false
1064            };
1065            // queueYIELD_IF_USING_PREEMPTION(), inside the section.
1066            // `yield_required` first: it is false on every send that is
1067            // not a mutex give, and it is a local, so on the common path
1068            // the list is not read a second time at all. Both operands are
1069            // pure, so the order is free to choose. (The read cannot be
1070            // hoisted above the removal above it -- removing the last
1071            // waiter is exactly what changes the answer.)
1072            if woke_higher || (yield_required && self.lists.is_empty_of(receivers)) {
1073                self.port_yield();
1074            }
1075            self.exit_critical();
1076            self.end_wait(caller);
1077            return Ok(Ready(()));
1078        }
1079        let remaining = self.begin_wait(caller, queue, ticks);
1080        if remaining.unwrap_or(0) == 0 {
1081            self.exit_critical();
1082            self.trace_failure_or_owe(caller, OwedTrace::SendFailed(queue));
1083            if remaining.is_some() {
1084                // A frame was written, so it has to be torn down. `None` means
1085                // `begin_wait` took its zero-block-time exit and wrote
1086                // nothing, and then `end_wait` is a provable no-op.
1087                self.end_wait(caller);
1088            }
1089            return Err(Error::Full);
1090        }
1091        self.exit_critical();
1092        // That exit can release a tick, and a tick can switch this task
1093        // away. The C's thread stops INSIDE the exit, so everything below
1094        // runs when the task is scheduled again -- and names that task.
1095        if self.current != caller {
1096            self.set_queue_resume(caller, QueueResume::BelowSample);
1097            return Ok(Blocked);
1098        }
1099        self.queue_send_blocking(caller, queue)
1100    }
1101
1102    /// Everything `xQueueGenericSend` does below its sampling exit.
1103    ///
1104    /// Split out so a call preempted at that exit re-enters here rather
1105    /// than at the top. See [`Kernel::take_queue_resume`].
1106    #[cold]
1107    fn queue_send_blocking(&mut self, caller: TaskHandle, queue: QueueHandle) -> Result<Wait<()>> {
1108        self.suspend_all();
1109        self.lock_queue(queue);
1110        let left = self.check_for_timeout(caller);
1111        if left.is_none() {
1112            self.unlock_queue(queue)?;
1113            let _ = self.resume_all();
1114            self.trace_failure_or_owe(caller, OwedTrace::SendFailed(queue));
1115            self.end_wait(caller);
1116            return Err(Error::Full);
1117        }
1118        if self.is_queue_full(queue) {
1119            self.note_exits();
1120            let tick = self.tick;
1121            self.trace
1122                .event(tick, Event::BlockingOnQueueSend { queue, name: "" });
1123            // `check_for_timeout` above already resolved the TCB and wrote
1124            // this field; `remaining_ticks` resolved it a second time to read
1125            // it back.
1126            let ticks_left = left.map_or(0, core::num::NonZeroU64::get);
1127            self.place_on_event_list(Self::queue_send_list(queue), ticks_left)?;
1128            self.unlock_queue(queue)?;
1129            if !self.resume_all() {
1130                self.yield_or_owe(caller);
1131            }
1132        } else {
1133            self.unlock_queue(queue)?;
1134            let _ = self.resume_all();
1135        }
1136        Ok(Blocked)
1137    }
1138
1139    /// `prvCopyDataToQueue`; `true` when giving a mutex back lowered the
1140    /// giver's priority and a yield is therefore wanted.
1141    ///
1142    /// This resolves rather than taking the caller's snapshot, and
1143    /// [`Kernel::copy_data_from_queue`] does the opposite. That is not an
1144    /// inconsistency: both forms were measured on both helpers and they
1145    /// disagree, because the writer's caller does not keep its snapshot
1146    /// live across the call and the reader's does.
1147    ///
1148    /// In line on purpose, at ALL THREE call sites.
1149    ///
1150    /// The rationale here used to say `queue_send_generic` was its only caller.
1151    /// That is no longer true — `queue_add_to_set` and
1152    /// `queue_send_generic_from_isr` call it too — so an A4 split was tried on
1153    /// 2026-09-25, keeping the hint for the hot caller and routing the cold ones
1154    /// through an out-of-line handle. It measured **+72 B of flash**, `mv` +12
1155    /// and 49 more instructions, and was reverted. `prime_mutex` was a fourth
1156    /// caller when that was measured; it was deleted later the same day (see
1157    /// [`Self::new_mutex`]) and the split was **re-tested at three callers**:
1158    /// **+6 B**, still a loss but only a twelfth of the old one. So ~66 of the
1159    /// original 72 bytes were `prime_mutex`'s own site — an A4 verdict can be
1160    /// carried almost entirely by ONE caller, which is why §9's re-test law
1161    /// exists. At three callers this is now a near-tie held by 6 bytes.
1162    ///
1163    /// The reason is worth keeping: the cold callers pass CONSTANT arguments
1164    /// (`Position::Back` from `queue_add_to_set`), so each inlined copy is
1165    /// SPECIALISED and folds well below the 138 bytes C's `prvCopyDataToQueue`
1166    /// occupies. Out of line they pay a five-argument frame and force
1167    /// `&snapshot` into memory, which costs more than the copies they remove.
1168    ///
1169    /// The hot reason also still stands: out of line it paid a call and a frame
1170    /// on all 48,000 sends of `bench/kernel-ir` to move one value into a slot
1171    /// the caller had already resolved.
1172    #[inline(always)]
1173    fn copy_data_to_queue(
1174        &mut self,
1175        queue: QueueHandle,
1176        snapshot: &Queue,
1177        value: u64,
1178        position: Position,
1179    ) -> Result<bool> {
1180        // The snapshot comes from the caller, which has already resolved this
1181        // handle -- and nothing between that resolve and this call can reach
1182        // the arena. Resolving again here made every send pay for the same
1183        // four checks twice. `copy_data_from_queue` has always taken its
1184        // snapshot this way.
1185        let mut yield_required = false;
1186        // `prvCopyDataToQueue` counts the item in — except on an overwrite
1187        // of a queue that already held one, where it decrements first so
1188        // the increment cancels and the count stays where it was.
1189        //
1190        // Decided once, up here, so that each arm below can fold the count
1191        // into the resolve it is already making. Deciding it after the arms
1192        // is what forced a further resolve for one field.
1193        let counted = !(position == Position::Overwrite && snapshot.waiting > 0);
1194        if snapshot.kind.carries_data() {
1195            let (index, next_read, next_write) = match position {
1196                Position::Back => (
1197                    snapshot.write_to,
1198                    snapshot.read_from,
1199                    wrap_next(snapshot.write_to, snapshot.length),
1200                ),
1201                // Write at the item last read, then step back, so the next
1202                // read's pre-increment lands on it. An overwrite takes the
1203                // same path; only the message count differs.
1204                Position::Front | Position::Overwrite => (
1205                    snapshot.read_from,
1206                    wrap_prev(snapshot.read_from, snapshot.length),
1207                    snapshot.write_to,
1208                ),
1209            };
1210            // `base + index` is below `base + length`, which the geometry
1211            // put inside `SLOTS`; and the `get_mut` refuses anything it is
1212            // not, so nothing rests on the arithmetic either way.
1213            if let Some(slot) = self.slots.get_mut(snapshot.base.wrapping_add(index)) {
1214                *slot = value;
1215            }
1216            let q = self.queues.resolve_mut(queue)?;
1217            q.read_from = next_read;
1218            q.write_to = next_write;
1219            if counted {
1220                q.waiting = q.waiting.wrapping_add(1);
1221            }
1222        } else if snapshot.kind.is_mutex() {
1223            // Giving a mutex back: the holder drops any inherited
1224            // priority. The disinherit touches the holder's TCB, not this
1225            // queue, so the resolve after it is still the first one.
1226            yield_required = self.priority_disinherit(snapshot.holder)?;
1227            let q = self.queues.resolve_mut(queue)?;
1228            q.holder = TaskHandle::NULL;
1229            if counted {
1230                q.waiting = q.waiting.wrapping_add(1);
1231            }
1232        } else if counted {
1233            // A counting or binary semaphore: only the count moves.
1234            let q = self.queues.resolve_mut(queue)?;
1235            q.waiting = q.waiting.wrapping_add(1);
1236        }
1237        Ok(yield_required)
1238    }
1239
1240    // ----------------------------------------------------------- receive --
1241
1242    /// The out-of-line handle on [`Kernel::queue_take`]s body.
1243    ///
1244    /// `peek` was a `const PEEK: bool`, which gave the whole take chain TWO
1245    /// monomorphisations and three inlined copies of a ~600-byte body that no
1246    /// A4 split could share, because `<true>` and `<false>` are different
1247    /// functions. As a runtime flag there is one body to share.
1248    ///
1249    /// Only `semaphore_take` uses this handle. `queue_receive` and `queue_peek`
1250    /// keep the inlined body because all four of `recv_empty`, `peek_ok`,
1251    /// `queue_roundtrip` and `block_cycle` go through one or the other --
1252    /// routing `queue_peek` here cost `peek_ok` **45 -> 108**, which is what a
1253    /// call and a frame are worth on a row that short.
1254    #[inline(never)]
1255    fn take_outlined(&mut self, queue: QueueHandle, ticks: u64, peek: bool) -> Result<Wait<u64>> {
1256        self.queue_take(queue, ticks, peek)
1257    }
1258
1259    /// `xQueueReceive`.
1260    ///
1261    /// # Errors
1262    /// [`Error::Empty`] when the block time expires with the queue still
1263    /// empty; [`Error::Gone`] for a stale handle.
1264    pub fn queue_receive(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
1265        self.queue_take(queue, ticks, false)
1266    }
1267
1268    /// `xQueuePeek`: read the head without removing it.
1269    ///
1270    /// # Errors
1271    /// As [`Kernel::queue_receive`].
1272    pub fn queue_peek(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
1273        self.queue_take(queue, ticks, true)
1274    }
1275
1276    /// `xSemaphoreTake`, which is `xQueueSemaphoreTake`: a receive with no
1277    /// data, and — on a mutex — with priority inheritance while it waits.
1278    ///
1279    /// # Errors
1280    /// [`Error::Empty`] on timeout; [`Error::Gone`] for a stale handle.
1281    // A3: ONE caller, so the out-of-line body pays a prologue and epilogue for
1282    // a single call. Inlining moves the body rather than duplicating it.
1283    #[inline]
1284    pub fn semaphore_take(&mut self, semaphore: QueueHandle, ticks: u64) -> Result<Wait<()>> {
1285        match self.take_outlined(semaphore, ticks, false)? {
1286            Blocked => Ok(Blocked),
1287            Ready(_) => Ok(Ready(())),
1288        }
1289    }
1290
1291    /// The shared body of `xQueueReceive`, `xQueuePeek` and
1292    /// `xQueueSemaphoreTake` — one pass of the C `for(;;)`.
1293    /// `peek` is a const because it is one at every call site: a receive
1294    /// passes `false`, a peek `true`, and a semaphore take `false`. As a
1295    /// parameter it cost an argument to set up and a branch at each of the
1296    /// ten places this function and its copy helper consult it.
1297    /// In line on purpose, into all three of `xQueueReceive`, `xQueuePeek`
1298    /// and `xSemaphoreTake`.
1299    ///
1300    /// Out of line it charged eight instructions of prologue and ten of
1301    /// epilogue to every take -- 48,000 of them in `khot-ir`, which is 7.6%
1302    /// of that instrument -- so that three wrappers could each hand it two
1303    /// arguments and return its result unchanged. LLVM declined on size; the
1304    /// frame is the reason to overrule that.
1305    ///
1306    /// The cost is stated rather than hidden: `kernel-ir` pays 214,804 for
1307    /// the larger wrappers. Splitting the body from the symbol does not
1308    /// recover it -- outlining at the semaphore site alone leaves `kernel-ir`
1309    /// 262,828 up and gives back 427,983 of `khot-ir`'s win, and outlining at
1310    /// the receive site leaves it 190,238 up and gives back 1,104,183 -- so
1311    /// the regression is the wrappers growing, not any one call site.
1312    #[inline(always)]
1313    fn queue_take(&mut self, queue: QueueHandle, ticks: u64, peek: bool) -> Result<Wait<u64>> {
1314        let caller = self.current;
1315        // Resuming below the sampling exit, as `queue_send_generic` does.
1316        // The snapshot is re-read rather than carried: nothing below uses
1317        // anything of it that a concurrent access could change, and the
1318        // read takes no critical section, so it costs the clock nothing.
1319        match self.take_queue_resume(caller) {
1320            QueueResume::No => {}
1321            QueueResume::BelowSample => {
1322                return self.queue_take_blocking(caller, queue, peek);
1323            }
1324            QueueResume::BelowTimedOutResume => {
1325                return self.queue_take_timed_out(queue, peek);
1326            }
1327        }
1328        self.enter_critical();
1329        // ONLY the fields the fast path reads. This was `*q` -- the whole
1330        // eleven-field descriptor copied to reach five of them, and on rv32
1331        // that is nine words of `usize` where four are dead on every
1332        // successful receive. Eleven live fields is also more than LLVM will
1333        // keep in hand, which is why this function claimed callee-saved
1334        // registers it had no use for. The blocking tail below still wants
1335        // the whole thing and re-resolves for it, outside the section and at
1336        // no cost to the clock, exactly as the resume arms above do.
1337        let (waiting, kind, base, length, read_from) = match self.queues.resolve(queue) {
1338            Ok(q) => (q.waiting, q.kind, q.base, q.length, q.read_from),
1339            Err(e) => {
1340                self.exit_critical();
1341                return Err(e);
1342            }
1343        };
1344        // The wait frame is set where the C sets it: `xQueueReceive` and
1345        // `xQueueGenericSend` call `vTaskInternalSetTimeOutState` only
1346        // after finding the queue unusable AND the block time non-zero,
1347        // guarded by `xEntryTimeSet`. Setting it up here instead meant
1348        // every *successful* call wrote a six-field frame and then had
1349        // `end_wait` wipe it on the way out.
1350        //
1351        // It also has to be after the resolve, so that a handle naming
1352        // nothing leaves the caller exactly as it found it -- which is
1353        // what `configASSERT( pxQueue )` means in the C.
1354        if waiting > 0 {
1355            let value = self.copy_data_from_queue(queue, kind, base, length, read_from, peek)?;
1356            self.note_exits();
1357            let tick = self.tick;
1358            // `xQueuePeek` is its own function in the C with its own trace
1359            // macro; `xQueueSemaphoreTake` shares `xQueueReceive`'s.
1360            let event = if peek {
1361                Event::QueuePeek { queue, name: "" }
1362            } else {
1363                Event::QueueReceive { queue, name: "" }
1364            };
1365            self.trace.event(tick, event);
1366            if peek {
1367                // A peek wakes another *receiver*, not a sender: the item
1368                // is still there.
1369                let receivers = Self::queue_receive_list(queue);
1370                if !self.lists.is_empty_of(receivers)
1371                    && self.remove_from_event_list(receivers)?
1372                {
1373                    self.port_yield();
1374                }
1375            } else {
1376                if kind.is_mutex() {
1377                    self.queues.resolve_mut(queue)?.holder = caller;
1378                    self.increment_mutexes_held(caller);
1379                }
1380                let senders = Self::queue_send_list(queue);
1381                if !self.lists.is_empty_of(senders)
1382                    && self.remove_from_event_list(senders)?
1383                {
1384                    self.port_yield();
1385                }
1386            }
1387            self.exit_critical();
1388            self.end_wait(caller);
1389            return Ok(Ready(value));
1390        }
1391        let remaining = self.begin_wait(caller, queue, ticks);
1392        if remaining.unwrap_or(0) == 0 {
1393            self.exit_critical();
1394            // `traceQUEUE_peek_FAILED` is not one of the harness's hooks,
1395            // so a failed peek says nothing on either side.
1396            if !peek {
1397                self.trace_failure_or_owe(caller, OwedTrace::ReceiveFailed(queue));
1398            }
1399            if remaining.is_some() {
1400                self.end_wait(caller);
1401            }
1402            return Err(Error::Empty);
1403        }
1404        self.exit_critical();
1405        // That exit can release a tick, and a tick can switch this task
1406        // away. The C's thread stops INSIDE the exit, so everything below
1407        // runs when the task is scheduled again -- and names that task.
1408        if self.current != caller {
1409            self.set_queue_resume(caller, QueueResume::BelowSample);
1410            return Ok(Blocked);
1411        }
1412        self.queue_take_blocking(caller, queue, peek)
1413    }
1414
1415    /// Everything `xQueueReceive` and `xQueuePeek` do below their sampling
1416    /// exit. See [`Kernel::take_queue_resume`].
1417    #[cold]
1418    fn queue_take_blocking(
1419        &mut self,
1420        caller: TaskHandle,
1421        queue: QueueHandle,
1422        peek: bool,
1423    ) -> Result<Wait<u64>> {
1424        // `kind` is read HERE rather than handed down from the caller, because
1425        // it is the one field of the descriptor that cannot change after
1426        // `new_queue` sets it -- so resolving it late reads the same byte, and
1427        // resolving it early only lengthened a live range across the hot
1428        // function's whole body.
1429        //
1430        // SINKING it below the timed-out branch -- which never reads it, and
1431        // whose callee resolves `kind` for itself -- removes a resolve from
1432        // that path and measured **+2 B** on 2026-09-25. Refuted: the resolve
1433        // is still emitted once at the later site and the branch around it grew
1434        // by more. Both paths are `#[cold]`, so there was no runtime case to
1435        // weigh against the bytes.
1436        let kind = self.queues.resolve(queue)?.kind;
1437        self.suspend_all();
1438        self.lock_queue(queue);
1439        let left = self.check_for_timeout(caller);
1440        if left.is_none() {
1441            self.unlock_queue(queue)?;
1442            let _ = self.resume_all();
1443            // `xTaskResumeAll` replays any tick that pended while the
1444            // scheduler was suspended, and replaying it can switch this task
1445            // away with `prvIsQueueEmpty` still to run. The C's thread stops
1446            // inside it; everything below runs when the task is next
1447            // scheduled. Without this, `prvIsQueueEmpty`'s section is spent
1448            // in the wrong window -- one exit, and IntQueue's 100,000-tick
1449            // run diverges at tick 16,260.
1450            if self.current != caller {
1451                self.set_queue_resume(caller, QueueResume::BelowTimedOutResume);
1452                return Ok(Blocked);
1453            }
1454            return self.queue_take_timed_out(queue, peek);
1455        }
1456        // `left` is `Some` here, and it carries the block time
1457        // `check_for_timeout` has just written into the TCB.
1458        self.queue_take_locked(caller, queue, peek, kind, left.map_or(0, core::num::NonZeroU64::get))
1459    }
1460
1461    /// `xQueueReceive` below the `xTaskResumeAll` of its timed-out branch.
1462    /// `caller` is read here rather than passed, for the reason given on
1463    /// [`Kernel::queue_take_blocking`]: both call sites have already
1464    /// established that it is `self.current`.
1465    #[cold]
1466    fn queue_take_timed_out(
1467        &mut self,
1468        queue: QueueHandle,
1469        peek: bool,
1470    ) -> Result<Wait<u64>> {
1471        let caller = self.current;
1472        // `kind` is read HERE rather than handed down from the caller,
1473        // because it is the one field of the descriptor that cannot change
1474        // after `new_queue` sets it -- so resolving it late reads the same
1475        // byte, and resolving it early only lengthened a live range across
1476        // the hot function's whole body.
1477        let kind = self.queues.resolve(queue)?.kind;
1478        {
1479            if self.is_queue_empty(queue) {
1480                if kind.is_mutex() && self.wait_inherited(caller) {
1481                    // `vTaskPriorityDisinheritAfterTimeout`: the holder
1482                    // keeps only what the still-waiting tasks justify.
1483                    self.enter_critical();
1484                    let highest = self.highest_waiting_priority(queue)?;
1485                    let holder = self.queues.resolve(queue).map(|q| q.holder)?;
1486                    self.priority_disinherit_after_timeout(holder, highest)?;
1487                    self.exit_critical();
1488                }
1489                if !peek {
1490                    self.trace_failure_or_owe(caller, OwedTrace::ReceiveFailed(queue));
1491                }
1492                self.end_wait(caller);
1493                return Err(Error::Empty);
1494            }
1495            Ok(Blocked)
1496        }
1497    }
1498
1499    /// `xQueueReceive` below its timeout test, with the queue still locked.
1500    fn queue_take_locked(
1501        &mut self,
1502        caller: TaskHandle,
1503        queue: QueueHandle,
1504        peek: bool,
1505        // The descriptor's `kind`, and ONLY that. All three of these
1506        // functions took the whole `Queue` by value -- thirty-six bytes on
1507        // rv32, copied at every hop of a three-deep chain -- to read
1508        // `kind.is_mutex()` twice. Nothing else of it was ever touched.
1509        kind: Kind,
1510        ticks_left: u64,
1511    ) -> Result<Wait<u64>> {
1512        // Both arms end the same way -- unlock, then resume -- and
1513        // `resume_all_inline` is exactly that: INLINE. Written as two arms it
1514        // was two copies of its body in one function. The sequence below is
1515        // the sequence both arms had, in the same order, because on the sim a
1516        // critical-section exit is the clock and reordering one is a
1517        // divergence.
1518        let was_empty = self.is_queue_empty(queue);
1519        if was_empty {
1520            let event = if peek {
1521                Event::BlockingOnQueuePeek { queue, name: "" }
1522            } else {
1523                Event::BlockingOnQueueReceive { queue, name: "" }
1524            };
1525            self.note_exits();
1526            let tick = self.tick;
1527            self.trace.event(tick, event);
1528            if kind.is_mutex() {
1529                self.enter_critical();
1530                let holder = self.queues.resolve(queue).map(|q| q.holder)?;
1531                let inherited = self.priority_inherit(holder)?;
1532                self.exit_critical();
1533                if inherited {
1534                    self.set_wait_inherited(caller);
1535                }
1536            }
1537            self.place_on_event_list(Self::queue_receive_list(queue), ticks_left)?;
1538        }
1539        self.unlock_queue(queue)?;
1540        let yielded = self.resume_all_inline();
1541        if was_empty && !yielded {
1542            self.yield_or_owe(caller);
1543        }
1544        Ok(Blocked)
1545    }
1546
1547    /// `prvCopyDataFromQueue`, with the peek variant putting the cursor
1548    /// back as `xQueuePeek` does -- over fields its caller already read.
1549    ///
1550    /// Every caller resolves this queue to decide whether there is
1551    /// anything to read; this used to resolve it again to do the reading.
1552    /// The snapshot cannot be stale — nothing between the two touches this
1553    /// queue, and both are inside the same critical section.
1554    ///
1555    /// The same change to [`Kernel::copy_data_to_queue`] is **refused**,
1556    /// and the pair is why this bench exists: threading the snapshot into
1557    /// the writer is worth -245,389 Ir inside it and +211,717 in
1558    /// `queue_send_generic`, because a `&Queue` argument forces the
1559    /// caller's local to be addressable and it stops living in registers.
1560    /// Here the caller is `queue_take`, which keeps its snapshot alive
1561    /// across the call anyway, so there is no spill to pay for.
1562    fn copy_data_from_queue(
1563        &mut self,
1564        queue: QueueHandle,
1565        kind: Kind,
1566        base: usize,
1567        length: usize,
1568        read_from: usize,
1569        peek: bool,
1570    ) -> Result<u64> {
1571        if !kind.carries_data() {
1572            if !peek {
1573                let q = self.queues.resolve_mut(queue)?;
1574                // Wrapping: all three callers reach here under
1575                // `waiting > 0`, and the doc above says the snapshot they
1576                // tested cannot be stale, so there is an item to take.
1577                q.waiting = q.waiting.wrapping_sub(1);
1578            }
1579            return Ok(0);
1580        }
1581        let next = wrap_next(read_from, length);
1582        let value = self
1583            .slots
1584            .get(base.wrapping_add(next))
1585            .copied()
1586            .unwrap_or(0);
1587        // `xQueuePeek` saves and restores `pcReadFrom` — which is to
1588        // say it leaves it exactly as it found it. Writing it back stored
1589        // the value already there, and the resolve that reached it was a
1590        // whole handle validation for a no-op.
1591        if !peek {
1592            let q = self.queues.resolve_mut(queue)?;
1593            q.read_from = next;
1594            // Wrapping, for the same reason as the branch above.
1595            q.waiting = q.waiting.wrapping_sub(1);
1596        }
1597        Ok(value)
1598    }
1599
1600    // ------------------------------------------------------ recursive mutex --
1601
1602    /// `xSemaphoreTakeRecursive`.
1603    ///
1604    /// # Errors
1605    /// [`Error::Empty`] on timeout; [`Error::Gone`] for a stale handle.
1606    pub fn mutex_take_recursive(&mut self, mutex: QueueHandle, ticks: u64) -> Result<Wait<()>> {
1607        let caller = self.current;
1608        // One resolve reads the holder and counts the re-entry.
1609        // `resolve_mut` runs the same four checks and answers the same
1610        // errors, so asking twice only asked twice.
1611        {
1612            let q = self.queues.resolve_mut(mutex)?;
1613            if q.holder == caller {
1614                q.recursions = q.recursions.wrapping_add(1);
1615                return Ok(Ready(()));
1616            }
1617        }
1618        match self.semaphore_take(mutex, ticks)? {
1619            Blocked => Ok(Blocked),
1620            Ready(()) => {
1621                let q = self.queues.resolve_mut(mutex)?;
1622                q.recursions = q.recursions.wrapping_add(1);
1623                Ok(Ready(()))
1624            }
1625        }
1626    }
1627
1628    /// `xSemaphoreGiveRecursive`.
1629    ///
1630    /// # Errors
1631    /// [`Error::NotActive`] when the caller does not hold the mutex.
1632    pub fn mutex_give_recursive(&mut self, mutex: QueueHandle) -> Result<()> {
1633        let caller = self.current;
1634        // One resolve, as in the take above.
1635        let remaining = {
1636            let q = self.queues.resolve_mut(mutex)?;
1637            if q.holder != caller {
1638                return Err(Error::NotActive);
1639            }
1640            q.recursions = q.recursions.wrapping_sub(1);
1641            q.recursions
1642        };
1643        if remaining == 0 {
1644            let _ = self.semaphore_give(mutex)?;
1645        }
1646        Ok(())
1647    }
1648
1649    // -------------------------------------------------------- queue locks --
1650
1651    /// `prvLockQueue`: one critical section. The lock counters themselves
1652    /// only matter to an ISR, and the sim has none — but the section is
1653    /// where sim time passes, so it is here.
1654    /// `prvLockQueue`: stop interrupts taking tasks off this queue's event
1655    /// lists while a task walks them. An interrupt that finds the queue
1656    /// locked counts what it did instead, and [`Kernel::unlock_queue`] pays
1657    /// it back.
1658    // In line at both callers (`rusty-compiler-leverage` A3): win 23, which
1659    // took this and `is_queue_empty`/`lock_queue`'s siblings together for
1660    // -48 B of flash. A two-caller body this small pays two frames for a
1661    // resolve and a critical section; `#[inline]` alone was declined.
1662    #[inline(always)]
1663    fn lock_queue(&mut self, queue: QueueHandle) {
1664        self.enter_critical();
1665        if let Ok(q) = self.queues.resolve_mut(queue) {
1666            if q.rx_lock == UNLOCKED {
1667                q.rx_lock = LOCKED_UNMODIFIED;
1668            }
1669            if q.tx_lock == UNLOCKED {
1670                q.tx_lock = LOCKED_UNMODIFIED;
1671            }
1672        }
1673        self.exit_critical();
1674    }
1675
1676    /// `prvUnlockQueue`: two critical sections, one per lock counter. The
1677    /// loops inside them wake tasks that an ISR queued while the lock was
1678    /// held, and on the sim there are none.
1679    /// `prvUnlockQueue`: two critical sections, one per lock count, each
1680    /// waking one task per send or receive an interrupt made while the
1681    /// queue was locked. The yields are *missed* yields — pended, not
1682    /// taken — because a task is walking the list.
1683    fn unlock_queue(&mut self, queue: QueueHandle) -> Result<()> {
1684        self.enter_critical();
1685        {
1686            // One resolve for both fields. They were two, and a resolve
1687            // is a null test, a bounds check, a generation compare and an
1688            // `Option` unwrap -- all of it repeated to reach the same slot.
1689            // The unlock is written on the SAME lookup that read the lock,
1690            // whenever the loop below is not going to run -- which is every
1691            // call where nothing was sent while the queue was held, i.e. the
1692            // common one. It used to take a second `resolve_mut` after the
1693            // loop to store a value already known here.
1694            let (mut tx_lock, container) = match self.queues.resolve_mut(queue) {
1695                Ok(q) => {
1696                    // The container is read only when queue sets exist. With
1697                    // `USE_QUEUE_SETS` false nothing ever writes `set_container`,
1698                    // so the const makes it a known NULL and the whole branch
1699                    // below folds -- the other two queue-set sites already put
1700                    // the const FIRST and this one tested the field first.
1701                    let read = (
1702                        q.tx_lock,
1703                        if C::USE_QUEUE_SETS {
1704                            q.set_container
1705                        } else {
1706                            QueueHandle::NULL
1707                        },
1708                    );
1709                    if read.0 <= LOCKED_UNMODIFIED {
1710                        q.tx_lock = UNLOCKED;
1711                    }
1712                    read
1713                }
1714                Err(_) => (UNLOCKED, QueueHandle::NULL),
1715            };
1716            let tx_looped = tx_lock > LOCKED_UNMODIFIED;
1717            while tx_lock > LOCKED_UNMODIFIED {
1718                if C::USE_QUEUE_SETS && !container.is_null() {
1719                    if C::USE_QUEUE_SETS && self.notify_queue_set_container(queue)? {
1720                        self.missed_yield();
1721                    }
1722                    // Wrapping: the loop runs only while this is above
1723                    // `LOCKED_UNMODIFIED`, so one off it stays in range.
1724                    tx_lock = tx_lock.wrapping_sub(1);
1725                    continue;
1726                }
1727                let receivers = Self::queue_receive_list(queue);
1728                if self.lists.is_empty_of(receivers) {
1729                    break;
1730                }
1731                if self.remove_from_event_list(receivers)? {
1732                    self.missed_yield();
1733                }
1734                // Wrapping: bounded by the loop, as above.
1735                tx_lock = tx_lock.wrapping_sub(1);
1736            }
1737            if tx_looped {
1738                if let Ok(q) = self.queues.resolve_mut(queue) {
1739                    q.tx_lock = UNLOCKED;
1740                }
1741            }
1742        }
1743        self.exit_critical();
1744        self.enter_critical();
1745        {
1746            // Same trade as the tx half above.
1747            let mut rx_lock = match self.queues.resolve_mut(queue) {
1748                Ok(q) => {
1749                    let read = q.rx_lock;
1750                    if read <= LOCKED_UNMODIFIED {
1751                        q.rx_lock = UNLOCKED;
1752                    }
1753                    read
1754                }
1755                Err(_) => UNLOCKED,
1756            };
1757            let rx_looped = rx_lock > LOCKED_UNMODIFIED;
1758            while rx_lock > LOCKED_UNMODIFIED {
1759                let senders = Self::queue_send_list(queue);
1760                if self.lists.is_empty_of(senders) {
1761                    break;
1762                }
1763                if self.remove_from_event_list(senders)? {
1764                    self.missed_yield();
1765                }
1766                // Wrapping: bounded by the loop, as above.
1767                rx_lock = rx_lock.wrapping_sub(1);
1768            }
1769            if rx_looped {
1770                if let Ok(q) = self.queues.resolve_mut(queue) {
1771                    q.rx_lock = UNLOCKED;
1772                }
1773            }
1774        }
1775        self.exit_critical();
1776        Ok(())
1777    }
1778
1779    /// `vQueueWaitForMessageRestricted`: what the timer service task does
1780    /// when it has no timer to run — block on the command queue without
1781    /// suspending the scheduler.
1782    ///
1783    /// `wait_indefinitely` is the C third argument: when set the wait
1784    /// becomes `portMAX_DELAY` and the task goes to the suspended list
1785    /// rather than a delayed one. The queue locks around it are C's
1786    /// `prvLockQueue` and `prvUnlockQueue` — three critical sections, and
1787    /// therefore three sixteenths of a tick's worth of sim time.
1788    ///
1789    /// # Errors
1790    /// A list error surfaces as itself.
1791    pub fn wait_for_message_restricted(
1792        &mut self,
1793        queue: QueueHandle,
1794        ticks: u64,
1795        wait_indefinitely: bool,
1796    ) -> Result<()> {
1797        self.lock_queue(queue);
1798        let empty = self
1799            .queues
1800            .resolve(queue)
1801            .map(|q| q.waiting == 0)
1802            .unwrap_or(false);
1803        if empty {
1804            // vTaskPlaceOnEventListRestricted
1805            let current = self.current;
1806            let event = Self::event_item(current);
1807            self.lists
1808                .insert_end(Self::queue_receive_list(queue), event)?;
1809            let ticks = if wait_indefinitely {
1810                Self::MAX_DELAY
1811            } else {
1812                ticks
1813            };
1814            let wake_at = self.tick.wrapping_add(ticks) & Self::MAX_DELAY;
1815            self.trace_task(current, |task, name| Event::TaskDelayUntil {
1816                task,
1817                name,
1818                wake_at,
1819            });
1820            self.add_current_task_to_delayed_list(ticks, wait_indefinitely)?;
1821        }
1822        self.unlock_queue(queue)?;
1823        Ok(())
1824    }
1825
1826    /// `prvIsQueueEmpty`, critical section and all — it is one of the
1827    /// four the blocking path spends, and therefore a sixteenth of a tick
1828    /// every four calls.
1829    // In line at both callers (`rusty-compiler-leverage` A3): win 23, which
1830    // took this and `is_queue_empty`/`lock_queue`'s siblings together for
1831    // -48 B of flash. A two-caller body this small pays two frames for a
1832    // resolve and a critical section; `#[inline]` alone was declined.
1833    #[inline(always)]
1834    fn is_queue_empty(&mut self, queue: QueueHandle) -> bool {
1835        self.enter_critical();
1836        let empty = self
1837            .queues
1838            .resolve(queue)
1839            .map(|q| q.waiting == 0)
1840            .unwrap_or(true);
1841        self.exit_critical();
1842        empty
1843    }
1844
1845    /// `prvIsQueueFull`, likewise.
1846    fn is_queue_full(&mut self, queue: QueueHandle) -> bool {
1847        self.enter_critical();
1848        let full = self
1849            .queues
1850            .resolve(queue)
1851            .map(|q| q.waiting >= q.length)
1852            .unwrap_or(false);
1853        self.exit_critical();
1854        full
1855    }
1856
1857    /// `prvGetHighestPriorityOfWaitToReceiveList`.
1858    fn highest_waiting_priority(&self, queue: QueueHandle) -> Result<u8> {
1859        let list = Self::queue_receive_list(queue);
1860        match self.lists.head(list)? {
1861            // The event item's value is `configMAX_PRIORITIES - priority`.
1862            Some(item) => {
1863                let value = self.lists.value(item)?;
1864                let max = u64::from(C::MAX_PRIORITIES);
1865                Ok(u8::try_from(max.saturating_sub(value)).unwrap_or(0))
1866            }
1867            None => Ok(0),
1868        }
1869    }
1870}
1871
1872/// The next index in a ring of `length`.
1873///
1874/// Five instructions behind a call at six sites. `#[inline]` lets the ring
1875/// bound fold into the caller, which already knows it.
1876#[inline]
1877const fn wrap_next(index: usize, length: usize) -> usize {
1878    // `wrapping_add`, and it is the SAME function, not an approximation
1879    // of it: at `usize::MAX` saturating yields `usize::MAX`, which is
1880    // `>= length`, so the caller gets 0 -- and wrapping yields 0, which is
1881    // `< length`, so the caller gets 0 as well. Every other index agrees
1882    // without argument.
1883    let next = index.wrapping_add(1);
1884    if next >= length { 0 } else { next }
1885}
1886
1887/// The previous index in a ring of `length`.
1888#[inline]
1889const fn wrap_prev(index: usize, length: usize) -> usize {
1890    match index.checked_sub(1) {
1891        Some(prev) => prev,
1892        None => length.saturating_sub(1),
1893    }
1894}
1895
1896/// The Rust face's raw surface: see [`crate::typed`].
1897///
1898/// Every method here is one of the kernel's own calls under another name.
1899/// The one that is not — [`Raw::raw_queue_has_room`] — is the kernel
1900/// reading its own queue rather than a task asking, so it takes no
1901/// critical section and costs no sim time, which is what lets the typed
1902/// face be free.
1903impl<
1904    C: Config,
1905    P: Port,
1906    T: Trace,
1907    H,
1908    const TASKS: usize,
1909    const ITEMS: usize,
1910    const LISTS: usize,
1911    const QUEUES: usize,
1912    const SLOTS: usize,
1913    const BUFFERS: usize,
1914    const BYTES: usize,
1915    const TIMERS: usize,
1916    const GROUPS: usize,
1917    const TIMER_CMDS: usize,
1918> crate::typed::Raw
1919    for Kernel<
1920        C,
1921        P,
1922        T,
1923        H,
1924        TASKS,
1925        ITEMS,
1926        LISTS,
1927        QUEUES,
1928        SLOTS,
1929        BUFFERS,
1930        BYTES,
1931        TIMERS,
1932        GROUPS,
1933        TIMER_CMDS,
1934    >
1935where
1936    H: TickHook<Self>,
1937{
1938    fn raw_queue_create(&mut self, length: usize) -> Result<QueueHandle> {
1939        self.queue_create(length)
1940    }
1941
1942    fn raw_queue_send(&mut self, queue: QueueHandle, value: u64, ticks: u64) -> Result<Wait<()>> {
1943        self.queue_send(queue, value, ticks)
1944    }
1945
1946    fn raw_queue_receive(&mut self, queue: QueueHandle, ticks: u64) -> Result<Wait<u64>> {
1947        self.queue_receive(queue, ticks)
1948    }
1949
1950    fn raw_queue_messages_waiting(&mut self, queue: QueueHandle) -> Result<usize> {
1951        self.queue_messages_waiting(queue)
1952    }
1953
1954    fn raw_queue_has_room(&self, queue: QueueHandle) -> bool {
1955        self.queues
1956            .resolve(queue)
1957            .is_ok_and(|q| q.waiting < q.length)
1958    }
1959
1960    fn raw_in_isr(&self) -> bool {
1961        self.port.in_isr()
1962    }
1963
1964    fn raw_queue_send_from_isr(&mut self, queue: QueueHandle, value: u64) -> Result<Woken> {
1965        self.queue_send_from_isr(queue, value)
1966    }
1967
1968    fn raw_mutex_create(&mut self) -> Result<QueueHandle> {
1969        self.mutex_create()
1970    }
1971
1972    fn raw_mutex_take(&mut self, mutex: QueueHandle, ticks: u64) -> Result<Wait<()>> {
1973        self.semaphore_take(mutex, ticks)
1974    }
1975
1976    fn raw_mutex_give(&mut self, mutex: QueueHandle) -> Result<()> {
1977        self.semaphore_give(mutex).map(|_| ())
1978    }
1979}