-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Description
Describe the bug
This codeline in time_units.h has an issue when
the to_hz argument is larger than the from_hz argument, and the timestamp t is larger than (UINT64_MAX / to_hz).
When using the gettimeofday() function this will happen once k_uptime_ticks() returns a value larger than (UINT64_MAX / to_hz), which equals about 6.4 days on the nRF52 platform where to_hz is a billion and from_hz is 32768:
UINT64_MAX / 1.000.000.000 / 32768 / 3600 = 152 hours = 6.4 days
To Reproduce
When running the gettimeofday sample the printed time and date should roll over after 6.4 days.
If there is a way to alter the runtime to a number just below UINT64_MAX / 1.000.000.000 it can reproduced quicker ;)
Suggested fix
The problem looks to be the fact that t is multiplied with to_hz first, and then divided, giving you a very large intermediary value which can overflow the 64-bit variable.
It should be possible to change the formula like this, in order to avoid the large intermediary value without losing accuracy:
return ((t+ off) / from_hz) * to_hz + (((t % from_hz) * to_hz+ off) / from_hz);