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 01/08/21 at 10:59:40

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
Line 
1/*
2 * Copyright (c) 2014, 2018 embedded brains GmbH.  All rights reserved.
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
12 * http://www.rtems.org/license/LICENSE.
13 */
14
15#include <rtems/counter.h>
16#include <rtems/sysinit.h>
17
18RTEMS_STATIC_ASSERT(sizeof(rtems_counter_ticks) <= sizeof(uint32_t), type);
19
20static uint64_t to_ns_scaler;
21
22static uint64_t from_ns_scaler;
23
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 )
29{
30  return (uint32_t) ((ticks * to_ns_scaler) >> 32);
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
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{
45  return (rtems_counter_ticks) (((uint64_t) sbt * from_sbt_scaler) >> 32);
46}
47
48void rtems_counter_initialize_converter( uint32_t frequency )
49{
50  uint64_t ns_per_s = UINT64_C(1000000000);
51  uint64_t bin_per_s = UINT64_C(1) << 32;
52  uint64_t bin_freq = (uint64_t) frequency << 32;
53
54  to_ns_scaler = ((ns_per_s << 32) + frequency - 1) / frequency;
55  from_ns_scaler = (bin_freq + ns_per_s - 1) / ns_per_s;
56
57  to_sbt_scaler = ((bin_per_s << 31) + frequency - 1) / frequency;
58  from_sbt_scaler = (bin_freq + bin_per_s - 1) / bin_per_s;
59}
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,
69  RTEMS_SYSINIT_ORDER_LAST_BUT_5
70);
Note: See TracBrowser for help on using the repository browser.