[riot-notifications] [RIOT-OS/RIOT] sys/ztimer: Potential footgun when mixing timestamps of ztimer clocks (#16698)

Marian Buschsieweke notifications at github.com
Tue Aug 3 09:15:43 CEST 2021

#### Description

Each ztimer clock can potentially be backed by different hardware. E.g. on a given system `ZTIMER_USEC` could use `periph_timer` as backend, while `ZTIMER_MSEC` could use `periph_rtt` as backend. A call to `ztimer_now()` will give the current counter value of the underlying hardware (after first applying frequency conversion and bit extension as needed). When comparing timestamps of different clocks this can be problematic (that is, after converting them to the same time unit), because:

1. Each hardware clock's epoch might be different. E.g. after a warm boot the RTT might resume counting from the value it had, while the high frequency timer will be reinitialized with zero.
2. Clocks will drift in regard to each other

#### Steps to reproduce the issue

static ztimer_now_t point_in_time_a_us;
static ztimer_now_t point_in_time_b_ms;
static ztimer_now_t point_in_time_c_ms;

static void event_a_callback(void) {
    point_in_time_a_us = ztimer_now(ZTIMER_USEC);

static void event_b_callback(void) {
    point_in_time_b_ms = ztimer_now(ZTIMER_MSEC);

static void event_c_callback(void) {
    point_in_time_c_ms = ztimer_now(ZTIMER_MSEC);
    ztimer_now_t duration_a_b_us = point_in_time_b_ms * USEC_PER_MSEC - point_in_time_a_us;
    ztimer_now_t duration_b_c_ms = point_in_time_c_ms - point_in_time_b_ms;

#### Expected results

Both `duration_a_b_us` and `duration_b_c_ms` are correct.

#### Actual results

If `ZTIMER_MSEC` and `ZTIMER_USEC` are not provided by the same hardware clock, `duration_a_b_us` will likely be incorrect.

#### Versions

Current `master`.

You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.riot-os.org/pipermail/notifications/attachments/20210803/017b53f9/attachment.htm>

More information about the notifications mailing list