nros_log/pool.rs
1//! Bounded storage so `get_or_create_logger` can hand out a
2//! logger for a name nobody registered at compile time.
3//!
4//! ## The gap this closes
5//!
6//! [`crate::get_logger`] is a LOOKUP: it answers with
7//! [`crate::DEFAULT_LOGGER`] for any name no `'static` [`crate::Logger`] was
8//! [`crate::register_logger`]ed under. That is correct for the Rust call sites
9//! it was written for, which declare their logger as a `static`. It is the
10//! wrong answer for a wrapper: `rclcpp::get_logger("x")` and
11//! `rcutils_get_logger("x")` CREATE, so a C caller doing
12//!
13//! ```c
14//! rclc_logger_set_level(rclc_log_get_logger("nav"), RCLC_LOG_SEVERITY_DEBUG);
15//! ```
16//!
17//! over a lookup-only implementation would silently have moved the threshold
18//! of the catch-all logger every other unregistered name also resolves to —
19//! compile, and differ. That is not allowed, so the creation has to be real,
20//! and because the Rust API is the source of truth for C and C++, it has to
21//! be real HERE rather than in `nros-c`.
22//!
23//! ## Bounded, because `no_std`
24//!
25//! Two static arenas, both sized by the `NROS_LOG_DYNAMIC_LOGGERS` knob
26//! (see `build.rs` for its ladder):
27//! one for the [`crate::Logger`] values, one for their names (a `&'static str`
28//! is what `Logger` holds, and a `const char *` from C is not one). Exhaustion
29//! is REPORTED, never silently aliased onto the default logger — see
30//! [`crate::get_or_create_logger`].
31
32use core::{cell::UnsafeCell, mem::MaybeUninit};
33
34use portable_atomic::{AtomicUsize, Ordering};
35
36use crate::Logger;
37
38/// How many loggers [`crate::get_or_create_logger`] may create.
39///
40/// The `NROS_LOG_DYNAMIC_LOGGERS` knob, resolved once by `build.rs` on the
41/// knob ladder: the environment (which is where an image's
42/// `[image.<id>] env` lands) > Kconfig `CONFIG_NROS_LOG_DYNAMIC_LOGGERS` /
43/// the board's `[knobs.log] dynamic_loggers` > 16. Linux host boards
44/// state 32; MCU boards keep 16. `0` declines the arena entirely (creation
45/// always fails, lookup still works), which is the right build for an image
46/// whose loggers are all `static`.
47///
48/// The `dynamic-loggers-<N>` features are deprecated (one release): honoured
49/// with a warning when no knob is stated, and a build error when they disagree
50/// with one.
51#[must_use]
52pub const fn dynamic_logger_capacity() -> usize {
53 crate::config::DYNAMIC_LOGGER_CAPACITY
54}
55
56/// Name-arena bytes reserved per runtime logger.
57///
58/// An AVERAGE, not a per-name cap ([`MAX_LOGGER_NAME_LEN`] is that): the
59/// arena is one bump region of `capacity * 24` bytes shared by every name.
60const NAME_ARENA_BYTES_PER_LOGGER: usize = 24;
61
62/// Longest logger name the arena will accept, in bytes.
63///
64/// A cap per NAME as well as in total, so one absurd name cannot consume the
65/// budget every other logger in the image needs.
66pub const MAX_LOGGER_NAME_LEN: usize = 48;
67
68const CAPACITY: usize = dynamic_logger_capacity();
69const NAME_ARENA_BYTES: usize = CAPACITY * NAME_ARENA_BYTES_PER_LOGGER;
70
71struct Pool {
72 loggers: UnsafeCell<[MaybeUninit<Logger>; CAPACITY]>,
73 loggers_used: AtomicUsize,
74 names_used: AtomicUsize,
75}
76
77/// The name arena, a static of its OWN rather than a field of [`POOL`].
78///
79/// phase-479 W5 — so its symbol is exactly `capacity * 24` bytes, with no
80/// struct padding and no `Logger` (whose size moves with its fields) beside
81/// it. `just mem-report` reads the image's capacity back out of that size
82/// (`nros_log::pool::NAMES`), which is the only way a STATIC report can state
83/// a count rather than a byte figure.
84struct NameArena(UnsafeCell<[u8; NAME_ARENA_BYTES]>);
85
86// SAFETY: every mutation reserves its region first with a `compare_exchange`
87// on the matching `*_used` counter, so no two writers ever touch the same
88// bytes; a region is written once and never rewritten or freed, so a reader
89// holding a `&'static` into it can never observe a change. Publication to
90// OTHER threads happens through the intern table's `AcqRel` CAS in
91// `crate::get_or_create_logger`, which is the only way another thread can
92// reach one of these references.
93unsafe impl Sync for Pool {}
94
95// SAFETY: as for `Pool` — every region is reserved by a CAS on
96// `POOL.names_used` before it is written, and never written again.
97unsafe impl Sync for NameArena {}
98
99static POOL: Pool = Pool {
100 loggers: UnsafeCell::new([const { MaybeUninit::uninit() }; CAPACITY]),
101 loggers_used: AtomicUsize::new(0),
102 names_used: AtomicUsize::new(0),
103};
104
105static NAMES: NameArena = NameArena(UnsafeCell::new([0_u8; NAME_ARENA_BYTES]));
106
107/// Copy `name` into the static name arena and return a `&'static str` over the
108/// copy. `None` if the name is too long or the arena is exhausted.
109pub(crate) fn intern_name(name: &str) -> Option<&'static str> {
110 let len = name.len();
111 if len == 0 || len > MAX_LOGGER_NAME_LEN || len > NAME_ARENA_BYTES {
112 return None;
113 }
114 loop {
115 let used = POOL.names_used.load(Ordering::Acquire);
116 let end = used.checked_add(len)?;
117 if end > NAME_ARENA_BYTES {
118 return None;
119 }
120 if POOL
121 .names_used
122 .compare_exchange(used, end, Ordering::AcqRel, Ordering::Acquire)
123 .is_err()
124 {
125 continue;
126 }
127 // SAFETY: `[used, end)` is reserved to this call by the CAS above and
128 // is never written again. The arena is a `'static`, so the slice we
129 // build over it lives for the program.
130 let interned: &'static str = unsafe {
131 let base = NAMES.0.get().cast::<u8>();
132 core::ptr::copy_nonoverlapping(name.as_ptr(), base.add(used), len);
133 core::str::from_utf8_unchecked(core::slice::from_raw_parts(base.add(used), len))
134 };
135 return Some(interned);
136 }
137}
138
139/// Move `logger` into the static logger arena and return a `&'static` to it.
140/// `None` when the arena is exhausted.
141// `dynamic-loggers-0` makes the capacity 0, a legal size: the comparison is then
142// always true, which is the right answer for a pool with no slots.
143#[allow(clippy::absurd_extreme_comparisons)]
144pub(crate) fn place(logger: Logger) -> Option<&'static Logger> {
145 loop {
146 let used = POOL.loggers_used.load(Ordering::Acquire);
147 if used >= CAPACITY {
148 return None;
149 }
150 if POOL
151 .loggers_used
152 .compare_exchange(used, used + 1, Ordering::AcqRel, Ordering::Acquire)
153 .is_err()
154 {
155 continue;
156 }
157 // SAFETY: slot `used` is reserved to this call by the CAS above, is
158 // uninitialised until this write, and is never written again.
159 let placed: &'static Logger = unsafe {
160 let base = POOL.loggers.get().cast::<MaybeUninit<Logger>>();
161 let slot = base.add(used);
162 slot.write(MaybeUninit::new(logger));
163 &*slot.cast::<Logger>()
164 };
165 return Some(placed);
166 }
167}
168
169/// How many of the [`dynamic_logger_capacity`] slots are spent.
170///
171/// Counts slots CLAIMED, which is one more than the loggers reachable by name
172/// whenever two threads raced the same new name: the loser's slot is spent and
173/// unreferenced. Bounded and reported rather than reclaimed — this arena has
174/// no free list by construction.
175#[must_use]
176pub fn dynamic_loggers_in_use() -> usize {
177 POOL.loggers_used.load(Ordering::Acquire)
178}
179
180/// Bytes of the name arena spent, and its total size.
181#[must_use]
182pub fn dynamic_logger_name_arena() -> (usize, usize) {
183 (POOL.names_used.load(Ordering::Acquire), NAME_ARENA_BYTES)
184}