diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 95c7c46..fc825fc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -345,12 +345,12 @@ ZephCore-only divergence from Arduino MeshCore (like the Adaptive Contention Win **Per-role step policy** (policy lives in the role, not the estimator): | Role | Policy | Why | |---|---|---| -| Repeater | bidirectional | clock not load-bearing: forwarding/dedup/remote-admin run on `millis()`/hashes; a backward step only mutes own adverts at peers for a window equal to the step | +| Repeater | bidirectional | clock not load-bearing: forwarding/dedup/remote-admin run on `millis()`/hashes; a backward verdict is slewed by the clock (ADR 0013), so nothing is muted | | Observer | bidirectional | clock only stamps observations — exactly what this fixes | | Room server | forward-only | post timestamps feed client `sync_since` ordering | | Companion | forward-only | own clock stamps outgoing DMs; peers hold per-sender replay high-water marks | -**Step application**: the shared policy (suppression/pedigree checks inside `evaluateNow`, forward-only skip, uint32-overflow guard, set clock, one `zephcore_rtc_save` per step — never per evaluation) lives in `MeshTimeSync::runTick()`; when it returns true, the role shifts its wall-clock-anchored bookkeeping by `lastStepDelta()` — repeater: neighbor `heard_timestamp`s, ACL `last_activity`, login/anon/discover rate-limiter resets; room server: ACL + login limiter. +**Step application**: the shared policy (suppression/pedigree checks inside `evaluateNow`, forward-only skip, uint32-overflow guard, set clock, one `zephcore_rtc_save` per step — never per evaluation) lives in `MeshTimeSync::runTick()`; when it returns true, the role shifts its wall-clock-anchored bookkeeping by `lastStepDelta()` — repeater: neighbor `heard_timestamp`s and ACL `last_activity`, forward steps only (a backward one is slewed, the clock does not jump); room server: ACL + login limiter. All policy timers (6 h rate limit, 7-day suppression, tenure, sample age) anchor on **uptime, never wall clock** — otherwise the very steps they govern would distort them. @@ -981,7 +981,7 @@ Repeaters and room servers default to `CONFIG_ZEPHCORE_REPEATER_GPS_INTERVAL_SEC **Telemetry** (`REQ_TYPE_GET_TELEMETRY_DATA`, every role, upstream's shape): battery on channel 1, then `sensors.querySensors()` (`adapters/sensors/ZephyrSensorManager.cpp`): GPS position on channel 1 while the GPS is on and has a fix, each environment sensor and power-monitor channel found at boot on its own channel from 2 up (probe order), board-local analog sensors (T1000-E) on channel 1; then the MCU temperature on channel 1 (the SoC's die sensor: the `die-temp0` alias, which is `coretemp` on ESP32-S3/C3/C6, else the Nordic nodelabel `temp`; omitted where there is none: classic ESP32, STM32WL, MG24). Servers give guests battery + MCU temperature only and honour the requester's inverse permission mask, as upstream. Encoded by `helpers/compat/CayenneLPP.h`: upstream's library API and wire format, but values round to the nearest step where the library truncates. -**Clock** (`adapters/clock/ZephyrRTCClock`): `setCurrentTime()` also writes the hardware RTC when the board has one (coalesced on the system work queue; a time outside 2000-2099 is not written), as upstream's `AutoDiscoverRTCClock` writes its chip; `seedCurrentTime()` is the boot restore, not written back. A chip is adopted at boot only once it is identified (`adapters/clock/ZephyrRTCDiscover.c`), because other parts can answer at the same address: a device is passed over when two reads each show a bit set that the chip's data sheet fixes at zero, or a time field out of range, and a time is restored only from a read in which every field is valid. An RV-3028 cleanly identified in 12-hour mode has its `twelve-hour-bit` cleared first, so the chip converts its own hours. No time is taken from a cleanly identified RV-3028 whose `twelve-hour-bit` register cannot be read or reads FFh, or whose clear or re-read fails. The time is written in each chip's own encoding (the RX8130CE takes a one-hot weekday, `weekday-one-hot` in its descriptor), and an RV-3028 whose descriptor carries `rv3028-eeprom-config` (the RAK12002 on a RAK4631) has that configuration, its backup switchover, stored in the chip's EEPROM. Without a hardware RTC, the last time read is kept in no-init memory (RTC slow memory on ESP32) and restored after a reset that keeps RAM (reboot, crash, watchdog), as upstream's `ESP32RTCClock`; a power cycle starts from 1970 again. +**Clock** (`adapters/clock/ZephyrRTCClock`): `setCurrentTime()` also writes the hardware RTC when the board has one (coalesced on the system work queue; a time outside 2000-2099 is not written), as upstream's `AutoDiscoverRTCClock` writes its chip; `seedCurrentTime()` is the boot restore, not written back. A chip is adopted at boot only once it is identified (`adapters/clock/ZephyrRTCDiscover.c`), because other parts can answer at the same address: a device is passed over when two reads each show a bit set that the chip's data sheet fixes at zero, or a time field out of range, and a time is restored only from a read in which every field is valid. An RV-3028 cleanly identified in 12-hour mode has its `twelve-hour-bit` cleared first, so the chip converts its own hours. No time is taken from a cleanly identified RV-3028 whose `twelve-hour-bit` register cannot be read or reads FFh, or whose clear or re-read fails. The time is written in each chip's own encoding (the RX8130CE takes a one-hot weekday, `weekday-one-hot` in its descriptor), and an RV-3028 whose descriptor carries `rv3028-eeprom-config` (the RAK12002 on a RAK4631) has that configuration, its backup switchover, stored in the chip's EEPROM. Without a hardware RTC, the last time read is kept in no-init memory (RTC slow memory on ESP32) and restored after a reset that keeps RAM (reboot, crash, watchdog), as upstream's `ESP32RTCClock`; a power cycle starts from 1970 again. `setCurrentTime()` steps to a time at or after the current second and slews to an earlier one (`helpers/ClockSlew.h`, ADR 0013): the clock runs at 11/12 until the lead is gone, never back; a new set during a slew starts from the time shown. The chip is written on a step and once a slew has finished; the no-init backup holds the time shown. `resetCurrentTime()` steps back (`clkreboot` only). The wall clock is the epoch offset plus kernel uptime, so it is as accurate as the system clock: the 32 kHz crystal on nRF52 (+15 to +19 ppm measured on a Wio Tracker L1) and the 40 MHz crystal on ESP32 awake (+24 ppm on a XIAO ESP32-S3), but in ESP32 light sleep the internal RC slow clock, which ran +170 to +490 ppm fast (LLD 13 §17). **LED master switch** (`helpers/led_gate.{c,h}`, `set leds on|off`, all roles): one process-wide flag every LED driver consults — heartbeat and unread-message LEDs in `helpers/ui/ui_common.c`, the @@ -1314,7 +1314,7 @@ The full set (~50 opcodes, `0x01`–`0x42`) is defined at the top of `app/Compan | 0x01 | CMD_APP_START | app version + name (session start) | | 0x02 | CMD_SEND_TXT_MSG | txt_type + attempt + timestamp + pubkey_prefix + text | | 0x04 | CMD_GET_CONTACTS | [optional 4B `since` lastmod filter] | -| 0x05 / 0x06 | CMD_GET/SET_DEVICE_TIME | (none) / 4B epoch (forward-only) | +| 0x05 / 0x06 | CMD_GET/SET_DEVICE_TIME | (none) / 4B epoch (later: step; earlier: slewed, ADR 0013; before the build day: ERR) | | 0x07 | CMD_SEND_SELF_ADVERT | [optional type byte: flood/zero-hop] | | 0x08 | CMD_SET_ADVERT_NAME | name string | | 0x0A | CMD_SYNC_NEXT_MESSAGE | (none) — offline queue peek/confirm | diff --git a/docs/CLI_commands.md b/docs/CLI_commands.md index abe6ad3..0c05060 100644 --- a/docs/CLI_commands.md +++ b/docs/CLI_commands.md @@ -44,7 +44,7 @@ The text CLI of every ZephCore role. Commands are sent over USB serial (CDC-ACM) | `start dfu` | *(ZephCore only)* nRF52: reboot into the UF2 bootloader for drag-and-drop update. ESP32-S3: reboot into the ROM download mode on USB-Serial-JTAG (`303a:1001`), so ordinary `esptool write-flash` and browser flashers can reach the chip. Every other chip replies with an error and does **not** reboot — ESP32-C3/C6 and classic ESP32 never lose the port to USB OTG so esptool resets them itself, and nRF54L15/MG24/STM32WL have no USB device peripheral and are flashed over SWD | | `start ota` | nRF52: reboot into BLE OTA DFU mode. ESP32 repeater (S3/C-series): start the WiFi AP + HTTP OTA server, `Started: http://192.168.100.1/update`. ESP32 companion built with `--sysbuild` (releases; not the Heltec V3, Wireless Tracker or the C6 boards): open the BLE OTA window, `BLE OTA open for 600 s`; a passkey-bonded nRF Connect Device Manager uploads `-update.bin` and resets the node; the window stays open while an upload runs. Again while open: `BLE OTA already open ( s left)`. Every other build replies `Err: no OTA in this build - flash over USB` and does **not** reboot | | `stop ota` | *(ZephCore only)* ESP32: stop the WiFi OTA server (`OTA stopped`) or close the BLE OTA window (`BLE OTA closed`); `OTA not active` when nothing is open, `Not supported` elsewhere | -| `clkreboot` | Set clock to a fixed reference time (15 May 2024 8:50pm UTC) then reboot. On a board with a hardware RTC the reference time is written to the chip too, as upstream, so the reset survives the reboot | +| `clkreboot` | Set clock to a fixed reference time (15 May 2024 8:50pm UTC) then reboot. The one command that moves the clock back at once. On a board with a hardware RTC the reference time is written to the chip too, as upstream, so the reset survives the reboot | | `powersaving` / `powersaving on` / `powersaving off` | Upstream's command and replies. On ESP32 light-sleep builds (repeaters of boards with `light_sleep: true`, companions of boards with `light_sleep_companion: true`) it gates light sleep: `off` (persisted) keeps the SoC awake, which also keeps a USB Serial/JTAG console attached; `on` allows sleep again, replying `on - After N s (console window)` while the console window is open, else `on - Immediate effect`. Default **on** on those repeaters, and prefs from firmware that stored the field without acting on it are read as on once. Default **off** on companions: a companion sleeps only after `powersaving on`, and then not while a USB host is attached, the display is on, or a Bluetooth link is not yet encrypted. nRF52/nRF54L: stored, replies `on - Immediate effect` (they always idle in System ON; `off` changes nothing). Other boards: `Board not supported` | --- @@ -54,8 +54,8 @@ The text CLI of every ZephCore role. Commands are sent over USB serial (CDC-ACM) | Command | Description | |---------|-------------| | `clock` | Display current UTC time | -| `clock sync` | Sync clock from the sender's timestamp (only advances, cannot go backwards). Arms the 7-day mesh-time-sync suppression window. | -| `time ` | Set RTC to a specific Unix timestamp (cannot go backwards). Arms the 7-day mesh-time-sync suppression window. | +| `clock sync` | Sync clock from the sender's timestamp. A later time is set at once; an earlier one is slewed (the clock runs at 11/12 speed until it matches, so it never goes back; reply `OK - clock slewing back s`), unless it is before the firmware's build day (`ERR: clock cannot go before the build day`). Arms the 7-day mesh-time-sync suppression window. | +| `time ` | Set RTC to a specific Unix timestamp. A later time is set at once; an earlier one is slewed as for `clock sync` (reply `OK - clock slewing back s`), unless it is before the firmware's build day (`(ERR: clock cannot go before the build day)`). Arms the 7-day mesh-time-sync suppression window. | Every clock set (these commands, GPS, the app, mesh time sync, SNTP) is also written to the board's hardware RTC when it has one, so the time survives a power-off. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index cdaae74..23ce6d2 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -293,8 +293,8 @@ it polls external state. Repeater and room server share one loop (`server_main_c ### 8.2 Time - Two clocks: monotonic milliseconds (all protocol timers) and wall-clock RTC (timestamps only). -- Invariant: wall-clock set paths are **forward-only**, except the GPS fix and `clkreboot`; a backward step mutes - a node mesh-wide. +- Invariant: the wall clock **never goes back**, except at `clkreboot`; a backward step mutes a node mesh-wide. + A set to an earlier time, from any source, is slewed at 1/12 (ADR 0013). - Sources: GPS / manual set > mesh consensus (`MeshTimeSync`, opt-in) > hardware RTC. Every set also writes the hardware RTC when the board has one. diff --git a/docs/MESHTIMESYNC.md b/docs/MESHTIMESYNC.md index d30223c..c439102 100644 --- a/docs/MESHTIMESYNC.md +++ b/docs/MESHTIMESYNC.md @@ -58,30 +58,25 @@ worth watching that dry-run output for a day before (and after) enabling. region of the live mesh has a 60+ node island that is 28 hours fast), your node may step toward them. The damage is bounded to 4 hours per day and every step is visible in the logs and in `get meshtimesync`. -- A backward step mutes this node's own adverts at peers for a window equal - to the step size. It self-heals as their clocks pass the old mark, or - delete + re-add the contact in the app to recover instantly. +- A backward correction is not a step: the clock runs at 11/12 speed until + it reaches the mesh time (an hour takes 12 hours), so it never goes back + and nothing is muted. `get meshtimesync` counts it as a step all the same. - Worst case — a coordinated wrong majority around you: turn it off (`set meshtimesync off`) and set the clock manually, which also arms the 7-day protection. ## Recovery recipe -If the clock ever ends up AHEAD of true time (`time` alone will refuse with -"clock cannot go backwards"): +If the clock ever ends up AHEAD of true time, set the correct time: ``` -set meshtimesync off -clkreboot -(log back in) time -set meshtimesync on ``` -Works over remote admin too. The off/on bracket makes it deterministic (no -bootstrap race), and the manual set arms the 7-day protection anyway. Fresh -adverts take tens of minutes to accumulate after a reboot, so an operator -syncing right after login always wins. +(or `clock sync` from the app). It slews the clock back at 1/12 of real time +instead of stepping it, so nothing is locked out on the way, and arms the +7-day protection like any manual set. A time before the firmware's build day +is still refused; `clkreboot` is the only command that steps the clock back. For the design details (consensus algorithm, security model, why the limits are what they are), see [ARCHITECTURE.md](ARCHITECTURE.md) section 4.9. diff --git a/docs/adr/0013-backward-clock-corrections-slew.md b/docs/adr/0013-backward-clock-corrections-slew.md new file mode 100644 index 0000000..cfa9bf4 --- /dev/null +++ b/docs/adr/0013-backward-clock-corrections-slew.md @@ -0,0 +1,51 @@ +# ADR 0013 — A backward clock correction is slewed, never stepped + +Status: accepted (2026-11-24) + +## Context + +- Every time set but GPS and `clkreboot` was forward-only: the app's set-time (`CMD_SET_DEVICE_TIME`), `time`, + `clock sync`, and meshtimesync on companions and room servers. Upstream MeshCore has the same rule for the app + and CLI. A clock that is ahead could never be pulled back: only `clkreboot`, a reboot and a new set. +- Bench, 2026-11-23/24, against a PC disciplined to a LAN stratum-1 server: every node ran fast. Wio Tracker L1 + +15 to +19 ppm (32 kHz crystal, temperature dependent), XIAO ESP32-S3 +24 ppm awake, +167 ppm in light sleep + with a BLE link and +492 ppm with none (the RC slow clock counts sleep). A sleeping ESP32 gains + about 42 s a day; users saw the app's clock hint come back after every sync. +- A backward step is not an option: replay checks hold the highest timestamp seen from each sender (adverts, + logins, requests), so a node whose clock steps back by Δ is refused for Δ. +- A learned drift correction (a drift file) was rejected: the crystal rate moves with temperature + (-0.034 ppm/°C², -27 ppm at -3 °C) and the light-sleep rate with how the node sleeps. +- Widening the GPS guard and meshtimesync ppm limits by a hand-picked bound was rejected (architect: no + hand-made numbers). + +## Decision + +- `ZephyrRTCClock::setCurrentTime()` steps to a time at or after the current second, and slews to an earlier + one: the clock runs at 11/12 of real time until the lead is gone, then at full speed. The time shown never + decreases. 1/12 is chrony's default `maxslewrate` (83,333 ppm): a 30 s lead is gone in 6 minutes, an hour in + 12 hours. The arithmetic is `helpers/ClockSlew.h`, host-tested. +- A new set during a slew starts from the time shown at that moment: an earlier one restarts the slew towards + it, a later one steps and ends it. A wrong target is therefore undone by the next good set. +- The rule is inside the clock, so every source gets it: the app, `time`, `clock sync`, GPS, SNTP and + meshtimesync. The app, `time` and `clock sync` accept an earlier time unless it is before the firmware's + build day (`FIRMWARE_BUILD_EPOCH`), which is refused as before. +- `clkreboot` keeps stepping back: it calls `RTCClock::resetCurrentTime()` (a `// ZEPHCORE:` addition to the + upstream interface; its default is `setCurrentTime()`). +- The hardware RTC chip is written on a step, and after a slew once it has finished, never with a time still + ahead. The reset-surviving backup in no-init RAM holds the time shown, so a reboot during a slew restarts + from that time and the lead it had left is dropped. +- The repeater no longer shifts its neighbour and client times or resets its rate limiters after a backward + meshtimesync correction: the clock does not jump, so nothing underflows or wedges. +- No cap on the size of a backward correction. meshtimesync keeps its own limits (±1 h, one per 6 h, 7-day + suppression after a manual or GPS set); companions and room servers still skip its backward verdicts. + +## Consequences + +- A fast clock is corrected by any time source without locking anyone out; the "wall clock only moves forward" + invariant now holds for every path but `clkreboot`. +- While a slew runs, timestamps advance 8 % slower and `getCurrentTime()` lags the target by the remaining lead. + The app may keep showing its clock hint until the slew is done (accepted by the architect). +- A wrong backward set (a phone in the wrong time zone) slows the clock until the next correct set instead of + being refused. +- Open: meshtimesync's backward skip on companions and room servers could now be lifted; the GPS guard compares + GPS time with the time shown, not the slew target. diff --git a/docs/adr/README.md b/docs/adr/README.md index f262153..76f126b 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -15,3 +15,4 @@ restructure; most describe decisions taken earlier. The system view is in [../DE | [0008](0008-storage-and-settings-backend.md) | Storage layout, power-loss writes, BLE bonds in NVS | | [0009](0009-wifi-companion-boards.md) | WiFi companion boards and contact counts | | [0011](0011-esp32-companion-ble-ota.md) | ESP32 companions update over BLE with MCUmgr (sysbuild builds; `ble_ota: false` opts a board out) | +| [0013](0013-backward-clock-corrections-slew.md) | A backward clock correction is slewed at 1/12, never stepped; only `clkreboot` steps back | diff --git a/releasenotes/RELEASE_NOTES_1.18.3-zephcore.md b/releasenotes/RELEASE_NOTES_1.18.3-zephcore.md index 8a87425..fa35991 100644 --- a/releasenotes/RELEASE_NOTES_1.18.3-zephcore.md +++ b/releasenotes/RELEASE_NOTES_1.18.3-zephcore.md @@ -1,7 +1,8 @@ # ZephCore 1.18.3-zephcore A failed-login limit that really limits, faster and less colliding transmits on a busy channel, a fix for nodes -that fell silent after 25 days, and a working charger on the LilyGo T-Impulse Plus. +that fell silent after 25 days, clocks that can be set back when they run fast, and a working charger on the +LilyGo T-Impulse Plus. > [!NOTE] > A normal upgrade keeps your identity, settings, contacts and phone pairing. @@ -46,6 +47,18 @@ the `lbt_logging.conf` build option logs every transmit attempt, with how full t The battery now charges on USB without LilyGo's firmware first, the wristband no longer restarts every few minutes on USB (which dropped Bluetooth), and the GPS is switched on rather than off. +## A clock that runs fast can be set back + +Node clocks run a little fast: a second or two a day on most boards, and up to about 40 s a day on an ESP32 with +`powersaving on`. Until now the app and the CLI could only move the clock forward, so a fast node stayed ahead +and the app kept asking to fix the clock. Now **an earlier time is accepted** from the app's time sync, `time` +and `clock sync`: the clock runs at 11/12 speed until it matches instead of jumping back, so adverts, logins and +replay checks keep working on the way. A minute ahead is gone in 12 minutes, an hour in 12 hours. GPS and mesh +time sync correct a fast clock the same way; before, they set it back in one jump, which made the node's +adverts and logins look like replays to the nodes that had heard it. A time before the firmware's build date is +still refused, and `clkreboot` still resets the clock at once. The app may keep showing its clock hint until the +clock has caught up. + ## Fixes - **A node no longer falls silent after 25 days.** If every transmit had gone out at the first try for 25 days, @@ -105,5 +118,6 @@ Details in [CLI_commands.md](../docs/CLI_commands.md). | `get lbt.stats` | New; `clear stats` resets it | | `get/set cad.ceiling` | New: seconds before a packet held back by a busy channel is sent anyway (5-59, default 15) | | `get txdelay` | Shows the neighbour estimate and number of steps | +| `time `, `clock sync` | Accept an earlier time and slew the clock back to it (`OK - clock slewing back s`); only a time before the firmware's build day is refused | | `get/set backoff.multiplier` | Removed; a saved value is ignored | | Remote CLI on a companion | Can run the `gps` commands, `get/set adc.multiplier`, `get/set ble.name` and `get/set buzzer`, as in MeshCore | diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cbcfc80..76b0bf9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -23,6 +23,7 @@ add_executable(zephcore_unit unit/dispatcher_tests.cpp unit/identity_tests.cpp unit/timesync_tests.cpp + unit/clock_slew_tests.cpp unit/helper_tests.cpp unit/radio_tests.cpp unit/sx126x_heltec_tests.cpp diff --git a/tests/unit/clock_slew_tests.cpp b/tests/unit/clock_slew_tests.cpp new file mode 100644 index 0000000..844b6e6 --- /dev/null +++ b/tests/unit/clock_slew_tests.cpp @@ -0,0 +1,94 @@ +#include "test.h" +#include + +namespace { +// Shown time never decreases over [from, to] uptime, sampled every ms. +bool monotonic(const ClockSlew& c, int64_t from, int64_t to) { + int64_t last = c.nowMs(from); + for (int64_t up = from + 1; up <= to; ++up) { + int64_t now = c.nowMs(up); + if (now < last) return false; + last = now; + } + return true; +} +} + +TEST(clockSlewForwardSteps, "clock-slew-forward-steps", "A set at or after the current second steps the clock") { + ClockSlew c; + CHECK(!c.set(2000000, 5000)); + CHECK(c.nowMs(5000) == 2000000000LL); + CHECK(!c.set(2000100, 6000)); + CHECK(c.nowMs(6000) == 2000100000LL); + CHECK(c.remainingMs(6000) == 0); +} + +TEST(clockSlewSameSecond, "clock-slew-same-second", "A set to the current second steps, without a slew") { + ClockSlew c; + c.step(2000000700LL, 0); // shows 2000000.700 s + CHECK(!c.set(2000000, 0)); + CHECK(c.nowMs(0) == 2000000000LL); + CHECK(c.lead_ms == 0); +} + +TEST(clockSlewBackward, "clock-slew-backward", "An earlier time is slewed at 1/12, never stepped back") { + ClockSlew c; + c.step(2000000000LL, 0); + const int64_t up = 100000; // shows 2000100.000 s + CHECK(c.set(2000040, up)); // 60 s lead + CHECK(c.nowMs(up) == 2000100000LL); // nothing moved back + CHECK(c.remainingMs(up) == 60000); + CHECK(c.nowMs(up + 12000) - c.nowMs(up) == 11000); // runs at 11/12 + CHECK(monotonic(c, up, up + 720000 + 5000)); + CHECK(c.remainingMs(up + 720000) == 0); // 60 s lead gone after 12 min + CHECK(c.nowMs(up + 720000) == 2000040000LL + 720000); + CHECK(c.nowMs(up + 730000) - c.nowMs(up + 720000) == 10000); // full speed again +} + +TEST(clockSlewSettle, "clock-slew-settle", "A finished slew folds into the offset once, without a jump") { + ClockSlew c; + c.step(2000000000LL, 0); + CHECK(c.set(1999990, 0)); // 10 s lead, done after 120 s + CHECK(!c.settle(119999)); + int64_t before = c.nowMs(120000); + CHECK(c.settle(120000)); + CHECK(c.nowMs(120000) == before); + CHECK(!c.settle(130000)); + CHECK(c.nowMs(130000) == before + 10000); +} + +TEST(clockSlewRetarget, "clock-slew-retarget", "A new set during a slew starts from the time shown, never back") { + ClockSlew c; + c.step(2000000000LL, 0); + CHECK(c.set(1999700, 0)); // 300 s lead + const int64_t up = 60000; // 5 s removed so far + int64_t shown = c.nowMs(up); + CHECK(shown == 2000055000LL); + CHECK(c.set(2000050, up)); // retarget: 5 s lead from the time shown + CHECK(c.nowMs(up) == shown); + CHECK(c.remainingMs(up) == 5000); + CHECK(monotonic(c, up, up + 70000)); + CHECK(c.remainingMs(up + 60000) == 0); +} + +TEST(clockSlewForwardCancels, "clock-slew-forward-cancels", "A forward set during a slew ends it with a step") { + ClockSlew c; + c.step(2000000000LL, 0); + CHECK(c.set(1999000, 0)); + CHECK(!c.set(2000010, 1000)); + CHECK(c.remainingMs(1000) == 0); + CHECK(c.nowMs(1000) == 2000010000LL); + CHECK(c.nowMs(2000) == 2000011000LL); +} + +TEST(clockSlewSecondsNeverRepeatBackward, "clock-slew-seconds-monotonic", "Whole seconds shown never decrease during a slew") { + ClockSlew c; + c.step(2000000999LL, 0); + CHECK(c.set(1999999, 0)); + int64_t last = c.nowMs(0) / 1000; + for (int64_t up = 1; up <= 30000; ++up) { + int64_t s = c.nowMs(up) / 1000; + CHECK(s >= last); + last = s; + } +} diff --git a/zephcore/adapters/clock/ZephyrRTCClock.cpp b/zephcore/adapters/clock/ZephyrRTCClock.cpp index e32320b..9a21d01 100644 --- a/zephcore/adapters/clock/ZephyrRTCClock.cpp +++ b/zephcore/adapters/clock/ZephyrRTCClock.cpp @@ -21,6 +21,17 @@ static void rtc_save_work_fn(struct k_work *work) } static K_WORK_DEFINE(s_rtc_save_work, rtc_save_work_fn); + +static void rtc_save(ZephyrRTCClock *clock) +{ + s_saved_clock = clock; + k_work_submit(&s_rtc_save_work); +} +#else +static void rtc_save(ZephyrRTCClock *clock) +{ + ARG_UNUSED(clock); +} #endif /* The last time read, kept across a reset that keeps RAM (reboot, crash, @@ -40,40 +51,60 @@ static RTC_BACKUP_ATTR uint32_t _rtc_backup_magic; ZephyrRTCClock::ZephyrRTCClock() { if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > RTC_TIME_MIN) { - epoch_offset = _rtc_backup_time; + slew.step((int64_t)_rtc_backup_time * 1000, 0); } } uint32_t ZephyrRTCClock::getCurrentTime() { - uint32_t uptime_sec = (uint32_t)(k_uptime_get() / 1000); - uint32_t now = epoch_offset + uptime_sec; + k_spinlock_key_t key = k_spin_lock(&lock); + int64_t up = k_uptime_get(); + bool settled = slew.settle(up); + uint32_t now = (uint32_t)(slew.nowMs(up) / 1000); /* upstream does this in tick(), which nothing calls here */ if (now > RTC_TIME_MIN && now != _rtc_backup_time) { _rtc_backup_time = now; _rtc_backup_magic = RTC_BACKUP_MAGIC; } + k_spin_unlock(&lock, key); + if (settled) { + rtc_save(this); + } return now; } void ZephyrRTCClock::seedCurrentTime(uint32_t time) { - uint32_t uptime_sec = (uint32_t)(k_uptime_get() / 1000); - epoch_offset = time - uptime_sec; + k_spinlock_key_t key = k_spin_lock(&lock); + + slew.step((int64_t)time * 1000, k_uptime_get()); /* As upstream's setCurrentTime(): unconditional, so a set below * RTC_TIME_MIN (clkreboot) replaces the backup and is not restored. */ _rtc_backup_time = time; _rtc_backup_magic = RTC_BACKUP_MAGIC; + k_spin_unlock(&lock, key); } void ZephyrRTCClock::setCurrentTime(uint32_t time) +{ + k_spinlock_key_t key = k_spin_lock(&lock); + bool slewing = slew.set(time, k_uptime_get()); + + if (!slewing) { + _rtc_backup_time = time; + _rtc_backup_magic = RTC_BACKUP_MAGIC; + } + k_spin_unlock(&lock, key); + if (!slewing) { + rtc_save(this); + } +} + +void ZephyrRTCClock::resetCurrentTime(uint32_t time) { seedCurrentTime(time); -#if DT_HAS_COMPAT_STATUS_OKAY(zephcore_rtc_i2c) - s_saved_clock = this; - k_work_submit(&s_rtc_save_work); -#endif + rtc_save(this); } } /* namespace mesh */ diff --git a/zephcore/adapters/clock/ZephyrRTCClock.h b/zephcore/adapters/clock/ZephyrRTCClock.h index e3214fb..1d0713c 100644 --- a/zephcore/adapters/clock/ZephyrRTCClock.h +++ b/zephcore/adapters/clock/ZephyrRTCClock.h @@ -6,6 +6,8 @@ #pragma once #include +#include +#include namespace mesh { @@ -14,15 +16,21 @@ public: /* Starts from the time kept across the last reset, if any (see the .cpp). */ ZephyrRTCClock(); uint32_t getCurrentTime() override; - /* Also written to the board's hardware RTC, if it has one, as upstream's + /* A time at or after the current second steps the clock; an earlier one + * is slewed (helpers/ClockSlew.h), so the clock never goes back. Also + * written to the board's hardware RTC, if it has one, as upstream's * AutoDiscoverRTCClock does: coalesced on the system work queue, so - * callers on any thread pay no I2C. */ + * callers on any thread pay no I2C. A slewed time is written once the + * slew is done. */ void setCurrentTime(uint32_t time) override; + /* Steps to any time, backward too (clkreboot). */ + void resetCurrentTime(uint32_t time) override; /* Boot only: the time just read from the hardware RTC, not written back. */ void seedCurrentTime(uint32_t time); private: - uint32_t epoch_offset = 0; + ClockSlew slew; + struct k_spinlock lock; }; } /* namespace mesh */ diff --git a/zephcore/app/CompanionMesh.cpp b/zephcore/app/CompanionMesh.cpp index ae3f2e8..48e0e62 100644 --- a/zephcore/app/CompanionMesh.cpp +++ b/zephcore/app/CompanionMesh.cpp @@ -2186,8 +2186,9 @@ bool CompanionMesh::handleCmdSetDeviceTime(const uint8_t *data, size_t len) uint32_t secs = get_le32(&data[1]); uint32_t curr = getRTCClock()->getCurrentTime(); - // Arduino: only allow setting time forward (prevents time attacks) - if (secs >= curr) { + /* Forward steps; backward slews (ADR 0013), but not to before + * the firmware's build day. */ + if (secs >= curr || secs >= FIRMWARE_BUILD_EPOCH) { getRTCClock()->setCurrentTime(secs); time_sync_report(TIME_SYNC_APP); _timesync.noteManualSync((uint32_t)(k_uptime_get() / 1000)); diff --git a/zephcore/app/RepeaterMesh.cpp b/zephcore/app/RepeaterMesh.cpp index 2a72e16..e98619f 100644 --- a/zephcore/app/RepeaterMesh.cpp +++ b/zephcore/app/RepeaterMesh.cpp @@ -1689,26 +1689,21 @@ void RepeaterMesh::timeSyncTick() { if (!_prefs.meshtimesync) return; if (!_timesync.runTick(*getRTCClock())) return; - /* Step applied — wall-clock-anchored bookkeeping must move with it, or a - * backward step underflows the unsigned "seconds ago" math. 0 = unset - * sentinel. */ + /* A forward step moves wall-clock-anchored bookkeeping with it. A backward + * correction is slewed (the clock never goes back), so those stamps stay. + * 0 = unset sentinel. */ int64_t delta = _timesync.lastStepDelta(); + if (delta > 0) { #if MAX_NEIGHBOURS > 0 - for (int i = 0; i < MAX_NEIGHBOURS; i++) { - if (neighbours[i].heard_timestamp == 0) continue; - int64_t shifted = (int64_t)neighbours[i].heard_timestamp + delta; - neighbours[i].heard_timestamp = (shifted > 0) ? (uint32_t)shifted : 1; - } + for (int i = 0; i < MAX_NEIGHBOURS; i++) { + if (neighbours[i].heard_timestamp == 0) continue; + neighbours[i].heard_timestamp += (uint32_t)delta; + } #endif - for (int i = 0; i < acl.getNumClients(); i++) { - ClientInfo* c = acl.getClientByIdx(i); - if (c->last_activity == 0) continue; - int64_t shifted = (int64_t)c->last_activity + delta; - c->last_activity = (shifted > 0) ? (uint32_t)shifted : 1; + for (int i = 0; i < acl.getNumClients(); i++) { + ClientInfo* c = acl.getClientByIdx(i); + if (c->last_activity == 0) continue; + c->last_activity += (uint32_t)delta; + } } - /* A backward step would otherwise wedge these shut until wall-clock - * catch-up. */ - discover_limiter.reset(); - anon_limiter.reset(); - login_fail_limiter.reset(); } diff --git a/zephcore/boards/common/pm_esp32.conf b/zephcore/boards/common/pm_esp32.conf index 976f53e..a236022 100644 --- a/zephcore/boards/common/pm_esp32.conf +++ b/zephcore/boards/common/pm_esp32.conf @@ -66,7 +66,9 @@ # Kernel time is safe across sleep: the Xtensa/ESP32 timer drivers implement # the LPM hooks (esp32_lptim_hook_on_lpm_entry/exit) that read the RTC counter # and announce elapsed ticks, so k_uptime_get() and every maintenance deadline -# stay correct. +# stay correct. The time asleep is counted by the internal RC slow clock, so +# the wall clock runs fast while the node sleeps: +170 to +490 ppm measured on +# the XIAO (devdocs/lld/13-power-management.md, section 17). CONFIG_PM=y diff --git a/zephcore/helpers/ClockSlew.h b/zephcore/helpers/ClockSlew.h new file mode 100644 index 0000000..c3f6f9b --- /dev/null +++ b/zephcore/helpers/ClockSlew.h @@ -0,0 +1,67 @@ +/* + * SPDX-License-Identifier: MIT + * Wall clock as an offset from uptime, in milliseconds. A set at or after the + * current second steps the clock; an earlier one is slewed: the clock runs at + * 11/12 speed until the lead is gone, so it never goes back (ADR 0013). + * Pure arithmetic, no locking: ZephyrRTCClock holds the lock. + */ + +#pragma once + +#include + +struct ClockSlew { + /* A slew removes 1 ms per 12 ms of uptime: chrony's default maxslewrate. */ + static constexpr int64_t RATE_DIV = 12; + + int64_t offset_ms = 0; /* wall = offset_ms + uptime - removed() */ + int64_t lead_ms = 0; /* backward correction of the current slew */ + int64_t start_ms = 0; /* uptime at which it began */ + + int64_t removed(int64_t up_ms) const + { + int64_t r = (up_ms - start_ms) / RATE_DIV; + + return r < lead_ms ? r : lead_ms; + } + + int64_t nowMs(int64_t up_ms) const { return offset_ms + up_ms - removed(up_ms); } + + /* Lead still to remove. */ + int64_t remainingMs(int64_t up_ms) const { return lead_ms - removed(up_ms); } + + void step(int64_t target_ms, int64_t up_ms) + { + offset_ms = target_ms - up_ms; + lead_ms = 0; + } + + /* Steps to target_s when it is not before the current second, else + * (re)starts a slew to it from the time shown now. Returns true when + * slewing. */ + bool set(uint32_t target_s, int64_t up_ms) + { + int64_t now = nowMs(up_ms); + int64_t target = (int64_t)target_s * 1000; + + if ((int64_t)target_s >= now / 1000) { + step(target, up_ms); + return false; + } + offset_ms = now - up_ms; + lead_ms = now - target; + start_ms = up_ms; + return true; + } + + /* Folds a finished slew into the offset. Returns true once, when it does. */ + bool settle(int64_t up_ms) + { + if (lead_ms == 0 || removed(up_ms) < lead_ms) { + return false; + } + offset_ms -= lead_ms; + lead_ms = 0; + return true; + } +}; diff --git a/zephcore/helpers/CommonCLI.cpp b/zephcore/helpers/CommonCLI.cpp index bf112cb..c5d9e3a 100644 --- a/zephcore/helpers/CommonCLI.cpp +++ b/zephcore/helpers/CommonCLI.cpp @@ -426,7 +426,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch strcpy(reply, "OK - rebooting"); scheduleReboot(REBOOT_NORMAL); } else if (memcmp(command, "clkreboot", 9) == 0) { - getRTCClock()->setCurrentTime(1715770351); // 15 May 2024, 8:50pm + getRTCClock()->resetCurrentTime(1715770351); // 15 May 2024, 8:50pm /* Deferred like every other reboot path: called inline this reset the * board before the reply — and before any delivery-ack — could leave * the TX queue. */ @@ -440,18 +440,24 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch strcpy(reply, "OK - Advert sent"); } else if (memcmp(command, "clock sync", 10) == 0) { uint32_t curr = getRTCClock()->getCurrentTime(); - if (sender_timestamp > curr) { - getRTCClock()->setCurrentTime(sender_timestamp + 1); + uint32_t target = sender_timestamp + 1; + if (sender_timestamp > curr || target >= FIRMWARE_BUILD_EPOCH) { + getRTCClock()->setCurrentTime(target); time_sync_report(TIME_SYNC_CLI); MeshTimeSync* ts = _callbacks->getMeshTimeSync(); if (ts) ts->noteManualSync((uint32_t)(k_uptime_get() / 1000)); - uint32_t now = getRTCClock()->getCurrentTime(); - time_t t = (time_t)now; - struct tm *tm = gmtime(&t); - snprintf(reply, CLI_REPLY_SIZE, "OK - clock set: %02d:%02d - %d/%d/%d UTC", - tm->tm_hour, tm->tm_min, tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900); + if (target < curr) { + snprintf(reply, CLI_REPLY_SIZE, "OK - clock slewing back %u s", + (unsigned)(curr - target)); + } else { + uint32_t now = getRTCClock()->getCurrentTime(); + time_t t = (time_t)now; + struct tm *tm = gmtime(&t); + snprintf(reply, CLI_REPLY_SIZE, "OK - clock set: %02d:%02d - %d/%d/%d UTC", + tm->tm_hour, tm->tm_min, tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900); + } } else { - strcpy(reply, "ERR: clock cannot go backwards"); + strcpy(reply, "ERR: clock cannot go before the build day"); } } else if (memcmp(command, "clock", 5) == 0) { uint32_t now = getRTCClock()->getCurrentTime(); @@ -462,17 +468,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch } else if (memcmp(command, "time ", 5) == 0) { uint32_t secs = _atoi(&command[5]); uint32_t curr = getRTCClock()->getCurrentTime(); - if (secs > curr) { + if (secs > curr || secs >= FIRMWARE_BUILD_EPOCH) { getRTCClock()->setCurrentTime(secs); time_sync_report(TIME_SYNC_CLI); MeshTimeSync* ts = _callbacks->getMeshTimeSync(); if (ts) ts->noteManualSync((uint32_t)(k_uptime_get() / 1000)); - time_t t = (time_t)secs; - struct tm *tm = gmtime(&t); - snprintf(reply, CLI_REPLY_SIZE, "OK - clock set: %02d:%02d - %d/%d/%d UTC", - tm->tm_hour, tm->tm_min, tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900); + if (secs < curr) { + snprintf(reply, CLI_REPLY_SIZE, "OK - clock slewing back %u s", + (unsigned)(curr - secs)); + } else { + time_t t = (time_t)secs; + struct tm *tm = gmtime(&t); + snprintf(reply, CLI_REPLY_SIZE, "OK - clock set: %02d:%02d - %d/%d/%d UTC", + tm->tm_hour, tm->tm_min, tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900); + } } else { - strcpy(reply, "(ERR: clock cannot go backwards)"); + strcpy(reply, "(ERR: clock cannot go before the build day)"); } #ifndef ZEPHCORE_COMPANION /* no region map on a companion */ } else if (_region_map && memcmp(command, "region", 6) == 0) { diff --git a/zephcore/include/mesh/MeshCore.h b/zephcore/include/mesh/MeshCore.h index 6124a50..90aca73 100644 --- a/zephcore/include/mesh/MeshCore.h +++ b/zephcore/include/mesh/MeshCore.h @@ -124,6 +124,10 @@ public: */ virtual void setCurrentTime(uint32_t time) = 0; + // ZEPHCORE: setCurrentTime() never moves the clock back (it slews); this + // steps to any time, for clkreboot. + virtual void resetCurrentTime(uint32_t time) { setCurrentTime(time); } + /** * override in classes that need to periodically update internal state */