source: rtems/cpukit/sapi/src/cpucounterconverter.c @ c734e86

Last change on this file since c734e86 was c734e86, checked in by Sebastian Huber <sebastian.huber@…>, on Jan 8, 2021 at 10:59:40 AM

cpucounter: Increase conversion accuracy

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.
  • Property mode set to 100644
File size: 1.8 KB
RevLine 
[24bf11e]1/*
[65f868c]2 * Copyright (c) 2014, 2018 embedded brains GmbH.  All rights reserved.
[24bf11e]3 *
4 *  embedded brains GmbH
5 *  Dornierstr. 4
6 *  82178 Puchheim
7 *  Germany
8 *  <rtems@embedded-brains.de>
9 *
10 * The license and distribution terms for this file may be
11 * found in the file LICENSE in this distribution or at
[c499856]12 * http://www.rtems.org/license/LICENSE.
[24bf11e]13 */
14
15#include <rtems/counter.h>
[65f868c]16#include <rtems/sysinit.h>
[24bf11e]17
18RTEMS_STATIC_ASSERT(sizeof(rtems_counter_ticks) <= sizeof(uint32_t), type);
19
[65f868c]20static uint64_t to_ns_scaler;
[24bf11e]21
[65f868c]22static uint64_t from_ns_scaler;
[24bf11e]23
[b9ffb624]24static uint64_t to_sbt_scaler;
25
26static uint64_t from_sbt_scaler;
27
28uint64_t rtems_counter_ticks_to_nanoseconds( rtems_counter_ticks ticks )
[24bf11e]29{
[b9ffb624]30  return (uint32_t) ((ticks * to_ns_scaler) >> 32);
[24bf11e]31}
32
33rtems_counter_ticks rtems_counter_nanoseconds_to_ticks( uint32_t nanoseconds )
34{
35  return (rtems_counter_ticks) ((nanoseconds * from_ns_scaler) >> 32);
36}
37
[b9ffb624]38int64_t rtems_counter_ticks_to_sbintime( rtems_counter_ticks ticks )
39{
40  return (int64_t) ((ticks * to_sbt_scaler) >> 31);
41}
42
43rtems_counter_ticks rtems_counter_sbintime_to_ticks( int64_t sbt )
44{
[c734e86]45  return (rtems_counter_ticks) (((uint64_t) sbt * from_sbt_scaler) >> 32);
[b9ffb624]46}
47
[24bf11e]48void rtems_counter_initialize_converter( uint32_t frequency )
49{
50  uint64_t ns_per_s = UINT64_C(1000000000);
[b9ffb624]51  uint64_t bin_per_s = UINT64_C(1) << 32;
[c734e86]52  uint64_t bin_freq = (uint64_t) frequency << 32;
[24bf11e]53
54  to_ns_scaler = ((ns_per_s << 32) + frequency - 1) / frequency;
[c734e86]55  from_ns_scaler = (bin_freq + ns_per_s - 1) / ns_per_s;
[b9ffb624]56
57  to_sbt_scaler = ((bin_per_s << 31) + frequency - 1) / frequency;
[c734e86]58  from_sbt_scaler = (bin_freq + bin_per_s - 1) / bin_per_s;
[24bf11e]59}
[65f868c]60
61static void rtems_counter_sysinit( void )
62{
63  rtems_counter_initialize_converter( rtems_counter_frequency() );
64}
65
66RTEMS_SYSINIT_ITEM(
67  rtems_counter_sysinit,
68  RTEMS_SYSINIT_CPU_COUNTER,
[c344e58]69  RTEMS_SYSINIT_ORDER_LAST_BUT_5
[65f868c]70);
Note: See TracBrowser for help on using the repository browser.