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
epoch.hpp
Go to the documentation of this file.
1/**
2 * @file epoch.hpp
3 * @brief A 32-bit counter extended to 64 bits by counting its overflows
4 * @ingroup system
5 *
6 * The port's counter wraps at 2^32; its overflow interrupt calls
7 * on_overflow(), which counts the wrap and acknowledges the flag. count64()
8 * reads the epoch, the count and the pending flag and retries if the epoch
9 * moved under it. A wrap the handler has not serviced yet shows as the flag
10 * set with a small count, and counts as one more epoch.
11 *
12 * The handler's two writes are not atomic as a pair, so the overflow
13 * interrupt must run at a level no reader of count64() preempts. The bound:
14 * the handler runs within half a wrap period, 35.8 minutes at 1 MHz.
15 *
16 * A template over the port so it is unit-tested with a fake counter.
17 */
18
19#ifndef SBL_SYSTEM_EPOCH_HPP_
20#define SBL_SYSTEM_EPOCH_HPP_
21
22#include <cstdint>
23
24namespace sbl::system {
25
26template<class Port>
27class Epoch {
28public:
29 /** The port's overflow handler: `Port::setup(&Epoch<Port>::on_overflow)`. */
30 static void on_overflow() {
31 if (Port::overflow()) { // a late flag clear can re-enter the handler
32 epoch_ = epoch_ + 1;
33 Port::acknowledge();
34 }
35 }
36
37 /** The count since the port started, 64 bits. */
38 static uint64_t count64() {
39 for (;;) {
40 const uint32_t e1 = epoch_;
41 const uint32_t c = Port::count();
42 const bool pending = Port::overflow();
43 const uint32_t e2 = epoch_;
44 if (e1 != e2) {
45 continue; // the handler ran mid-read
46 }
47 const uint32_t e = (pending && c < 0x80000000u) ? e1 + 1 : e1;
48 return (static_cast<uint64_t>(e) << 32) | c;
49 }
50 }
51
52 /** Wraps counted so far. */
53 static uint32_t epoch() { return epoch_; }
54
55 /** Start over; for a port that restarts, and for tests. */
56 static void reset() { epoch_ = 0; }
57
58private:
59 static inline volatile uint32_t epoch_ = 0;
60};
61
62namespace detail {
63
64/** A 64-bit count at `rate` counts per second, in milliseconds, without overflow. */
65constexpr uint64_t to_millis(uint64_t count, uint32_t rate) {
66 return (count / rate) * 1000u + ((count % rate) * 1000u) / rate;
67}
68
69} // namespace detail
70
71} // namespace sbl::system
72
73#endif // SBL_SYSTEM_EPOCH_HPP_
static uint32_t epoch()
Definition epoch.hpp:53
static void on_overflow()
Definition epoch.hpp:30
static uint64_t count64()
Definition epoch.hpp:38
static void reset()
Definition epoch.hpp:56
The system layer: execution levels, the control critical section, ring buffers, assertions and the fa...
Definition assert.hpp:49