When logging is not an option - count
In microcontroller firmwares it is not always possible or desirable to log things, for example due to:
- Timing constraints in interrupts
- Memory constraints
- Absence of a logging interface
- Absence of log recording from firmware boot, making accurate calculations impossible
- Inconvenience of analyzing log output
This crate provide a convenient way to count events, errors or anything else, using a RAM array:
fn high_frequency_irq() {
let r = do_something();
cnt::cnt_if!(r.is_err(), unpack_errors: u64);
}
fn process_packet() {
cnt::cnt!(packet_count: u32);
}Under the hood, a simple linker trick is used to obtain a unique ID for each count statement (similar to defmt).
Then an element of a _CNT_RAM_BUFFER is incremented. There are no critical sections involved, so counting is safe in
any context, including interrupts. On cores with atomic read-modify-write instructions (Cortex-M3 and up) counters are
updated with ldrex/strex, so a counter shared between thread mode and an interrupt never loses an update; on cores
without them (Cortex-M0/M0+) a plain load, add and store is used.
Library crates can count per instance, see Instance counters.
- Add
cnt = "0.5"toCargo.toml(the dependency must not be renamed, generated code refers tocnt) - Add
"-C", "link-arg=-Tcnt.x",to.cargo/config.toml - Optionally set
CNT_RAM_BUFFER_SIZE_WORDSin the[env]section as well, default value is 64 words (256 bytes, 6400 words on a host). Linking fails with acnt: too many RAM counterserror if the buffer is too small for the counters in use. - Flash your firmware and run the CLI tool:
-
To read once:
cnt read --chip <CHIP> <PATH_TO_ELF> -
To run TUI:
cnt tui --chip <CHIP> <PATH_TO_ELF> -
<PATH_TO_ELF>can be omitted when running inside the firmware project, the most recently built binary is used. -
Probe and target are selected the same way as in probe-rs:
--chip,--probe VID:PID[:SERIAL],--protocol,--speed,--connect-under-reset,--chip-description-path, or the matchingPROBE_RS_*environment variables. If multiple probes are connected and--probeis not given, you will be asked to pick one. -
If
--chipis not given, it is taken from aprobe-rs run --chip <CHIP>orcnt run --chip <CHIP>runner in.cargo/config.toml, so usually justcnt readorcnt tuiis enough. -
For scripts, CI and agents:
--format jsonprints one JSON document,--format jsonlone JSON object per counter and line (alsoCNT_FORMAT=json), e.g.cnt read --format jsonl | jq 'select(.value > 0)'. Applies tolist,readandreset; JSON goes to stdout, diagnostics to stderr. -
To follow changes:
cnt read --watch [--interval <MS>]prints all counters, then every counter whose value changed, with its current value. With--format jsonleach line has anevent(initial,change,resetwhen all non-zero counters of a buffer went down,decreasewhen only some did) and atsin Unix milliseconds, e.g.cnt read --watch --format jsonl | jq 'select(.event == "reset")'. -
defmt logs of the firmware (defmt-rtt) are shown together with the counters in
cnt read --watchandcnt tui, using the same probe connection,--no-defmtturns them off. Injsonlthey are{"event": "log", ...}lines. -
cnt runflashes the firmware, resets the target and then works likecnt read --watch(orcnt tuiwith--tui), so it can be the cargo runner instead ofprobe-rs run. Watching stops withqor Ctrl+C:[target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "cnt run --chip STM32H533RE"
-
read,tuiandresetcheck that the target runs the ELF's firmware: the GNU build id is read from the target's flash and compared with the ELF's, a mismatch is refused (--forceto use the ELF anyway), as the counters would be decoded with the wrong names. Without an ELF argument the ELF with the target's build id is used: fromtarget/, the directories inWW_ELF_PATH, or the ELF directory~/.cache/ww/elf, whichcnt elf add <ELF or release archive .tar.zst>fills. The firmware has to keep the note in flash:# .cargo/config.toml rustflags = ["-C", "link-arg=--build-id=sha1"]
/* memory.x */ SECTIONS { .note.gnu.build-id : ALIGN(4) { __build_id_start = .; KEEP(*(.note.gnu.build-id)); __build_id_end = .; } > FLASH } INSERT AFTER .rodata; -
The same counters can be read over WireWeaver instead of a probe:
ww counters(theww_countersAPI).
-
examples/b135_demo is a firmware that shows the TUI at work on a B135 board (STM32H725IG):
made-up traffic of a USB path, a CAN bus, an ADC and a control loop, as counters of each kind, in groups, with units
and all five severities, a group the firmware clears, a counter in backup registers and defmt logs. just demo
flashes it through the probe and opens the TUI.
Call counters_ram_buffer, it returns the buffer as &[AtomicU32], as the values keep changing while it is read:
use core::sync::atomic::Ordering;
fn main() {
for word in cnt::counters_ram_buffer() {
let value = word.load(Ordering::Relaxed);
// send using whatever interface to host
}
}u64 counters occupy two words, low word first, and might be torn if read while being incremented.
Instance counters (see Instance counters) can be read by name with get, and set back to 0 with
clear:
let crc_errors: u64 = UART1_FRAMER_CNT.get(FramerEvent::CrcError);
UART1_FRAMER_CNT.clear();While cargo test runs on the target, e.g. with embedded-test, probe-rs
holds the probe, so the CLI cannot read the counters. Assert on them in the test instead: give the code under test its
own instance counters and check them with get. Give each test its own Counters static, declared inside the test:
#[test]
fn bad_crc_is_counted() {
static CNT: cnt::Counters<FramerEvent> = cnt::counters!(FramerEvent, bad_crc);
let mut framer = Framer::new(&CNT);
framer.feed_frame(&BAD_CRC);
assert_eq!(CNT.get(FramerEvent::CrcError), 1);
}The target is reset before every test, so there one shared static would also start at 0. On a host (see
Host builds) the tests of a binary run in parallel threads of one process, so tests sharing a static
count into the same counters and exact asserts fail at random; neither clear() at the start of a test nor comparing
values before and after helps against that. With one static per test the same tests pass on both.
This only works if the code under test takes its &'static Counters<E> from the caller. cnt! call-site counters and
Counters statics private to the code under test have no handle a test can choose: they are shared by all tests and
cnt! counters cannot be read with get at all, so use injected instance counters for anything a test should check.
Code using counters also builds and runs on a host (any target_os other than none), e.g. in unit tests. There is no
cnt.x there, so each counter gets its words in the buffer when it is first incremented: counting works and
counters_ram_buffer/counters_bkp_buffer return the values, in order of first use. Both buffers are ordinary statics
of 6400 words on a host, unless CNT_RAM_BUFFER_SIZE_WORDS/CNT_BKP_BUFFER_SIZE_WORDS is set, so that every test can
have its own Counters statics (see Tests on the target). Counting panics with
cnt: too many RAM counters when a buffer is full.
cnt!(event_count: u32 += 1 + request.len() as u32);cnt!(bytes_lost: u64, warn);cnt!(bytes_rx: u64 += buf.len() as u64, debug, usart);Set unit for better readability, upstream software can then convert from e.g., Bytes to KiB or MiB automatically:
cnt!(bytes_rx: u64 "B" += buf.len() as u64, debug, usart);A cnt! counter belongs to its call site: if a driver crate is used twice in a firmware, both instances count into the
same counter. For per-instance counters the driver declares its events as an enum and takes a &'static Counters<E>,
and the firmware decides how many instances there are, what they are called and where they live:
// In the driver crate
#[derive(cnt::Count)]
pub enum FramerEvent {
CrcError, // u32, info
#[count(warn)]
Overrun,
#[count(u64, unit = "B", debug)]
RxBytes,
}
pub struct Framer { cnt: &'static cnt::Counters<FramerEvent>, /* ... */ }
impl Framer {
pub fn feed(&mut self, byte: u8) {
self.cnt.add(FramerEvent::RxBytes, 1);
self.cnt.count_if(crc_failed, FramerEvent::CrcError);
}
}
// In the firmware
static UART1_FRAMER_CNT: cnt::Counters<FramerEvent> = cnt::counters!(FramerEvent, uart1);
static RADIO_FRAMER_CNT: cnt::Counters<FramerEvent> = cnt::bkp_counters!(FramerEvent, radio);
let uart1 = Framer::new(&UART1_FRAMER_CNT);
let radio = Framer::new(&RADIO_FRAMER_CNT);Host tools show them as uart1/CrcError, radio/CrcError and so on, with the location of the counters! line. The
counters live in the same _CNT_RAM_BUFFER/_CNT_BKP_BUFFER as cnt! counters, so counters_ram_buffer() still
returns everything. Increments compile to the same code as cnt!, the variant is a constant offset from the instance.
The disabled feature of cnt compiles all counters out: the macros expand to nothing (arguments are still
type-checked, but not evaluated), Counters<E> becomes a zero-sized no-op and no buffers exist. A library crate can
depend on cnt unconditionally and let its users opt in, or a firmware can measure the overhead of counting:
[dependencies]
cnt = { version = "0.5", features = ["disabled"] }cnt.x is still generated (empty), so a -Tcnt.x link argument keeps working. cnt::DISABLED tells at compile time
whether counters are active.
bkp_cnt! and bkp_cnt_if! take the same arguments as cnt! and cnt_if!, but count into _CNT_BKP_BUFFER, which
is meant to be placed into memory that survives a reset, e.g. backup SRAM. To use it:
- Set
CNT_BKP_BUFFER_SIZE_WORDSin the[env]section of.cargo/config.toml, the default is 0. - Add a
BKPSRAMregion tomemory.x, or setCNT_BKP_MEMORY_REGIONto the name of an existing region:MEMORY { /* ... */ BKPSRAM : ORIGIN = 0x40024000, LENGTH = 4K }
- Enable the backup domain in the firmware before counting (clock, write access, battery or VBAT), as it is chip specific and not done by this crate.
The buffer is never initialized by the startup code, so on the first boot it contains whatever the memory did; zero it
once yourself or with cnt reset --bkp. In the TUI, R resets BKP counters, r RAM counters.
On cores without atomic read-modify-write instructions (target_has_atomic = "32" not set, e.g. Cortex-M0/M0+) a
counter updated both from thread mode and from an interrupt may lose an update when the interrupt preempts another
update of the same counter. On all cores a u64 counter is two words, so reading it while it is being incremented may
return a torn value. Counters are for statistics, not for exact accounting.
Instance counters must live in a static, as their space is allocated by the linker; dynamically created instances
have to share one.
If CLI is not available, use arm-none-eabi-nm to view the counter indices:
arm-none-eabi-nm ./path/to/elf_fw | grep '"kind":"counter"'