[PATCH] cpucounter: Increase conversion accuracy

Gedare Bloom gedare at rtems.org
Tue Jan 26 15:46:37 UTC 2021


The reasoning about the math looks safe. I'm not competent to judge its
correctness :)

On Tue, Jan 26, 2021 at 8:11 AM Sebastian Huber <
sebastian.huber at embedded-brains.de> wrote:

> The maximum frequency is UINT32_MAX.  Converted to a uint64_t variable
> it can be shifted by 32.  The addition does not overflow since bin_per_s
> - 1 is UINT32_MAX.
> ---
>  cpukit/sapi/src/cpucounterconverter.c | 7 ++++---
>  1 file changed, 4 insertions(+), 3 deletions(-)
>
> diff --git a/cpukit/sapi/src/cpucounterconverter.c
> b/cpukit/sapi/src/cpucounterconverter.c
> index 08a745dfc6..88403987d2 100644
> --- a/cpukit/sapi/src/cpucounterconverter.c
> +++ b/cpukit/sapi/src/cpucounterconverter.c
> @@ -42,19 +42,20 @@ int64_t rtems_counter_ticks_to_sbintime(
> rtems_counter_ticks ticks )
>
>  rtems_counter_ticks rtems_counter_sbintime_to_ticks( int64_t sbt )
>  {
> -  return (rtems_counter_ticks) (((uint64_t) sbt * from_sbt_scaler) >> 31);
> +  return (rtems_counter_ticks) (((uint64_t) sbt * from_sbt_scaler) >> 32);
>  }
>
>  void rtems_counter_initialize_converter( uint32_t frequency )
>  {
>    uint64_t ns_per_s = UINT64_C(1000000000);
>    uint64_t bin_per_s = UINT64_C(1) << 32;
> +  uint64_t bin_freq = (uint64_t) frequency << 32;
>
>    to_ns_scaler = ((ns_per_s << 32) + frequency - 1) / frequency;
> -  from_ns_scaler = ((UINT64_C(1) << 32) * frequency + ns_per_s - 1) /
> ns_per_s;
> +  from_ns_scaler = (bin_freq + ns_per_s - 1) / ns_per_s;
>
>    to_sbt_scaler = ((bin_per_s << 31) + frequency - 1) / frequency;
> -  from_sbt_scaler = ((UINT64_C(1) << 31) * frequency + bin_per_s - 1) /
> bin_per_s;
> +  from_sbt_scaler = (bin_freq + bin_per_s - 1) / bin_per_s;
>  }
>
>  static void rtems_counter_sysinit( void )
> --
> 2.26.2
>
> _______________________________________________
> devel mailing list
> devel at rtems.org
> http://lists.rtems.org/mailman/listinfo/devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.rtems.org/pipermail/devel/attachments/20210126/7b853b2e/attachment.html>


More information about the devel mailing list