Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
registry.hpp
Go to the documentation of this file.
1/**
2 * @file registry.hpp
3 * @brief The profiling registry: every budget, section and counter in one table
4 *
5 * An AudioBudget, a SectionProfile or a Counter that registers by name keeps
6 * its statistics in an entry of one static table, behind a header, at the
7 * symbol `sbl_profiling_registry`. The reporter (report.hpp) walks the table,
8 * so an app does not list what it measures, and a tool that reads memory
9 * over SWD needs that one symbol and the layout documented on Registry. No allocation: the
10 * table holds SBL_PROFILING_REGISTRY_CAPACITY entries, and a registration
11 * past the capacity fails.
12 *
13 * Gated behind SBL_PROFILING_ENABLED: without it there is no table and
14 * registration does nothing.
15 *
16 * Usage:
17 * @code
18 * static sbl::system::profiling::AudioBudget budget;
19 * static sbl::system::profiling::SectionProfile osc;
20 * static sbl::system::profiling::Counter edges;
21 *
22 * // At startup, before the audio starts:
23 * budget.init(48000, 48);
24 * budget.register_as("audio");
25 * osc.register_as("osc");
26 * edges.register_as("edges");
27 * @endcode
28 */
29
30#ifndef SBL_SYSTEM_PROFILING_REGISTRY_HPP_
31#define SBL_SYSTEM_PROFILING_REGISTRY_HPP_
32
33#include <atomic>
34#include <cstddef>
35#include <cstdint>
36
37#ifdef SBL_PROFILING_ENABLED
39#endif
40
41/** Entries the registry's table holds. Define it for the app's target to change it. */
42#ifndef SBL_PROFILING_REGISTRY_CAPACITY
43#define SBL_PROFILING_REGISTRY_CAPACITY 16
44#endif
45
46namespace sbl::system::profiling {
47
48inline constexpr uint32_t REGISTRY_MAGIC = 0x464F5250u; /**< the bytes "PROF", little-endian */
49inline constexpr uint32_t REGISTRY_VERSION = 1; /**< layout version this header writes */
50inline constexpr size_t REGISTRY_CAPACITY = SBL_PROFILING_REGISTRY_CAPACITY; /**< entries the table holds */
51inline constexpr size_t NAME_SIZE = 12; /**< an entry's name field, terminator included */
52inline constexpr uint32_t NO_MINIMUM = 0xFFFFFFFFu; /**< `min` before the window's first measurement */
53
54static_assert(REGISTRY_CAPACITY > 0, "SBL ERROR: SBL_PROFILING_REGISTRY_CAPACITY must be at least 1");
55
56/** What an entry measures: the value of its `kind` field. */
57enum class Kind : uint8_t {
58 None = 0,
59 Budget = 1,
60 Section = 2,
61 Counter = 3,
62};
63
64/** One entry of the table: its live statistics and its last window. The layout is in the Registry comment. */
65struct Entry {
66 uint32_t kind = 0; /**< a Kind value */
67 char name[NAME_SIZE] = {}; /**< NUL-terminated, 11 characters at most */
68 uint32_t count = 0; /**< blocks, passes or events since the start */
69 float avg = 0.0f; /**< running average in cycles (budget, section) */
70 uint32_t max = 0; /**< largest in the open window, in cycles */
71 uint32_t min = NO_MINIMUM; /**< smallest in the open window; NO_MINIMUM before the first */
72 uint32_t overruns = 0; /**< budget: blocks over the limit in the open window */
73 uint32_t limit = 0; /**< budget: cycles a block may take */
74 uint32_t window_count = 0; /**< blocks, passes or events in the last window */
75 float window_avg = 0.0f; /**< avg when the window closed */
76 uint32_t window_max = 0; /**< max of the window; 0 if it measured nothing */
77 uint32_t window_min = 0; /**< min of the window; 0 if it measured nothing */
78 uint32_t window_overruns = 0; /**< overruns of the window */
79 uint32_t window_base = 0; /**< count when the window closed */
80
81 /**
82 * @brief True if the entry is of this kind
83 * @param k Kind to test
84 * @return kind == k
85 */
86 constexpr bool is(Kind k) const { return kind == static_cast<uint32_t>(k); }
87
88 /**
89 * @brief Record one measurement: the count, the running average (alpha 1/128), the window's extremes
90 * @param cycles Measured cycles
91 */
92 void measure(uint32_t cycles) {
93 ++count;
94 if (cycles > max) {
95 max = cycles;
96 }
97 if (cycles < min) {
98 min = cycles;
99 }
100 avg += (static_cast<float>(cycles) - avg) * AVERAGE_ALPHA;
101 }
102
103 /** Start a window over: the extremes and the overruns. The average and the count go on. */
104 void open_window() {
105 max = 0;
106 min = NO_MINIMUM;
107 overruns = 0;
108 }
109
110 /** Copy the statistics into the window fields and start the next window. */
120
121 /** Forget every statistic. The kind, the name and the limit stay. */
122 void clear() {
123 count = 0;
124 avg = 0.0f;
125 window_count = 0;
126 window_avg = 0.0f;
127 window_max = 0;
128 window_min = 0;
129 window_overruns = 0;
130 window_base = 0;
131 open_window();
132 }
133
134 /** The running average's weight for a new measurement (about 130 ms to settle at 1 ms blocks). */
135 static constexpr float AVERAGE_ALPHA = 1.0f / 128.0f;
136};
137
138/**
139 * @brief The header and the table
140 *
141 * ## Windows
142 *
143 * An entry has live fields, written by the code it measures, and window
144 * fields, a copy of the statistics for one span of time. A reader asks for a
145 * window; the measured context closes it. request_window() adds one to
146 * `window_request`, and the next AudioBudget::on_block_end() of a registered
147 * budget (or a call of window_point()) copies every entry's statistics into
148 * its window fields, starts the next window (the maximum, the minimum and
149 * the overruns start over; the running average and the count go on) and
150 * publishes `window_seq`. The reader touches the window fields only between
151 * that and its next request, so it never reads a window that is being
152 * written and the measured context is never masked.
153 *
154 * The context that closes a window copies every entry. An entry measured in
155 * another context is copied as it stands: each field whole, the set of them
156 * possibly from before and after one of its updates.
157 *
158 * ## Layout, version 1
159 *
160 * Little-endian, every field four bytes, so the layout is the same on a
161 * 32-bit target and a 64-bit host. `u32` is an unsigned integer, `f32` an
162 * IEEE 754 single.
163 *
164 * Header, at `sbl_profiling_registry`:
165 *
166 * | Offset | Type | Field | Meaning |
167 * |--------|------|----------------|---------|
168 * | 0 | u32 | magic | 0x464F5250, the bytes "PROF" |
169 * | 4 | u32 | version | 1 |
170 * | 8 | u32 | header_size | Bytes from the symbol to the first entry (40) |
171 * | 12 | u32 | entry_size | Bytes an entry takes (64) |
172 * | 16 | u32 | capacity | Entries the table holds |
173 * | 20 | u32 | count | Entries registered, in registration order |
174 * | 24 | u32 | cycle_rate | Counts per second of the cycle counter |
175 * | 28 | u32 | window_request | Windows asked for; a reader adds one |
176 * | 32 | u32 | window_seq | Twice the request last served; odd while a window is being written |
177 * | 36 | u32 | reserved | 0 |
178 *
179 * Entry `i`, at `header_size + i * entry_size`:
180 *
181 * | Offset | Type | Field | Meaning |
182 * |--------|------|-----------------|---------|
183 * | 0 | u32 | kind | 1 budget, 2 section, 3 counter |
184 * | 4 | char | name[12] | The name, NUL-terminated, 11 characters at most |
185 * | 16 | u32 | count | Blocks, passes or events since the start |
186 * | 20 | f32 | avg | Running average in cycles (budget, section) |
187 * | 24 | u32 | max | Largest in the open window, in cycles |
188 * | 28 | u32 | min | Smallest in the open window; 0xFFFFFFFF before the first |
189 * | 32 | u32 | overruns | Budget: blocks over the limit in the open window |
190 * | 36 | u32 | limit | Budget: cycles a block may take |
191 * | 40 | u32 | window_count | Blocks, passes or events in the last window |
192 * | 44 | f32 | window_avg | avg when the window closed |
193 * | 48 | u32 | window_max | max of the window; 0 if it measured nothing |
194 * | 52 | u32 | window_min | min of the window; 0 if it measured nothing |
195 * | 56 | u32 | window_overruns | overruns of the window |
196 * | 60 | u32 | window_base | count when the window closed |
197 *
198 * A counter uses kind, name, count, window_count and window_base.
199 *
200 * ## Reading over SWD while the core runs
201 *
202 * Read the header at the symbol and check magic and version; then read
203 * `count` entries from `header_size`, `entry_size` apart.
204 *
205 * - A live field is one word and is whole whenever it is read. Two live
206 * fields may be from before and after one update.
207 * - The window fields of all entries are one consistent set when
208 * `window_seq` is even and reads the same before and after they are read.
209 * If it is odd or has changed, read again.
210 * - A new window comes when the app's reporter asks for one. A tool can ask
211 * too: write `window_request + 1` to `window_request`, then wait until
212 * `window_seq` is even and at least twice that value. The app and the tool
213 * share the windows, so a tool's request ends the app's window early.
214 */
215struct Registry {
216 uint32_t magic; /**< REGISTRY_MAGIC */
217 uint32_t version; /**< REGISTRY_VERSION */
218 uint32_t header_size; /**< REGISTRY_HEADER_SIZE */
219 uint32_t entry_size; /**< REGISTRY_ENTRY_SIZE */
220 uint32_t capacity; /**< REGISTRY_CAPACITY */
221 uint32_t count; /**< entries registered, in registration order */
222 uint32_t cycle_rate; /**< counts per second of the cycle counter */
223 std::atomic<uint32_t> window_request; /**< windows asked for; a reader adds one */
224 std::atomic<uint32_t> window_seq; /**< twice the request last served; odd while a window is being written */
225 uint32_t reserved; /**< 0 */
226 Entry entries[REGISTRY_CAPACITY]; /**< the table */
227};
228
229inline constexpr uint32_t REGISTRY_HEADER_SIZE = 40; /**< bytes from the symbol to the first entry */
230inline constexpr uint32_t REGISTRY_ENTRY_SIZE = 64; /**< bytes an entry takes */
231
232// The documented layout: a change here is a change of REGISTRY_VERSION.
233static_assert(sizeof(std::atomic<uint32_t>) == sizeof(uint32_t) && std::atomic<uint32_t>::is_always_lock_free,
234 "SBL ERROR: the registry needs a lock-free 32-bit atomic the size of a uint32_t");
235static_assert(sizeof(float) == 4, "SBL ERROR: the registry's f32 fields are 4 bytes");
236static_assert(sizeof(Entry) == REGISTRY_ENTRY_SIZE, "SBL ERROR: the registry entry's size is documented");
237static_assert(offsetof(Entry, name) == 4 && offsetof(Entry, count) == 16 && offsetof(Entry, avg) == 20 &&
238 offsetof(Entry, max) == 24 && offsetof(Entry, min) == 28 && offsetof(Entry, overruns) == 32 &&
239 offsetof(Entry, limit) == 36,
240 "SBL ERROR: the registry entry's live fields are documented");
241static_assert(offsetof(Entry, window_count) == 40 && offsetof(Entry, window_avg) == 44 &&
242 offsetof(Entry, window_max) == 48 && offsetof(Entry, window_min) == 52 &&
243 offsetof(Entry, window_overruns) == 56 && offsetof(Entry, window_base) == 60,
244 "SBL ERROR: the registry entry's window fields are documented");
245static_assert(offsetof(Registry, count) == 20 && offsetof(Registry, cycle_rate) == 24 &&
246 offsetof(Registry, window_request) == 28 && offsetof(Registry, window_seq) == 32 &&
247 offsetof(Registry, entries) == REGISTRY_HEADER_SIZE,
248 "SBL ERROR: the registry header is documented");
249
250#ifdef SBL_PROFILING_ENABLED
251
252extern "C" {
253/** The registry. C linkage, so the symbol is this name on every target. */
254inline Registry sbl_profiling_registry = {
259 static_cast<uint32_t>(REGISTRY_CAPACITY),
260 0, // count
261 cycle_rate(), // cycle_rate
262 {0}, // window_request
263 {0}, // window_seq
264 0, // reserved
265 {},
266};
267}
268
269/** The registry, for code that walks it. */
270inline Registry& registry() { return sbl_profiling_registry; }
271
272/** Entries registered. */
273inline uint32_t entry_count() { return registry().count; }
274
275/** Entry `index` in registration order, or nullptr past the last. */
276inline const Entry* entry(uint32_t index) { return index < registry().count ? &registry().entries[index] : nullptr; }
277
278namespace detail {
279
280/**
281 * Take the next entry for `kind` under `name`, starting from `from`'s statistics.
282 * The name is cut to NAME_SIZE - 1 characters. Returns nullptr when the table is full.
283 * Startup only: before the measured code runs.
284 */
285inline Entry* add_entry(Kind kind, const char* name, const Entry& from) {
286 Registry& r = registry();
287 if (r.count >= REGISTRY_CAPACITY || name == nullptr) {
288 return nullptr;
289 }
290 Entry& e = r.entries[r.count];
291 e = from;
292 e.kind = static_cast<uint32_t>(kind);
293 size_t i = 0;
294 for (; i < NAME_SIZE - 1 && name[i] != '\0'; ++i) {
295 e.name[i] = name[i];
296 }
297 for (; i < NAME_SIZE; ++i) {
298 e.name[i] = '\0';
299 }
300 r.count = r.count + 1; // last, so a reader never lists an entry that is not whole
301 return &e;
302}
303
304/** `window_seq` for a served request. */
305inline constexpr uint32_t seq_for(uint32_t request) { return request << 1; }
306
307/**
308 * @brief Where a budget, a section or a counter keeps its statistics
309 *
310 * Its own entry until it registers, then an entry of the registry's table.
311 * Not copyable: a copy would write to the original's entry.
312 */
313class Slot {
314public:
315 constexpr Slot() = default;
316 Slot(const Slot&) = delete;
317 Slot& operator=(const Slot&) = delete;
318
319 /** Move the statistics into the table. False if already registered or the table is full. */
320 bool enroll(Kind kind, const char* name) {
321 if (registered_) {
322 return false;
323 }
324 Entry* e = add_entry(kind, name, *stats_);
325 if (e == nullptr) {
326 return false;
327 }
328 stats_ = e;
329 registered_ = true;
330 return true;
331 }
332
333 Entry& stats() { return *stats_; }
334 const Entry& stats() const { return *stats_; }
335 bool registered() const { return registered_; }
336
337private:
338 Entry own_{};
339 Entry* stats_ = &own_;
340 bool registered_ = false;
341};
342
343} // namespace detail
344
345/**
346 * @brief Ask for a window. Reader's side (the main loop).
347 * @return The request, for window_ready()
348 */
349inline uint32_t request_window() {
350 Registry& r = registry();
351 const uint32_t request = r.window_request.load(std::memory_order_relaxed) + 1;
352 r.window_request.store(request, std::memory_order_release);
353 return request;
354}
355
356/**
357 * @brief True once the window asked for by `request` is closed
358 *
359 * From then until the reader's next request_window(), the window fields are
360 * the reader's to read.
361 */
362inline bool window_ready(uint32_t request) {
363 const uint32_t seq = registry().window_seq.load(std::memory_order_acquire);
364 return (seq & 1u) == 0 && static_cast<int32_t>(seq - detail::seq_for(request)) >= 0;
365}
366
367/**
368 * @brief Close the window if a reader asked for one. Measured side.
369 *
370 * A registered AudioBudget calls this at the end of each block. An app with
371 * no budget calls it where its measured work ends. Costs two loads and a
372 * compare when no window is asked for.
373 */
374inline void window_point() {
375 Registry& r = registry();
376 const uint32_t served = r.window_seq.load(std::memory_order_relaxed);
377 if (detail::seq_for(r.window_request.load(std::memory_order_relaxed)) == served) {
378 return;
379 }
380 const uint32_t request = r.window_request.load(std::memory_order_acquire);
381 r.window_seq.store(detail::seq_for(request) - 1, std::memory_order_relaxed); // odd: being written
382 for (uint32_t i = 0; i < r.count; ++i) {
383 r.entries[i].close_window();
384 }
385 r.window_seq.store(detail::seq_for(request), std::memory_order_release);
386}
387
388/**
389 * @brief Empty the table and forget the windows
390 *
391 * For tests, and for an app that sets its profiling up again. Objects
392 * registered before the call still write to their old entries: register
393 * them again or stop using them.
394 */
395inline void clear_registry() {
396 Registry& r = registry();
397 r.count = 0;
398 for (Entry& e : r.entries) {
399 e = Entry{};
400 }
401 r.window_request.store(0, std::memory_order_relaxed);
402 r.window_seq.store(0, std::memory_order_relaxed);
403}
404
405#endif // SBL_PROFILING_ENABLED
406
407} // namespace sbl::system::profiling
408
409#endif // SBL_SYSTEM_PROFILING_REGISTRY_HPP_
The cycle counter behind the profiling tools.
Profiling: the cycle counter, the audio budget, section profiles and reports.
constexpr uint32_t REGISTRY_HEADER_SIZE
Definition registry.hpp:229
constexpr uint32_t REGISTRY_ENTRY_SIZE
Definition registry.hpp:230
constexpr size_t REGISTRY_CAPACITY
Definition registry.hpp:50
constexpr uint32_t NO_MINIMUM
Definition registry.hpp:52
constexpr uint32_t REGISTRY_MAGIC
Definition registry.hpp:48
constexpr uint32_t cycle_rate()
Definition cycles.hpp:42
constexpr size_t NAME_SIZE
Definition registry.hpp:51
constexpr uint32_t REGISTRY_VERSION
Definition registry.hpp:49
#define SBL_PROFILING_REGISTRY_CAPACITY
Definition registry.hpp:43
void measure(uint32_t cycles)
Record one measurement: the count, the running average (alpha 1/128), the window's extremes.
Definition registry.hpp:92
constexpr bool is(Kind k) const
True if the entry is of this kind.
Definition registry.hpp:86
static constexpr float AVERAGE_ALPHA
Definition registry.hpp:135
The header and the table.
Definition registry.hpp:215
std::atomic< uint32_t > window_request
Definition registry.hpp:223
std::atomic< uint32_t > window_seq
Definition registry.hpp:224
Entry entries[REGISTRY_CAPACITY]
Definition registry.hpp:226