libpayload/libc/time: Fix possible overflow in multiplication
The value from raw_read_cntfrq_el0() could be large enough to cause overflow when multiplied by USECS_PER_SEC. To prevent this, both USECS_PER_SEC and hz can be reduced by dividing them by their GCD. This patch also modifies the return type of `timer_hz()` from `uint64_t` to `uint32_t`, assuming that in practice the timestamp counter should never be that fast. BUG=b:307790895 TEST=boot to kernel and check the timestamps from `cbmem` Change-Id: Ia55532490651fcf47128b83a8554751f050bcc89 Signed-off-by: Yidi Lin <yidilin@chromium.org> Reviewed-on: https://review.coreboot.org/c/coreboot/+/78888 Reviewed-by: Julius Werner <jwerner@chromium.org> Reviewed-by: Yu-Ping Wu <yupingso@google.com> Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
This commit is contained in:
@ -38,6 +38,7 @@
|
||||
#if CONFIG(LP_ARCH_X86) && CONFIG(LP_NVRAM)
|
||||
#include <arch/rdtsc.h>
|
||||
#endif
|
||||
#include <commonlib/bsd/gcd.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
extern u32 cpu_khz;
|
||||
@ -170,17 +171,21 @@ void arch_ndelay(uint64_t ns)
|
||||
|
||||
u64 timer_us(u64 base)
|
||||
{
|
||||
static u64 hz;
|
||||
static u32 hz, mult = USECS_PER_SEC;
|
||||
u32 div;
|
||||
|
||||
// Only check timer_hz once. Assume it doesn't change.
|
||||
if (hz == 0) {
|
||||
hz = timer_hz();
|
||||
if (hz < 1000000) {
|
||||
printf("Timer frequency %" PRIu64 " is too low, "
|
||||
if (hz < mult) {
|
||||
printf("Timer frequency %" PRIu32 " is too low, "
|
||||
"must be at least 1MHz.\n", hz);
|
||||
halt();
|
||||
}
|
||||
div = gcd32(hz, mult);
|
||||
hz /= div;
|
||||
mult /= div;
|
||||
}
|
||||
|
||||
return (1000000 * timer_raw_value()) / hz - base;
|
||||
return (mult * timer_raw_value()) / hz - base;
|
||||
}
|
||||
|
Reference in New Issue
Block a user