arch/arm64/arch_timer: 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 tfreq can be reduced by dividing them by their GCD.

BUG=b:307790895
TEST=emerge-geralt coreboot
TEST=boot to kernel and check the timestamps from `cbmem`

Change-Id: I366667de05392913150414f0fa9058725be71c52
Signed-off-by: Yidi Lin <yidilin@chromium.org>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/78800
Reviewed-by: Yu-Ping Wu <yupingso@google.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
This commit is contained in:
Yidi Lin 2023-10-31 18:50:06 +08:00 committed by Martin L Roth
parent da1a0e891b
commit 85d7809e0c
1 changed files with 20 additions and 3 deletions

View File

@ -1,12 +1,29 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#include <timer.h>
#include <arch/lib_helpers.h>
#include <commonlib/bsd/gcd.h>
#include <timer.h>
void timer_monotonic_get(struct mono_time *mt)
{
uint64_t tvalue = raw_read_cntpct_el0();
uint32_t tfreq = raw_read_cntfrq_el0();
long usecs = (tvalue * 1000000) / tfreq;
static uint32_t tfreq, mult;
uint32_t div;
/*
* 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 tfreq can be reduced by dividing them by
* their GCD.
*/
if (tfreq == 0) {
tfreq = raw_read_cntfrq_el0();
mult = USECS_PER_SEC;
div = gcd32(tfreq, mult);
tfreq /= div;
mult /= div;
}
long usecs = (tvalue * mult) / tfreq;
mono_time_set_usecs(mt, usecs);
}