Skip to main content

nros_platform_api/
lib.rs

1//! Platform capability sub-traits for nros.
2//!
3//! This crate exists to break the dependency cycle between
4//! `nros-platform` (which depends on every platform crate via its
5//! feature-gated `ConcretePlatform` resolver) and the platform crates
6//! themselves (which need to implement these traits on their ZSTs).
7//! It contains only trait definitions — no implementations, no
8//! dependencies — so platform crates can take a build-time dep on it
9//! without creating a cycle back through `nros-platform`.
10//!
11//! `nros-platform` re-exports everything from this crate, so downstream
12//! code that writes `use nros_platform::PlatformClock;` continues to
13//! work unchanged.
14//!
15//! Each trait covers an independent system capability. Platform
16//! implementations pick which traits to implement based on what the
17//! hardware/RTOS provides. RMW shim crates declare trait bounds for
18//! the capabilities they need.
19
20#![no_std]
21//!
22//! # Naming convention
23//!
24//! Method names drop redundant prefixes when the trait name already
25//! supplies the namespace — e.g., `PlatformTcp::open` rather than
26//! `PlatformTcp::tcp_open`. Dispatch is always through a qualified
27//! path (`<ConcretePlatform as PlatformTcp>::open(...)`), so
28//! trait-to-trait collisions (PlatformTcp::open vs PlatformUdp::open)
29//! are disambiguated at the call site without needing a prefix on the
30//! trait method itself.
31//!
32//! Three categories still keep sub-namespace prefixes internally:
33//!
34//! * `PlatformThreading` — `mutex_*`, `condvar_*`, `task_*` because the
35//!   trait bundles three independent primitive families and unprefixed
36//!   `init` / `drop` would be ambiguous *within* the trait itself.
37//! * `PlatformUdpMulticast` — `mcast_*` because these methods have
38//!   different signatures from `PlatformUdp`'s same-name methods; keeping
39//!   the prefix makes call sites that use both traits self-documenting.
40//! * The `close` method appears on both `PlatformTcp` and
41//!   `PlatformSocketHelpers` — the first is TCP teardown, the second is
42//!   zenoh-pico's generic "shutdown + close" helper. Both live unprefixed
43//!   in their respective traits; call sites disambiguate via the
44//!   qualified path.
45//!
46//! # Who implements these traits
47//!
48//! The bare-metal Rust ports (`Mps2An385Platform`,
49//! `Stm32f4Platform`) implement them, and `nros_platform_export!` exports
50//! those impls over the C platform ABI; `CffiPlatform` implements them in
51//! the other direction, over that ABI. The hosted and RTOS ports (POSIX,
52//! Zephyr, FreeRTOS, NuttX, ThreadX) are C (`nros-platform-<rtos>/src/
53//! platform.c`). Their Rust ZSTs, ~~`PosixPlatform`~~ among them, are gone,
54//! and with them the plan that would have moved each one from
55//! inherent methods onto these traits.
56
57// phase-359 W10 — the ONE Rust-side spawn helper for the task ABI this crate
58// defines. It lived in `nros-node::executor::platform_task`, private, which
59// meant the second Rust caller (`nros-cpp`'s native sched task runtime) could only
60// reach it by exposing a core crate's internals or by writing a third copy of
61// allocate-spawn-join — `nros-board-nuttx` already holds a second. A helper for
62// an ABI belongs with the ABI.
63#[cfg(feature = "alloc")]
64extern crate alloc;
65// The module is NOT `alloc`-gated; `PlatformTask` inside it is. Gating the whole
66// module put `stack_unused_bytes` — a bare `extern` query that allocates nothing
67// — behind `alloc`, so `Executor::check_stack_headroom_rule` failed to compile
68// in every no-alloc image. That is the build where stack headroom matters most,
69// and the rule was unreachable there (phase-425 sweep; the lane that catches it,
70// `check workspace-embedded`, runs in no merge-gating event).
71pub mod task;
72
73use core::ffi::{c_int, c_void};
74
75pub mod boot_config;
76pub mod wake;
77pub mod xorshift32;
78
79pub use boot_config::{
80    BOOT_SET_DOMAIN, BOOT_SET_LOCATOR, BOOT_SET_NAMESPACE, BOOT_SET_NODE_NAME, BOOT_SET_RMW,
81    BakedBootConfig, NROS_BOOT_CONFIG_MAGIC, NROS_BOOT_CONFIG_VERSION,
82};
83pub use wake::{WAKE_STORAGE_ALIGN, WAKE_STORAGE_BYTES, Wake, WakeInitError, WakeReason};
84
85// ============================================================================
86// Clock (required by all RMW backends)
87// ============================================================================
88
89/// Monotonic clock.
90///
91/// The most critical platform primitive. Must be backed by a hardware timer
92/// or OS tick — never by a software counter that only advances when polled.
93pub trait PlatformClock {
94    /// Monotonic nanoseconds since a platform-defined epoch. Never
95    /// decreases. See `<nros/platform.h>` for the full contract
96    /// (RFC-0073).
97    fn clock_ns() -> u64;
98
99    /// Granularity of [`Self::clock_ns`] in nanoseconds: the smallest
100    /// non-zero difference two successive reads can report. Non-zero,
101    /// and constant after platform init.
102    fn clock_resolution_ns() -> u64;
103
104    /// Microseconds since the UNIX epoch, or `0` when this platform has no
105    /// wall-clock source. See `<nros/platform.h>` for the full contract
106    /// (issue 0758).
107    ///
108    /// DEFAULTED to `0` deliberately. Every existing port is correct
109    /// without changing a line: none of them has an epoch source today, and
110    /// `0` is precisely the honest answer. Making this a required method
111    /// would have forced eleven ports to write `0` by hand, which is the
112    /// same information spelled eleven times plus eleven chances to write
113    /// something else.
114    ///
115    /// It is also the difference between an ABI addition that is a
116    /// no-op for ports and one that breaks every image that has not caught
117    /// up — and the C side has no such default, so a port implemented in C
118    /// DOES say `0` explicitly.
119    ///
120    /// Unlike [`Self::clock_ns`] this is not monotonic: a port that
121    /// acquires its epoch after boot jumps when it does.
122    fn epoch_us() -> u64 {
123        0
124    }
125}
126
127// ============================================================================
128// Heap allocation (zenoh-pico requires ~64 KB heap)
129// ============================================================================
130
131/// Heap memory allocation.
132pub trait PlatformAlloc {
133    /// Allocate `size` bytes. Returns null on failure.
134    fn alloc(size: usize) -> *mut c_void;
135
136    /// Reallocate a previously allocated block. Returns null on failure.
137    fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void;
138
139    /// Free a previously allocated block.
140    fn dealloc(ptr: *mut c_void);
141
142    /// Phase 230 Z5 / RFC-0034 D7 — bytes currently allocated from the
143    /// platform heap. The true unified figure where the platform owns one
144    /// kernel heap shared by the C side (`alloc`) and the Rust
145    /// `#[global_allocator]`. Default `0` = "unknown / not instrumented".
146    fn heap_used_bytes() -> usize {
147        0
148    }
149
150    /// Total managed heap size in bytes (used + free), or `0` if unknown.
151    fn heap_total_bytes() -> usize {
152        0
153    }
154}
155
156// ============================================================================
157// Fatal error
158// ============================================================================
159
160/// The image's one ending.
161///
162/// Mirrors `nros_platform_panic` in `<nros/platform.h>`. Rust's
163/// `#[panic_handler]`, a C precondition failure and a C++ terminate all arrive
164/// here, so an image has one fatal path instead of one per language.
165///
166/// The ABI could express ALLOCATION but not fatality, so each language invented
167/// its own ending and four libraries each hardcoded a different one. This is the
168/// missing half.
169pub trait PlatformPanic {
170    /// Terminate the image. Never returns.
171    ///
172    /// `msg` is a DIAGNOSTIC, not a C string: `len` bytes, no NUL required,
173    /// possibly empty, and not necessarily UTF-8 — a port forwarding to a text
174    /// sink should treat it as bytes.
175    ///
176    /// Implementors must tolerate being called from ANY context: interrupt,
177    /// scheduler locked, or before the kernel starts. That rules out anything
178    /// needing a scheduler, which is why this is not "log at Fatal, then halt".
179    ///
180    /// Implementors SHOULD emit `msg` where a human can read it first. A silent
181    /// halt is the one behaviour no RTOS in this tree chose for itself.
182    fn panic(msg: *const u8, len: usize) -> !;
183}
184
185// ============================================================================
186// Sleep / delay
187// ============================================================================
188
189/// Sleep primitives.
190///
191/// On bare-metal with smoltcp, implementations should poll the network
192/// stack during busy-wait sleep to avoid missing packets.
193pub trait PlatformSleep {
194    /// Sleep for the given number of microseconds.
195    fn sleep_us(us: usize);
196
197    /// Sleep for the given number of milliseconds.
198    fn sleep_ms(ms: usize);
199
200    /// Sleep for the given number of seconds.
201    fn sleep_s(s: usize);
202}
203
204// ============================================================================
205// Cooperative yield
206// ============================================================================
207
208/// Scheduler yield primitive.
209///
210/// Used inside `socket_wait_event` and similar "let another task make
211/// progress" points where the caller isn't actually waiting for I/O
212/// readability — the background read task already owns that — it just
213/// needs to relinquish the CPU so the real waiter can run.
214///
215/// Before this primitive existed, each backend hand-rolled its own 1-ms busy
216/// sleep (`libc::usleep(1000)`, `vTaskDelay(1)`, `tx_thread_sleep(1)`,
217/// `k_usleep(1000)`, `select(.., 1 ms)`) — all with slightly different
218/// units and no common home.
219///
220/// **ISR-safety**: on the hosted-RTOS backends (FreeRTOS / NuttX /
221/// Zephyr / ThreadX) the underlying primitives panic or error when
222/// invoked from an ISR. Don't call `yield_now()` from an interrupt
223/// handler.
224///
225/// **Bare-metal has no real yield**: there's nothing to yield *to*.
226/// The default bare-metal impl is `core::hint::spin_loop()` (a pure
227/// CPU hint: emits `YIELD` / `PAUSE` / `WFE` depending on the arch,
228/// safe everywhere). Board crates that have armed an IRQ source may
229/// opt in to deep idle (`wfi`) via a separate BoardIdle hook — not
230/// part of this trait because calling `wfi` without an IRQ source
231/// deadlocks.
232pub trait PlatformYield {
233    /// Relinquish the CPU long enough for another task / thread to run.
234    ///
235    /// Non-blocking in the sleep sense — returns as soon as the
236    /// scheduler has had an opportunity to pick a different runnable.
237    fn yield_now();
238}
239
240// ============================================================================
241// Phase 110.D — `PlatformScheduler` (per-thread OS scheduling policy)
242// ============================================================================
243
244/// Errors returned by [`PlatformScheduler`] entry points.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum SchedError {
247    /// The active platform doesn't expose this control surface
248    /// (e.g. bare-metal with no scheduler, or an RTOS without an
249    /// affinity API).
250    Unsupported,
251    /// The requested policy is valid for this platform but the
252    /// numeric arguments fall outside the platform's accepted range.
253    OutOfRange,
254    /// A platform-specific syscall / kernel call failed; check
255    /// `errno` (POSIX) or the RTOS error code for details.
256    KernelError,
257}
258
259/// Per-thread OS scheduling policy.
260///
261/// `Fifo` / `RoundRobin` / `Deadline` / `Sporadic` map to platform-
262/// native scheduling classes when available. `Platform(...)` is the
263/// escape hatch for RTOS-specific knobs (e.g. ThreadX preempt-
264/// threshold) that don't map cleanly into the portable variants.
265///
266/// User-facing API (`Executor::open_threaded`) takes the abstract
267/// [`Priority`-like](crate) values and `PlatformScheduler` translates
268/// them into platform-native numerics — direction-flipped priority
269/// (Zephyr / ThreadX low-numeric = high-priority vs POSIX / FreeRTOS
270/// high-numeric = high-priority) handled internally.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub enum SchedPolicy {
273    /// POSIX `SCHED_FIFO`. `os_pri` is the platform-native numeric
274    /// priority; out-of-range values surface `SchedError::OutOfRange`.
275    Fifo { os_pri: u8 },
276    /// POSIX `SCHED_RR` with `quantum_ms` time slice.
277    RoundRobin { os_pri: u8, quantum_ms: u32 },
278    /// Linux `SCHED_DEADLINE` (sched_setattr). All values nanoseconds.
279    Deadline {
280        runtime_ns: u64,
281        period_ns: u64,
282        deadline_ns: u64,
283    },
284    /// NuttX `SCHED_SPORADIC` server. Phase 110.E.
285    Sporadic {
286        budget_us: u32,
287        period_us: u32,
288        hi_pri: u8,
289        lo_pri: u8,
290    },
291}
292
293// Per-thread OS-scheduling control surface.
294//
295// Each platform implements as much of this trait as its kernel
296// supports. `bare-metal` returns [`SchedError::Unsupported`] from
297// every entry point — there is no scheduler to talk to.
298//
299// Phase 110.D wires this for Linux + NuttX (via POSIX) at v1; Zephyr
300// / FreeRTOS / ThreadX impls land alongside per-RTOS bring-up.
301
302// ============================================================================
303// Phase 110.E.b — `PlatformTimer` (ISR-driven periodic refill)
304// ============================================================================
305
306/// Errors returned by [`PlatformTimer`] entry points.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum TimerError {
309    /// The active platform doesn't expose a periodic-timer surface
310    /// (e.g. bare-metal without a board-side SysTickHook).
311    Unsupported,
312    /// `period_us` is below the platform's minimum timer resolution
313    /// or above its maximum representable interval.
314    OutOfRange,
315    /// A platform-specific syscall / kernel call failed; check
316    /// `errno` (POSIX) or the RTOS error code for details.
317    KernelError,
318}
319
320/// Periodic timer for ISR-driven sporadic-server budget refill.
321/// The trait factors out the per-platform timer
322/// surface so the executor (`nros-node`) can register an atomic
323/// refill callback without becoming generic over the platform —
324/// see `docs/design/0017-platform-timer.md`.
325///
326/// Default `create_periodic` returns [`TimerError::Unsupported`] so
327/// platforms without a timer surface inherit safe behavior; `destroy`
328/// is a no-op default for the same reason.
329pub trait PlatformTimer {
330    /// Opaque per-platform handle (FreeRTOS `TimerHandle_t`,
331    /// Zephyr `*mut k_timer`, ThreadX `*mut TX_TIMER`, POSIX
332    /// `timer_t`). Must be `Send + Sync + 'static` so the executor
333    /// can stash it across thread boundaries.
334    type TimerHandle: Send + Sync + 'static;
335
336    /// Register a periodic timer that fires `callback(user_data)`
337    /// every `period_us` microseconds. Returns the platform-native
338    /// handle for later destruction.
339    ///
340    /// # Safety
341    ///
342    /// `user_data` must outlive the returned handle. The callback is
343    /// invoked from a platform-defined timer context (direct ISR on
344    /// Zephyr / bare-metal, deferred via `xTimerPendFunctionCall` on
345    /// FreeRTOS, signal handler on POSIX) — bodies should be
346    /// short and use atomic ops only.
347    fn create_periodic(
348        _period_us: u32,
349        _callback: extern "C" fn(*mut c_void),
350        _user_data: *mut c_void,
351    ) -> Result<Self::TimerHandle, TimerError> {
352        Err(TimerError::Unsupported)
353    }
354
355    /// Cancel + free the timer. Idempotent on already-destroyed
356    /// handles. Must drain in-flight callback invocations before
357    /// returning so the user_data pointer is no longer accessed.
358    fn destroy(_handle: Self::TimerHandle) {}
359
360    /// Phase 110.E.b follow-up — register a one-shot timer that
361    /// fires `callback(user_data)` exactly once after `timeout_us`
362    /// microseconds. Used by per-callback runtime measurement: arm
363    /// just before dispatch with `timeout_us = budget_us`; on
364    /// callback completion call `cancel`. If the timer fires first
365    /// the callback overran its budget.
366    ///
367    /// Default returns `Unsupported` so platforms without a oneshot
368    /// surface inherit safe behavior.
369    fn create_oneshot(
370        _timeout_us: u32,
371        _callback: extern "C" fn(*mut c_void),
372        _user_data: *mut c_void,
373    ) -> Result<Self::TimerHandle, TimerError> {
374        Err(TimerError::Unsupported)
375    }
376
377    /// Phase 110.E.b follow-up — cancel a previously-armed oneshot
378    /// timer. Returns `true` when the cancellation prevented the
379    /// callback from firing, `false` when the callback already
380    /// fired (or the timer was already cancelled). Default is a
381    /// no-op returning `false`.
382    fn cancel(_handle: &mut Self::TimerHandle) -> bool {
383        false
384    }
385}
386
387pub trait PlatformScheduler {
388    /// Apply the requested policy to the calling thread.
389    ///
390    /// Default returns [`SchedError::Unsupported`] so single-core bare-
391    /// metal targets and RTOS impls without per-thread scheduling
392    /// pickup the no-op behavior automatically. Platforms with a
393    /// real scheduler override this.
394    fn set_current_thread_policy(_p: SchedPolicy) -> Result<(), SchedError> {
395        Err(SchedError::Unsupported)
396    }
397
398    /// Cooperative yield. Same semantics as
399    /// [`PlatformYield::yield_now`]; mirrored here so consumers don't
400    /// need to import both traits when only the scheduler control
401    /// surface is in scope. Default is a `core::hint::spin_loop()`.
402    fn yield_now() {
403        core::hint::spin_loop();
404    }
405
406    /// Pin the calling thread to the CPUs whose bit is set in
407    /// `_cpu_mask`. Default returns [`SchedError::Unsupported`] —
408    /// platforms with affinity APIs override.
409    fn set_affinity(_cpu_mask: u32) -> Result<(), SchedError> {
410        Err(SchedError::Unsupported)
411    }
412}
413
414// ============================================================================
415// Random number generation
416// ============================================================================
417
418/// Pseudo-random number generation.
419///
420/// A simple xorshift32 PRNG is sufficient. Seed with hardware entropy
421/// (RNG peripheral, ADC noise, wall-clock time) during platform init.
422pub trait PlatformRandom {
423    fn random_u8() -> u8;
424    fn random_u16() -> u16;
425    fn random_u32() -> u32;
426    fn random_u64() -> u64;
427
428    /// Fill buffer with random bytes.
429    fn random_fill(buf: *mut c_void, len: usize);
430}
431
432// ============================================================================
433// Wall-clock time (for logging, not timing-critical)
434// ============================================================================
435
436/// Wall-clock / system time.
437///
438/// Used for logging timestamps and `z_time_now_as_str()`.
439/// On bare-metal without an RTC, return 0.
440///
441/// ONE method for one fact, matching `nros_platform_time_now_ns` in the C ABI.
442/// It replaced `time_now_ms` + `time_since_epoch_secs` +
443/// `time_since_epoch_nanos`.
444///
445/// The old doc justified the split by zenoh-pico's FFI shape: "zpico-platform-
446/// shim forwards each of these directly to a `_z_time_*` symbol, so collapsing
447/// them into a Rust struct would require the shim to decompose the struct on
448/// every call." That argument was against a STRUCT, and it still holds — but a
449/// single `u64` is not a struct. The shim now takes one value and derives the
450/// pair with a divide and a remainder, which is both cheaper than two FFI calls
451/// and, unlike them, cannot tear across a second boundary.
452pub trait PlatformTime {
453    /// Wall-clock nanoseconds since the Unix epoch, or 0 if this platform has
454    /// no real-time clock.
455    fn time_now_ns() -> u64;
456
457    /// What [`PlatformTime::time_now_ns`] means right now, the C ABI's
458    /// `nros_platform_wall_clock_state`. REQUIRED, with no default: a port
459    /// that cannot say must not be answered for.
460    fn wall_clock_state() -> WallClockState;
461}
462
463/// `nros_wall_clock_state_t`: whether the wall clock is synced, which source
464/// answers (`WALL_CLOCK_SOURCE_*`), and how many times that source changed
465/// since boot.
466#[repr(C)]
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub struct WallClockState {
469    /// `true`: [`PlatformTime::time_now_ns`] answers real UNIX time.
470    pub synced: bool,
471    /// One of `WALL_CLOCK_SOURCE_*`.
472    pub source: u8,
473    /// Source changes since boot.
474    pub steps: u32,
475}
476
477// Layout of the C struct `{ bool; uint8_t; uint32_t; }`.
478const _: () = {
479    assert!(core::mem::size_of::<WallClockState>() == 8);
480    assert!(core::mem::offset_of!(WallClockState, source) == 1);
481    assert!(core::mem::offset_of!(WallClockState, steps) == 4);
482};
483
484/// `NROS_WALL_CLOCK_SOURCE_PLATFORM`: the port's own clock.
485pub const WALL_CLOCK_SOURCE_PLATFORM: u8 = 0;
486/// `NROS_WALL_CLOCK_SOURCE_SNTP`.
487pub const WALL_CLOCK_SOURCE_SNTP: u8 = 1;
488/// `NROS_WALL_CLOCK_SOURCE_ZENOH_HLC`.
489pub const WALL_CLOCK_SOURCE_ZENOH_HLC: u8 = 2;
490/// `NROS_WALL_CLOCK_SOURCE_BOARD`.
491pub const WALL_CLOCK_SOURCE_BOARD: u8 = 3;
492
493impl WallClockState {
494    /// The answer of a port with no wall clock: unsynced, its own clock,
495    /// never stepped.
496    pub const UNSYNCED_PLATFORM: Self = Self {
497        synced: false,
498        source: WALL_CLOCK_SOURCE_PLATFORM,
499        steps: 0,
500    };
501}
502
503// ============================================================================
504// Threading (multi-threaded platforms only)
505// ============================================================================
506//
507// Handle types are opaque `*mut c_void` to match the shape zenoh-pico
508// passes across the FFI boundary. The original draft had typed wrappers
509// (~~`TaskHandle`~~, ~~`MutexHandle`~~, ...) but every shipped platform used
510// `*mut c_void` internally and the shim never materialised the typed
511// forms — keeping them in the trait would have required a pointless
512// cast at every impl site. (F4.1 / F4.5 decision, 2026-04-24.)
513//
514// Mutex / condvar / task method names keep their sub-namespace prefix
515// (`mutex_*`, `condvar_*`, `task_*`) because the trait bundles three
516// independent primitive families and unprefixed `init` / `drop` would
517// be ambiguous *within* the trait itself.
518
519/// Threading primitives: tasks, mutexes, and condition variables.
520///
521/// # Threading
522///
523/// Mutex / condvar operations must be safe under concurrent callers.
524/// **Recursive mutex (`mutex_rec_*`) must support same-thread
525/// re-entrancy** — zenoh-pico relies on this; a non-recursive mutex
526/// backing `mutex_rec_*` deadlocks under load.
527///
528/// # ISR-safety
529///
530/// **None of these methods are ISR-safe** on hosted RTOSes
531/// (FreeRTOS / NuttX / Zephyr / ThreadX) — the underlying primitives
532/// panic or error when invoked from an ISR. Only `core::hint::spin_loop()`
533/// in [`PlatformYield::yield_now`] is.
534///
535/// For single-threaded platforms (bare-metal), all operations should
536/// be no-ops returning `0`, except [`task_init`](Self::task_init)
537/// which should return `-1`.
538pub trait PlatformThreading {
539    /// Smallest number of bytes ever left unused on the CALLING task's
540    /// stack, or `0` if this platform does not instrument it.
541    ///
542    /// Defaulted so every existing impl keeps compiling: a port that says
543    /// nothing reports `0`, which the ABI documents as "not instrumented"
544    /// rather than "no headroom left".
545    fn task_stack_unused_bytes() -> usize {
546        0
547    }
548
549    /// [`task_stack_unused_bytes`](Self::task_stack_unused_bytes), capped at
550    /// `limit`, reading at most `limit` bytes of the stack (phase-436 E5).
551    ///
552    /// The default is the full query, capped, which is right for a port
553    /// whose measurement is already cheap or absent. A port that SCANS for
554    /// paint overrides it to read only the `limit` bytes at the deep end; see
555    /// `nros_platform_task_stack_unused_bytes_upto` in `nros/platform.h`.
556    fn task_stack_unused_bytes_upto(limit: usize) -> usize {
557        Self::task_stack_unused_bytes().min(limit)
558    }
559    // -- Tasks --
560
561    /// Spawn a new task. `task` is opaque caller-provided storage;
562    /// `attr` carries scheduling hints (priority, stack size) or
563    /// `null` for defaults; `entry` is the task entry point; `arg`
564    /// is forwarded to `entry`. Returns `0` on success, non-zero
565    /// on failure.
566    fn task_init(
567        task: *mut c_void,
568        attr: *mut c_void,
569        entry: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
570        arg: *mut c_void,
571    ) -> i8;
572
573    /// Block until `task` exits. Cleans up the task storage on
574    /// success.
575    fn task_join(task: *mut c_void) -> i8;
576    /// Mark `task` as detached — its storage is reclaimed on exit
577    /// without a join.
578    fn task_detach(task: *mut c_void) -> i8;
579    /// Request `task` to terminate at the next cancellation point.
580    /// Cooperative.
581    fn task_cancel(task: *mut c_void) -> i8;
582    /// Terminate the calling task immediately. Does not return.
583    fn task_exit();
584    /// Free the task storage allocated by `task_init`.
585    fn task_free(task: *mut *mut c_void);
586
587    // -- Mutex --
588
589    /// Initialise a non-recursive mutex in caller-provided storage.
590    fn mutex_init(m: *mut c_void) -> i8;
591    /// Tear down a non-recursive mutex.
592    fn mutex_drop(m: *mut c_void) -> i8;
593    /// Lock; block if held.
594    fn mutex_lock(m: *mut c_void) -> i8;
595    /// Try to lock; non-zero return immediately if held.
596    fn mutex_try_lock(m: *mut c_void) -> i8;
597    /// Unlock; only the owning thread may call this.
598    fn mutex_unlock(m: *mut c_void) -> i8;
599
600    // -- Recursive mutex --
601
602    /// Initialise a *recursive* mutex (same-thread re-entrancy
603    /// permitted). Required by zenoh-pico.
604    fn mutex_rec_init(m: *mut c_void) -> i8;
605    /// Tear down a recursive mutex.
606    fn mutex_rec_drop(m: *mut c_void) -> i8;
607    /// Lock; re-entry from the owning thread must succeed.
608    fn mutex_rec_lock(m: *mut c_void) -> i8;
609    /// Try to lock; same re-entry semantics as `mutex_rec_lock`.
610    fn mutex_rec_try_lock(m: *mut c_void) -> i8;
611    /// Unlock; releases when the lock count returns to zero.
612    fn mutex_rec_unlock(m: *mut c_void) -> i8;
613
614    // -- Condition variables --
615
616    /// Initialise a condition variable in caller-provided storage.
617    fn condvar_init(cv: *mut c_void) -> i8;
618    /// Tear down a condition variable.
619    fn condvar_drop(cv: *mut c_void) -> i8;
620    /// Wake one waiter on the condition variable.
621    fn condvar_signal(cv: *mut c_void) -> i8;
622    /// Wake all waiters on the condition variable.
623    fn condvar_signal_all(cv: *mut c_void) -> i8;
624    /// Phase 124.B.7.a — ISR-safe variant of [`Self::condvar_signal`].
625    /// Callable from interrupt / signal-handler context. Backends
626    /// implement via async-signal-safe primitives (POSIX: `pipe`
627    /// write forwarded by a worker thread — Linux may use `eventfd`,
628    /// which is a Linux syscall and not POSIX; RTOS:
629    /// `xSemaphoreGiveFromISR`, `tx_event_flags_set` from ISR,
630    /// `k_sem_give` from ISR). Returns non-zero when the backend
631    /// has no ISR-safe path — caller can fall back to
632    /// `condvar_signal` (with the obvious latency cost).
633    ///
634    /// Default body: forward to `condvar_signal`. POSIX and other
635    /// backends override to use their async-signal-safe primitive.
636    fn condvar_signal_from_isr(cv: *mut c_void) -> i8 {
637        Self::condvar_signal(cv)
638    }
639    /// Atomically release `m` and block on `cv` until signalled or until
640    /// the absolute monotonic deadline `abstime` (milliseconds since the
641    /// [`PlatformClock::clock_ns`] epoch); the mutex is re-acquired before
642    /// this returns. Returns 0 when signalled, 1 on timeout and -1 on error
643    /// (issue 1906). The remaining time rounds UP to the port's tick.
644    ///
645    /// The ONLY condvar wait: the unbounded ~~`condvar_wait`~~ was removed from
646    /// the platform ABI (issue 1196, phase-436 D2). A caller whose contract
647    /// is unbounded loops over bounded waits, re-testing its predicate.
648    fn condvar_wait_until(cv: *mut c_void, m: *mut c_void, abstime: u64) -> i8;
649
650    // -- Wake primitive (Phase 130) --
651    //
652    // Binary-semaphore-shaped primitive for the executor's wake_flag
653    // / spin_once cv-wait pair. Default bodies return "unsupported"
654    // (`-1`, size 0) so existing single-thread bare-metal platforms
655    // don't need to override; platforms that want event-driven wake
656    // (POSIX, Zephyr, FreeRTOS, NuttX, ThreadX) override with their
657    // native binary semaphore.
658
659    /// Initialise a binary-semaphore-shaped wake primitive in
660    /// caller-provided storage. See `<nros/platform.h>` for the
661    /// per-platform backing primitive (POSIX `sem_t`, Zephyr
662    /// `k_sem`, FreeRTOS `xSemaphoreBinary`, …). Default returns
663    /// `-1` (unsupported).
664    fn wake_init(_w: *mut c_void) -> i8 {
665        -1
666    }
667    /// Tear down a wake primitive. Default returns `-1`
668    /// (unsupported).
669    fn wake_drop(_w: *mut c_void) -> i8 {
670        -1
671    }
672    /// Block until signaled or `timeout_ms` elapses. Returns `0` on
673    /// signal, `1` on timeout, `-1` on error. Default returns `-1`
674    /// (unsupported).
675    fn wake_wait_ms(_w: *mut c_void, _timeout_ms: u32) -> i8 {
676        -1
677    }
678    /// Wake one waiter. Idempotent — a signal pending when another
679    /// arrives is coalesced (the primitive stays at value 1).
680    /// Default returns `-1` (unsupported).
681    fn wake_signal(_w: *mut c_void) -> i8 {
682        -1
683    }
684    /// The signal an interrupt handler may call (on POSIX, a signal
685    /// handler): only interrupt-safe (async-signal-safe) calls, bounded and
686    /// non-blocking. Returns `-1` when the backend has no such path. A
687    /// caller in an interrupt must NOT then fall back to
688    /// [`wake_signal`](Self::wake_signal): on FreeRTOS that is
689    /// `xSemaphoreGive`, which corrupts the scheduler from an ISR. The wake
690    /// is then seen at the waiter's own deadline. Issue 2696.
691    ///
692    /// Default `-1`: a port states its interrupt path, it never inherits the
693    /// thread one.
694    fn wake_signal_from_isr(_w: *mut c_void) -> i8 {
695        -1
696    }
697    /// phase-436 W7 — OPTIONAL microsecond park.
698    ///
699    /// `wake_wait_ms` is the required primitive and floors every wait at a
700    /// millisecond through its own signature; this is the same wait without
701    /// that floor, for kernels whose timeout type is finer (issue 1242).
702    ///
703    /// `w` MUST be the executor's own wake object: the backend's listener
704    /// signals that one, and a park on anything else cannot be broken by data
705    /// arriving.
706    ///
707    /// Default `-1` — "cannot park", which leaves the executor on the
708    /// millisecond path it already had. A port that can do better overrides.
709    fn wake_park_until_us(_w: *mut c_void, _deadline_us: u64) -> i8 {
710        -1
711    }
712    /// The finest park `wake_park_until_us` can express, in microseconds.
713    ///
714    /// Default `0` — "no finer park offered". An RTOS tick is a coarser limit
715    /// than the ABI signature (ThreadX ticks at 100 Hz) and a timespec
716    /// primitive a finer one, so only the port can answer (issue 1242).
717    fn wake_park_granularity_us() -> u64 {
718        0
719    }
720    /// phase-521 W3 (RFC-0113 D3) — park on the wake object and on OS
721    /// handles: the same park as [`wake_park_until_us`](Self::wake_park_until_us),
722    /// ended also when one of `n` handles at `handles` becomes readable.
723    ///
724    /// Default `-1` — "this port cannot wait on OS handles", which is the
725    /// honest answer on every port without file descriptors. The executor then
726    /// keeps the wait it had.
727    fn wake_park_handles_us(
728        _w: *mut c_void,
729        _handles: *const i32,
730        _n: usize,
731        _deadline_us: u64,
732    ) -> i8 {
733        -1
734    }
735    /// Caller-storage size requirement (bytes). Default `0` —
736    /// signals "no wake primitive available". May be called before
737    /// `wake_init`.
738    fn wake_storage_size() -> usize {
739        0
740    }
741    /// Caller-storage alignment requirement (bytes). Default `1`.
742    fn wake_storage_align() -> usize {
743        1
744    }
745    /// Caller-storage size requirement (bytes) for a task handle.
746    ///
747    /// phase-359 W10 added these probes to `platform.h` and to the C ports but
748    /// not to this trait or the export macro, so `check-platform-abi-mirror`
749    /// saw a header symbol with no Rust emission. Same contract as the wake
750    /// pair above: default `0` means "this platform cannot start a task", which
751    /// is the honest answer for a port whose `task_init` always fails, and it
752    /// is safe to call before `task_init`.
753    fn task_storage_size() -> usize {
754        0
755    }
756    /// Caller-storage alignment requirement (bytes) for a task handle.
757    /// Default `1`.
758    fn task_storage_align() -> usize {
759        1
760    }
761    /// Caller-storage size requirement (bytes) for a plain mutex.
762    ///
763    /// phase-364 W2 declared the lock family's probes in `platform.h` without
764    /// the trait or macro halves — the same shape phase-359 W10 left for
765    /// `task`, one commit later. Defaults match the pair above: `0` size means
766    /// "this platform offers no such primitive", `1` alignment is the
767    /// no-constraint answer, and both are safe to call before any `*_init`.
768    fn mutex_storage_size() -> usize {
769        0
770    }
771    /// Caller-storage alignment requirement (bytes) for a plain mutex.
772    fn mutex_storage_align() -> usize {
773        1
774    }
775    /// Caller-storage size requirement (bytes) for a RECURSIVE mutex.
776    fn mutex_rec_storage_size() -> usize {
777        0
778    }
779    /// Caller-storage alignment requirement (bytes) for a recursive mutex.
780    fn mutex_rec_storage_align() -> usize {
781        1
782    }
783    /// Caller-storage size requirement (bytes) for a condition variable.
784    fn condvar_storage_size() -> usize {
785        0
786    }
787    /// Caller-storage alignment requirement (bytes) for a condition variable.
788    fn condvar_storage_align() -> usize {
789        1
790    }
791}
792
793/// Network poll callback for bare-metal platforms using smoltcp.
794///
795/// Not required for platforms with OS-level networking (POSIX, Zephyr, NuttX).
796///
797/// **Dispatch model**: bare-metal smoltcp platforms route this hook to
798/// `SmoltcpBridge::poll_network()` so CFFI callers, RMW shims, and direct
799/// platform users all share one network pump.
800pub trait PlatformNetworkPoll {
801    /// Poll the network stack to process pending I/O.
802    ///
803    /// Default no-op — platforms with OS-level networking don't need a
804    /// pump (kernel TCP/IP stack runs in the background). Bare-metal
805    /// smoltcp providers override this.
806    fn network_poll() {}
807}
808
809/// Global mutual exclusion against preemption + ISR delivery.
810///
811/// Backs the Rust `critical_section::Impl` registration used by
812/// DDS, nros-rmw-{xrce,zenoh}, and any other no_std consumer of
813/// `critical_section::with()`. The token returned by `acquire` is
814/// passed back to `release`; it holds whatever bookkeeping the
815/// platform needs to restore the prior posture (Cortex-M PRIMASK bit,
816/// Cortex-R CPSR I-bit, RISC-V `mstatus.MIE` snapshot, pthread
817/// recursion depth, etc.) and is opaque to callers.
818///
819/// Reentrant by contract: nested `acquire` / `release` pairs must
820/// stack — the platform impl is responsible for nesting (PRIMASK
821/// already stacks; pthread side uses a recursive mutex).
822pub trait PlatformCriticalSection {
823    /// Enter a critical section. Returns an opaque token to pass to
824    /// [`Self::release`].
825    fn acquire() -> u32;
826
827    /// Leave a critical section, restoring the posture captured at
828    /// [`Self::acquire`].
829    fn release(token: u32);
830}
831
832// ============================================================================
833// Networking — TCP
834// ============================================================================
835
836/// What a socket read returns on error (`NROS_PLATFORM_NET_SOCKET_ERROR`).
837pub const NET_SOCKET_ERROR: usize = usize::MAX;
838
839// Issue 2779.
840/// What a TCP read returns when the peer closed the stream
841/// (`NROS_PLATFORM_NET_SOCKET_EOF`): distinct from [`NET_SOCKET_ERROR`] and
842/// from 0, which means "nothing read yet". A port returns it only when it knows
843/// the peer closed; zenoh-pico then closes the session and reconnects, where a
844/// 0 would leave it polling a dead socket forever.
845pub const NET_SOCKET_EOF: usize = usize::MAX - 1;
846
847/// TCP networking.
848///
849/// Socket and endpoint parameters are opaque `*mut c_void` pointers to
850/// platform-specific types (`_z_sys_net_socket_t`, `_z_sys_net_endpoint_t`).
851/// The shim provides correctly-sized `#[repr(C)]` wrappers whose sizes are
852/// auto-detected from C headers at build time.
853///
854/// Read functions return `usize::MAX` on error. Send returns `usize::MAX` on error.
855///
856/// Method names are unprefixed — the trait already namespaces them. Shims
857/// dispatch via `<ConcretePlatform as PlatformTcp>::open(...)` etc.
858pub trait PlatformTcp {
859    /// Resolve address + port strings into an endpoint handle.
860    fn create_endpoint(ep: *mut c_void, address: *const u8, port: *const u8) -> i8;
861    /// Free endpoint resources.
862    fn free_endpoint(ep: *mut c_void);
863    /// Open a TCP client connection. `endpoint` is by-value (opaque bytes on stack).
864    fn open(sock: *mut c_void, endpoint: *const c_void, timeout_ms: u32) -> i8;
865    /// [`Self::open`] whose connect gives up after `connect_timeout_ms`
866    /// (`nros_platform_tcp_open_within`, issue 2438). Negative: no bound, the
867    /// same as [`Self::open`]. Required, not defaulted: a stack that cannot
868    /// bound its connect says so in its own implementation.
869    fn open_within(
870        sock: *mut c_void,
871        endpoint: *const c_void,
872        timeout_ms: u32,
873        connect_timeout_ms: i32,
874    ) -> i8;
875    /// Open a TCP listening socket.
876    fn listen(sock: *mut c_void, endpoint: *const c_void) -> i8;
877    /// Close a TCP socket.
878    fn close(sock: *mut c_void);
879    /// Read up to `len` bytes. Returns bytes read (0: nothing yet),
880    /// [`NET_SOCKET_EOF`] when the peer closed the stream, or
881    /// [`NET_SOCKET_ERROR`] on error.
882    fn read(sock: *const c_void, buf: *mut u8, len: usize) -> usize;
883    /// Read exactly `len` bytes. Returns `len` on success, [`NET_SOCKET_EOF`]
884    /// when the peer closed the stream first, [`NET_SOCKET_ERROR`] on error.
885    fn read_exact(sock: *const c_void, buf: *mut u8, len: usize) -> usize;
886    /// Send up to `len` bytes, waiting at most about the socket's timeout
887    /// (the `timeout_ms` it was opened with) for the stack to take them.
888    /// Returns the bytes taken — possibly fewer than `len`, and `0` when none
889    /// were taken in that time — or `usize::MAX` when the connection is
890    /// broken. Never waits for a peer that stopped reading (issue 2389); the
891    /// caller loops and owns the stall bound (`nros_platform_tcp_send`).
892    fn send(sock: *const c_void, buf: *const u8, len: usize) -> usize;
893
894    /// phase-521 W6 (RFC-0113 D4) — install (`Some`) or remove (`None`) the
895    /// connected socket's receive notification, called from the stack's own
896    /// context each time data is queued, so it must only signal.
897    ///
898    /// Default `-1`: this stack has no such hook.
899    fn set_rx_notify(
900        _sock: *const c_void,
901        _notify: Option<unsafe extern "C" fn(*mut c_void)>,
902        _ctx: *mut c_void,
903    ) -> i8 {
904        -1
905    }
906}
907
908// ============================================================================
909// Networking — UDP unicast
910// ============================================================================
911
912/// UDP unicast networking.
913pub trait PlatformUdp {
914    fn create_endpoint(ep: *mut c_void, address: *const u8, port: *const u8) -> i8;
915    fn free_endpoint(ep: *mut c_void);
916    fn open(sock: *mut c_void, endpoint: *const c_void, timeout_ms: u32) -> i8;
917    fn close(sock: *mut c_void);
918    fn read(sock: *const c_void, buf: *mut u8, len: usize) -> usize;
919    fn read_exact(sock: *const c_void, buf: *mut u8, len: usize) -> usize;
920    fn send(sock: *const c_void, buf: *const u8, len: usize, endpoint: *const c_void) -> usize;
921    /// Set the receive timeout on a UDP socket (milliseconds).
922    /// 0 means block indefinitely (no timeout).
923    fn set_recv_timeout(sock: *const c_void, timeout_ms: u32);
924
925    /// phase-521 W4 (RFC-0113 D4) — the OS handle that becomes readable when
926    /// a datagram arrives: a file descriptor on POSIX and NuttX.
927    ///
928    /// Default `-1`: this stack has no such handle, and its sessions report
929    /// readiness as a Notify instead.
930    fn readiness_handle(_sock: *const c_void) -> i32 {
931        -1
932    }
933
934    /// phase-521 W4 (RFC-0113 D4) — install (`Some`) or remove (`None`) the
935    /// socket's receive notification, called from the stack's own context
936    /// each time a datagram is queued, so it must only signal.
937    ///
938    /// Default `-1`: this stack has no such hook.
939    fn set_rx_notify(
940        _sock: *const c_void,
941        _notify: Option<unsafe extern "C" fn(*mut c_void)>,
942        _ctx: *mut c_void,
943    ) -> i8 {
944        -1
945    }
946
947    /// Open a UDP socket in listen (server) mode, bound to the given
948    /// endpoint. Returns 0 on success, negative on failure.
949    ///
950    /// Optional — the default returns `-1`, which the shim forwards to
951    /// `_z_listen_udp_unicast` as "not implemented". Platforms that
952    /// need UDP server sockets (e.g. for running an XRCE-DDS agent
953    /// locally) should override this. Once Phase 84.F4 lands (the
954    /// "platform traits become a real contract" refactor), the shim
955    /// will dispatch through this trait method automatically.
956    fn listen(_sock: *mut c_void, _endpoint: *const c_void, _timeout_ms: u32) -> i8 {
957        -1
958    }
959}
960
961// ============================================================================
962// Networking — socket helpers
963// ============================================================================
964
965/// Socket helper operations called by zenoh-pico's transport layer.
966///
967/// Unprefixed method names: dispatch via
968/// `<ConcretePlatform as PlatformSocketHelpers>::set_non_blocking(...)`.
969/// Note that the `close` method here is the socket-layer close (shutdown +
970/// close) used by zenoh-pico's generic helpers; `PlatformTcp::close` is the
971/// TCP-specific close. Both exist because zenoh-pico's C surface has both.
972pub trait PlatformSocketHelpers {
973    /// Set socket to non-blocking mode.
974    fn set_non_blocking(sock: *const c_void) -> i8;
975    /// Accept a pending connection.
976    fn accept(sock_in: *const c_void, sock_out: *mut c_void) -> i8;
977    /// Close a socket (shutdown + close).
978    fn close(sock: *mut c_void);
979    /// Wait for socket events (multi-threaded platforms).
980    fn wait_event(peers: *mut c_void, mutex: *mut c_void) -> i8;
981}
982
983// ============================================================================
984// libc stubs (bare-metal only)
985// ============================================================================
986
987/// Standard C library functions needed by zenoh-pico on bare-metal targets.
988///
989/// Platforms with a C runtime (RTOS, POSIX) do NOT need to implement this.
990///
991/// # Dispatch model
992///
993/// This trait is **documentary only** — it is NOT dispatched through by
994/// `zpico-platform-shim` or `xrce-platform-shim`. The C libraries resolve
995/// these symbols (`strlen`, `memcpy`, `errno`, ...) at link time directly
996/// from `#[unsafe(no_mangle)] extern "C" fn` definitions in
997/// `nros-baremetal-common`, which bare-metal platform crates pull in
998/// via the `libc-stubs` feature:
999///
1000/// ```text
1001///   nros-baremetal-common = { ..., features = ["libc-stubs"] }
1002/// ```
1003///
1004/// The trait is retained in this API surface so that a future shim
1005/// refactor could route libc through typed Rust methods without
1006/// changing consumers. Today, implementing `PlatformLibc` on a platform
1007/// ZST would be pure documentation; the actual contract — "the linker
1008/// can resolve `strlen` etc." — is enforced at link time, not at
1009/// compile time. No platform crate implements this trait in the
1010/// current tree.
1011pub trait PlatformLibc {
1012    fn strlen(s: *const u8) -> usize;
1013    fn strcmp(s1: *const u8, s2: *const u8) -> c_int;
1014    fn strncmp(s1: *const u8, s2: *const u8, n: usize) -> c_int;
1015    fn strchr(s: *const u8, c: c_int) -> *mut u8;
1016    fn strncpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
1017    fn memcpy(dest: *mut c_void, src: *const c_void, n: usize) -> *mut c_void;
1018    fn memmove(dest: *mut c_void, src: *const c_void, n: usize) -> *mut c_void;
1019    fn memset(dest: *mut c_void, c: c_int, n: usize) -> *mut c_void;
1020    fn memcmp(s1: *const c_void, s2: *const c_void, n: usize) -> c_int;
1021    fn memchr(s: *const c_void, c: c_int, n: usize) -> *mut c_void;
1022    fn strtoul(nptr: *const u8, endptr: *mut *mut u8, base: c_int) -> core::ffi::c_ulong;
1023    fn errno_ptr() -> *mut c_int;
1024}
1025
1026// ============================================================================
1027// Logging — Phase 88 leveled log delivery
1028// ============================================================================
1029
1030/// Per-platform leveled log delivery.
1031///
1032/// Matches the platform-ABI pattern: the portable
1033/// facade (`nros-log`) formats messages into a fixed buffer; each
1034/// `nros-platform-<rtos>` carries the actual delivery (stderr,
1035/// `printk`, `esp_log_write`, `syslog`, board-registered UART writer,
1036/// etc.).
1037///
1038/// `severity` is the `u8` discriminant of `nros_log::Severity`
1039/// (0 = Trace .. 5 = Fatal). Implementors should map onto the
1040/// platform's nearest native level.
1041///
1042/// `name` is the logger name (UTF-8, NOT null-terminated, may be
1043/// empty); `message` is the already-formatted body (UTF-8, NOT
1044/// null-terminated). Delivery is infallible from the caller's POV;
1045/// platforms that fill an internal buffer (RTT, syslog) silently
1046/// drop on overflow.
1047///
1048/// Thread / ISR safety is per-platform. The ABI itself is synchronous
1049/// and the caller-side facade carries a recursion guard so a sink
1050/// that triggers `log()` from inside `write` is short-circuited.
1051pub trait PlatformLog {
1052    /// Deliver one record. Severity is a stable `u8` matching
1053    /// `nros_log::Severity::as_u8()`.
1054    fn write(severity: u8, name: &[u8], message: &[u8]);
1055
1056    /// Best-effort drain of any internal buffer. Default = no-op.
1057    fn flush() {}
1058}
1059
1060// ============================================================================
1061// Networking — UDP multicast
1062// ============================================================================
1063
1064/// UDP multicast networking (used for zenoh scouting on desktop platforms).
1065pub trait PlatformUdpMulticast {
1066    fn mcast_open(
1067        sock: *mut c_void,
1068        endpoint: *const c_void,
1069        lep: *mut c_void,
1070        timeout_ms: u32,
1071        iface: *const u8,
1072    ) -> i8;
1073    fn mcast_listen(
1074        sock: *mut c_void,
1075        endpoint: *const c_void,
1076        timeout_ms: u32,
1077        iface: *const u8,
1078        join: *const u8,
1079    ) -> i8;
1080    fn mcast_close(
1081        sockrecv: *mut c_void,
1082        socksend: *mut c_void,
1083        rep: *const c_void,
1084        lep: *const c_void,
1085    );
1086    fn mcast_read(
1087        sock: *const c_void,
1088        buf: *mut u8,
1089        len: usize,
1090        lep: *const c_void,
1091        addr: *mut c_void,
1092    ) -> usize;
1093    fn mcast_read_exact(
1094        sock: *const c_void,
1095        buf: *mut u8,
1096        len: usize,
1097        lep: *const c_void,
1098        addr: *mut c_void,
1099    ) -> usize;
1100    fn mcast_send(
1101        sock: *const c_void,
1102        buf: *const u8,
1103        len: usize,
1104        endpoint: *const c_void,
1105    ) -> usize;
1106}
1107
1108// ============================================================================
1109// Inter-VM / mailbox transport (NVIDIA IVC and similar)
1110// ============================================================================
1111
1112/// Inter-processor mailbox transport, modelled after NVIDIA Tegra IVC.
1113///
1114/// IVC (Inter-VM Communication on Tegra; in practice CCPLEX↔SPE on AGX
1115/// Orin) is a header-prefixed lock-free SPSC ring in shared DRAM, paired
1116/// with a hardware doorbell for wake. One channel is one peer — there
1117/// is no discovery, naming, QoS, or fanout — which is why it's a *link*
1118/// transport (peer to TCP/UDP/Serial/RawEth inside zenoh-pico) rather
1119/// than a new RMW backend.
1120///
1121/// Channel handles are opaque `*mut c_void` to match the shape zenoh-pico
1122/// passes across its FFI boundary. The driver crate (`nvidia-ivc`)
1123/// translates between this opaque handle and either NVIDIA's FSP
1124/// `tegra_ivc_*` API (`fsp` feature) or a Unix-socket pair
1125/// (`unix-mock` feature, host dev + CI).
1126///
1127/// **Zero-copy contract**. NVIDIA's FSP IVC API is
1128/// fundamentally a "borrow ring slot, fill, commit / release"
1129/// pattern. Both backends mirror that here so consumers don't branch
1130/// on backend:
1131///
1132/// - [`Self::rx_get`] returns a pointer into the channel's RX slot
1133///   (and writes the frame length to `*len_out`); [`Self::rx_release`]
1134///   advances the producer-visible cursor. Returns null +
1135///   `*len_out = 0` if the ring is empty.
1136/// - [`Self::tx_get`] returns a writable pointer to the next free TX
1137///   slot (and writes the slot capacity to `*cap_out`);
1138///   [`Self::tx_commit`] makes the slot visible to the peer (and
1139///   rings the per-frame doorbell on FSP — see `notify` for batching).
1140///   [`Self::tx_abandon`] frees the slot without sending. Returns
1141///   null + `*cap_out = 0` if the ring is full.
1142///
1143/// Single outstanding RX slot and single outstanding TX slot per
1144/// channel — borrow, finish, repeat. Multi-frame batching is the
1145/// caller's job (loop `tx_get` / fill / `tx_commit`, then one
1146/// `notify`).
1147///
1148/// `frame_size` is the fixed per-channel frame size negotiated at
1149/// carveout setup (typical NVIDIA IVC: 64 bytes per frame, 16 frames
1150/// per channel). The link layer uses it to pick its reassembly buffer.
1151pub trait PlatformIvc {
1152    /// Resolve a channel ID into an opaque handle. Returns null on
1153    /// failure. The numeric ID matches the NVIDIA channel index
1154    /// (`channel 2 = aon_echo`).
1155    fn channel_get(id: u32) -> *mut c_void;
1156
1157    /// Fixed frame size negotiated for this channel, in bytes.
1158    fn frame_size(ch: *mut c_void) -> u32;
1159
1160    /// Borrow the next-available RX frame. Writes the frame length to
1161    /// `*len_out` and returns a pointer into the ring. Returns null +
1162    /// `*len_out = 0` if no frame is available.
1163    fn rx_get(ch: *mut c_void, len_out: *mut usize) -> *const u8;
1164
1165    /// Release the most recently `rx_get`'d frame back to the
1166    /// producer. Pair 1:1 with `rx_get` calls that returned non-null.
1167    fn rx_release(ch: *mut c_void);
1168
1169    /// Borrow the next free TX slot. Writes the slot capacity to
1170    /// `*cap_out` and returns a writable pointer. Returns null +
1171    /// `*cap_out = 0` if the ring is full.
1172    fn tx_get(ch: *mut c_void, cap_out: *mut usize) -> *mut u8;
1173
1174    /// Commit `len` bytes from the most recently `tx_get`'d slot.
1175    /// Slot is then visible to the peer; per-frame doorbell may also
1176    /// fire on FSP. Pair 1:1 with `tx_get` calls that returned
1177    /// non-null.
1178    fn tx_commit(ch: *mut c_void, len: usize);
1179
1180    /// Abandon the most recently `tx_get`'d slot without sending.
1181    /// Pair 1:1 with `tx_get` calls that returned non-null.
1182    fn tx_abandon(ch: *mut c_void);
1183
1184    /// Ring the doorbell. On FSP this is redundant (commit/release
1185    /// already invoke `ch->notify_remote`); on unix-mock it's a no-op
1186    /// (SOCK_DGRAM wakes the peer naturally). Provided for symmetry
1187    /// so callers can batch-commit then notify once.
1188    fn notify(ch: *mut c_void);
1189}
1190
1191// ============================================================================
1192// Serial (UART / PTY)
1193// ============================================================================
1194
1195/// Serial (byte-stream) transport.
1196///
1197/// Used by XRCE-DDS's HDLC-framed serial transport and (once the
1198/// bare-metal migration lands) by zenoh-pico's serial link layer.
1199///
1200/// # Handle model
1201///
1202/// `open()` returns a platform-defined [`Handle`](PlatformSerial::Handle)
1203/// — an FD on POSIX, a port-table index on bare-metal, whatever the
1204/// impl wants. Every other method takes the handle back. This lets a
1205/// single platform impl service multiple concurrent devices (e.g.,
1206/// `zpico-serial`'s two-port table) without the trait constraining
1207/// the impl to a single active device.
1208///
1209/// Single-device platforms return the same handle forever and ignore
1210/// it internally; `INVALID` gives a well-defined "no live handle"
1211/// sentinel for shims that stash the current handle in a `static`.
1212///
1213/// # Path conventions
1214///
1215/// `path` in `open()` is platform-specific: a null-terminated UTF-8
1216/// device path on POSIX (e.g., `/dev/ttyUSB0` or a PTY), or a
1217/// board-defined port identifier on bare-metal (typically parsed by
1218/// the platform's internal handler). Callers pass the locator string
1219/// from their config unchanged; interpretation is the platform's job.
1220///
1221/// # I/O conventions
1222///
1223/// Read / write return `usize::MAX` on hard error. Read with
1224/// `timeout_ms == 0` should block for a platform-chosen default;
1225/// positive values are the poll/select deadline in milliseconds.
1226/// Returning `0` from `read()` indicates "no data within timeout" and
1227/// is **not** an error — both XRCE and zenoh-pico tolerate
1228/// timeout-zero reads.
1229pub trait PlatformSerial {
1230    /// Platform-specific handle type. POSIX returns the FD (`i32`);
1231    /// bare-metal returns a port-table index (`u8`). Must be `Copy`
1232    /// so shims can stash it in a `static`.
1233    type Handle: Copy;
1234
1235    /// Sentinel handle meaning "not a live device". Shims initialise
1236    /// their cached handle to this and compare against it to detect
1237    /// "transport not yet opened" states.
1238    const INVALID: Self::Handle;
1239
1240    /// Returns `true` if `h` is a live handle (not [`INVALID`](Self::INVALID)
1241    /// and points at a device that was opened and not yet closed).
1242    fn is_valid(h: Self::Handle) -> bool;
1243
1244    /// Open the serial device identified by `path`. Returns a live
1245    /// handle on success, [`INVALID`](Self::INVALID) on failure.
1246    fn open(path: *const u8) -> Self::Handle;
1247
1248    /// Close the given handle. No-op if already closed or invalid.
1249    fn close(h: Self::Handle);
1250
1251    /// Configure baud rate (in bits per second). Returns 0 on success,
1252    /// -1 on error. Called after `open()`; implementations may choose
1253    /// to apply the baud rate during `open()` instead and make this a
1254    /// no-op.
1255    fn configure(h: Self::Handle, baudrate: u32) -> i8;
1256
1257    /// Read up to `len` bytes into `buf`. Returns the number of bytes
1258    /// read, `0` on timeout, or `usize::MAX` on hard error.
1259    fn read(h: Self::Handle, buf: *mut u8, len: usize, timeout_ms: u32) -> usize;
1260
1261    /// Write `len` bytes from `buf`. Returns bytes written, or
1262    /// `usize::MAX` on error.
1263    fn write(h: Self::Handle, buf: *const u8, len: usize) -> usize;
1264}
1265
1266// ============================================================================
1267// CAN frame driver (RFC-0132; the C header is the contract)
1268// ============================================================================
1269
1270/// The implementer surface of `<nros/platform_can.h>`, the CAN frame driver.
1271///
1272/// A Rust backend implements this and turns it into the five C symbols with
1273/// `nros_platform_cffi::nros_platform_export_can!`; a C backend defines the
1274/// symbols directly. The header is the contract: return codes are its
1275/// `NROS_PLATFORM_CAN_*` values, and each method mirrors one call there.
1276///
1277/// # Pointers
1278///
1279/// This crate has no dependencies, so it cannot name the header's types.
1280/// `can` points at the caller's `nros_platform_can_t` (the backend's state
1281/// lives inside it and must fit the header's size) and `frame` at an
1282/// `nros_platform_can_frame_t`; the export macro passes the typed pointers
1283/// through unchanged. Any of them may be NULL, and a backend checks.
1284///
1285/// # Frame validity
1286///
1287/// A backend refuses the frames `nros_platform_can_frame_check` (the header's
1288/// `static inline`) refuses, with `NROS_PLATFORM_CAN_EINVAL`. A C backend calls
1289/// it; a Rust backend calls it through a compiled shim, so the rule has one
1290/// definition.
1291pub trait PlatformCan {
1292    /// `nros_platform_can_open`: open `device` (NULL: the image's device);
1293    /// `want_fd` non-zero fails on a device without CAN FD.
1294    fn open(can: *mut c_void, device: *const core::ffi::c_char, want_fd: u8) -> i8;
1295
1296    /// `nros_platform_can_send`: send one frame within `timeout_us`.
1297    fn send(can: *mut c_void, frame: *const c_void, timeout_us: u32) -> i8;
1298
1299    /// `nros_platform_can_fd_active`: non-zero when the handle carries CAN FD.
1300    fn fd_active(can: *const c_void) -> u8;
1301
1302    /// `nros_platform_can_recv`: receive one frame within `timeout_us`.
1303    fn recv(can: *mut c_void, frame: *mut c_void, timeout_us: u32) -> i8;
1304
1305    /// `nros_platform_can_close`: idempotent.
1306    fn close(can: *mut c_void);
1307}
1308
1309/// Smallest number of bytes ever left unused on the CALLING task's stack, or
1310/// `0` if this port does not instrument it.
1311///
1312/// Lives at the crate root, NOT in [`task`], because that module is
1313/// `#[cfg(feature = "alloc")]` -- `PlatformTask` allocates its own storage --
1314/// while this is a bare `extern "C"` query returning a `usize`. Gating it
1315/// behind `alloc` made it unavailable on exactly the no_std targets whose
1316/// stacks are worth watching, and broke the executor's stack-headroom rule
1317/// on the Zephyr build.
1318///
1319/// The heap has long had `heap_used_bytes`; this is the stack's
1320/// counterpart. HEADROOM, not usage, and for the CALLING task only -- both
1321/// kernels answer for self with no handle, and answering for an arbitrary
1322/// task needs a native handle this ABI does not carry.
1323///
1324/// `0` means "not instrumented", not "no headroom".
1325pub fn stack_unused_bytes() -> usize {
1326    unsafe extern "C" {
1327        fn nros_platform_task_stack_unused_bytes() -> usize;
1328    }
1329    // SAFETY: a plain query with no arguments and no state; every port either
1330    // answers or returns 0.
1331    unsafe { nros_platform_task_stack_unused_bytes() }
1332}
1333
1334/// Give up the processor to another ready task, through the port's
1335/// `nros_platform_yield_now`. For a thread that must wait for another to
1336/// finish a short critical step (the executor's wake fan-out waits out a backend
1337/// callback this way) without spinning a single core it shares with that
1338/// thread.
1339pub fn yield_now() {
1340    unsafe extern "C" {
1341        fn nros_platform_yield_now();
1342    }
1343    // SAFETY: no arguments, no return value; every port defines it.
1344    unsafe { nros_platform_yield_now() }
1345}
1346
1347/// [`stack_unused_bytes`], capped at `limit`: `min(unused, limit)`, reading at
1348/// most `limit` bytes of the calling task's stack.
1349///
1350/// What the `stack-headroom-runtime` rule needs: whether at least `limit`
1351/// bytes are unused. Below `limit` the answer is the exact headroom, so a
1352/// breach is reported without a second, full scan. `0` means "not
1353/// instrumented", as for [`stack_unused_bytes`].
1354pub fn stack_unused_bytes_upto(limit: usize) -> usize {
1355    unsafe extern "C" {
1356        fn nros_platform_task_stack_unused_bytes_upto(limit: usize) -> usize;
1357    }
1358    // SAFETY: a plain query; `limit` is a value, and every port either
1359    // answers or returns 0.
1360    unsafe { nros_platform_task_stack_unused_bytes_upto(limit) }
1361}