Skip to content

sys/ztimer: Potential footgun when mixing timestamps of ztimer clocks #16698

@maribu

Description

@maribu

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.

Metadata

Metadata

Labels

Area: sysArea: SystemArea: timersArea: timer subsystemsProcess: API changeIntegration Process: PR contains or issue proposes an API change. Should be handled with care.State: don't staleState: Tell state-bot to ignore this issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions