Intrusive queues
(Milestone 14 (kernel objects from untyped) phase A.2. The mechanism behind
the repository partsfoundry/intrusive_queue, which the per-CPU run queues and migration inboxes are built on. See
design/kernel-objects-from-untyped.md, decision D1.)
The idea
An ordinary queue (VecDeque) owns storage and puts your data in it. An intrusive queue owns
nothing: the "next" pointer lives inside the thing being queued, and the queue is just a
head pointer and a tail pointer. Pushing a thread means writing its link field and the tail
pointer. Popping means reading the head and unhooking it.
Every serious kernel does scheduler queues this way (Linux list_head, seL4's TCB queues),
because of what it removes:
- Allocation. A push writes two pointers. It cannot allocate, so it cannot fail, so it is legal anywhere, including the paths where allocation is forbidden (our §9 (locking: IrqSafeMutex, plus a discipline): interrupt context). The scheduler used to pre-reserve VecDeque capacity so a push from the timer interrupt could never reallocate; that standing apology is gone, because the rule became structural.
- The lookup. The old queues held thread ids; every pop paid a table lookup to reach the thread.
An intrusive pop hands back the TCB itself. The migration path got the full benefit: draining
an inbox into a run queue is now pure pointer movement and touches no table at all, which is
why
drain_inboxneeds no scheduler lock.
One link means one queue, and that is the invariant
A thread has one next field, so it can be on at most one queue. For a scheduler this is not a
restriction; it is the state machine made physical:
| State | Where |
|---|---|
| Running | on a CPU, on no queue |
| Ready | on exactly one run queue or inbox |
| Blocked | on exactly one endpoint wait queue, or on none (a CALLer awaiting its Reply) |
| Finished | on no queue, awaiting the reaper |
The structure enforces what the states already meant. Phase A.3 moved the IPC wait queues onto
the same link, so "a thread waits on one endpoint at a time" stopped being a rule and became a
property of there being one field. The link's handoffs are strictly sequential: endpoint queue
(Blocked) to run queue (Ready, via wake, which pops first) to no queue (Running), each
transition under SCHED.
What keeps the pointers honest
The queue borrows nodes it does not own, and the borrow checker cannot see any of it. The safety is a discipline, stated once and kept:
- A queued thread is
Ready, and onlyFinishedthreads are reaped, so a queued TCB is never freed. This is the load-bearing rule, and it is whysched::thread_control_block_ptr(the one place a ThreadId becomes a pointer) documents it rather than each push site re-arguing it. - The thread table's TCB page pins the address: each thread lives at the start of one page that never moves (notes/thread-control-block.md).
- Only the queue that holds a thread touches its link, under that queue's synchronization: a run queue is single-core with interrupts masked; an inbox is behind its mutual exclusion lock.
The crate's contract, and the Unqueued token
partsfoundry/intrusive_queue states its caller's contract as three rules, and its doc comments cite them
by number:
- A node is pushed onto at most one queue, and not pushed again until popped. A push takes the
node's
Unqueuedtoken by value, and only a pop gives it back, so the compiler enforces this. - A node outlives its time on the queue. In the kernel a queued thread is
Ready, and onlyFinishedthreads are freed. - The caller serializes all access to a queue and its nodes' links, and mints each token from the
node's owning pointer, never from a reference.
&mut selfenforces it for the queue; for the links and the token's pointer it is stated atUnqueued::new.
Rule 2 fits no type available here, because the queue deliberately does not own its nodes. The
queue is safe because its callers are correct, and nothing in the crate can check that. The API
takes NonNull, so nullness is a fact of construction. That is what CodeQL's
rust/access-invalid-pointer was pointing at. The Kani harness proves the ordering logic, never
that a caller kept a queued node alive.
The token is calef's ruling C on #1842 (2026-10-08 UTC). It is neither Clone nor Copy, so a
node cannot be on two queues at once unless someone writes unsafe. Lifetime is the one obligation
it cannot carry, and Unqueued::new discharges it once, where the token is minted, rather than at
every push. It is #[repr(transparent)] over its pointer, so it costs nothing at run time: the same
register, the same layout, and Option<Unqueued<T>> is still one pointer wide. The kernel's
footprint gate rests on that. It is #[must_use] because dropping a token is safe but strands its
node: queueing the node again needs a second token, which is the unsafe the type keeps rare.
What is proved
The crate's Kani harness (script/verify) drives the real Queue with a symbolic operation
sequence: six steps, each an arbitrary push-or-pop over three nodes, checked against a
trivially-correct model. Every interleaving up to that depth at once, including the
drained-to-empty transitions where head/tail bugs live. FIFO order, no loss, no invention,
lengths agree, and no stale link is ever dereferenced (Kani checks the pointer accesses
themselves). The host tests cover the same ground concretely, plus link hygiene: a popped node
leaves with its link cleared.
The wake-before-switch-out race (found by a flake, fixed like the reaper)
Moving the wait queues (A.3) surfaced a scheduler race that predated it: the suite went from 10/10 green on the A.2 baseline to 8/10, failing in the address-space teardown test two different ways. The race:
- Thread T (core A) queues itself on an endpoint, marks itself
Blocked, releasesSCHED. T is still executing; its saved context is stale until A'sschedule()switches away. - Core B rendezvouses with T (or an interrupt signals its endpoint): pops T, wakes it, queues it on B's run queue.
- B switches into T's stale context while A is still running T's present one. Two cores in one thread, on two different ideas of its registers.
The window existed with thread-id queues too; the pointer rewire only shifted the timing enough to
observe it. The tell that it was old: the kernel had already solved the same race for death.
A Finished thread cannot be freed while its core is still switching off its stack, so §11
reaps it from its successor, after the switch (finish_switch). Being woken is the same
hazard as being freed, for the same reason, with the same fix:
on_cpu(on the thread's embeddedthread_wake_handshake::Handshake): set when a core schedules a thread in, cleared by that core's successor after the switch away.wake()findingon_cpuset does not queue the thread; it parks the wake in the handshake'swake_pending.finish_switch, running on the thread's own core with the context provably saved, completes the wake. (cpu::switched_fromgeneralizes the oldto_reap: the successor now finishes both duties, reap or wake, depending on the predecessor's state.)
Verified at the time by moving the suite back to repeated clean runs (statistics, not proof).
Since 2026-08-14 it is also searched: the on_cpu/wake_pending protocol lives in
crates/thread_wake_handshake, and loom explores every interleaving of the waker against the
switch-out. That includes a #[should_panic] reconstruction of exactly this race (the wake with the
deferral removed), which fails the model the way the flake failed the suite. That covers the
protocol's
logic under the kernel's locking discipline; the discipline itself, and the ISA-level orderings,
remain outside the model (notes/interleaving.md).
The aliasing fine print: where a token's pointer comes from
While a TCB pointer sits in a queue, other code occasionally creates &mut Thread to the same TCB
through the table (a mailbox write, the revocation sweep's iter_mut). Rust's aliasing models,
which Miri checks (Stacked Borrows, and Tree Borrows with -Zmiri-tree-borrows), decide whether
that is sound by the token's provenance, not by how the link is accessed:
- A token taken from a
&mutreborrow of the node, such asNonNull::from(get_mut(..)), dies at the owner's next&mutreborrow of the same node. The queue's next push or pop through it is undefined behavior under both models. - A token taken from the owning pointer (the one
Box::into_rawreturned, or the page pointer the thread table stores) survives those reborrows, because each reborrow also comes from that pointer, and using the token afterwards only ends the reborrow.
So Unqueued::new requires the second shape, and Threads::mint_token mints from the pointer the
table stores. The crate's test a_token_from_the_owning_pointer_survives_later_borrows
runs the thread table's sequence: store the owning pointer, mint from it, reborrow the node while
it moves on and off a queue, and retire it. Both models pass it. With the token minted from a
reborrow instead, both report undefined behavior at the next push. SCHED or a queue's own
synchronization also serializes every access, so no two accesses overlap in time. Miri never runs
the kernel itself, so the kernel's adherence rests on this argument and not on a run. The Kani harnesses are unaffected: Kani does not
model aliasing.
Where thread ids still live
Phases A.2 and A.3 moved all the queues to pointers; what still speaks generational thread ids is
the capability payloads (Reply(ThreadId)), the per-CPU current/idle/to_reap slots, and the
kernel's own bookkeeping around table lookups, all safely (see notes/generational-names.md).
That is the design doc's D2 path proceeding one structure at a time; the payloads fall last,
behind the safety mechanism the generational table already provides.
BUGS
- The two doc examples in
crates/inter_process_communication/src/rendezvous.rsstill mint their tokens fromNonNull::from(&mut x), a reference, which the provenance clause onUnqueued::newforbids. They change to&raw mutonce #3522, which is editing that file, lands.