• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <stddef.h>
17 #include <stdint.h>
18 
19 #include "pw_preprocessor/util.h"
20 
21 // The backend implements this header to provide the following SystemClock
22 // parameters, for more detail on the parameters see the SystemClock usage of
23 // them below:
24 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_NUMERATOR
25 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_DENOMINATOR
26 //   constexpr pw::chrono::Epoch pw::chrono::backend::kSystemClockEpoch;
27 //   constexpr bool pw::chrono::backend::kSystemClockFreeRunning;
28 //   constexpr bool pw::chrono::backend::kSystemClockNmiSafe;
29 #include "pw_chrono_backend/system_clock_config.h"
30 
31 #ifdef __cplusplus
32 
33 #include <chrono>
34 #include <ratio>
35 
36 namespace pw::chrono {
37 namespace backend {
38 
39 /// The ARM AEBI does not permit the opaque 'time_point' to be passed via
40 /// registers, ergo the underlying fundamental type is forward declared.
41 /// A SystemCLock tick has the units of one SystemClock::period duration.
42 /// This must be thread and IRQ safe and provided by the backend.
43 ///
44 int64_t GetSystemClockTickCount();
45 
46 }  // namespace backend
47 
48 /// The `SystemClock` represents an unsteady, monotonic clock.
49 ///
50 /// The epoch of this clock is unspecified and may not be related to wall time
51 /// (for example, it can be time since boot). The time between ticks of this
52 /// clock may vary due to sleep modes and potential interrupt handling.
53 /// `SystemClock` meets the requirements of C++'s `TrivialClock` and Pigweed's
54 /// `PigweedClock.`
55 ///
56 /// `SystemClock` is compatible with C++'s `Clock` & `TrivialClock` including:
57 /// - `SystemClock::rep`
58 /// - `SystemClock::period`
59 /// - `SystemClock::duration`
60 /// - `SystemClock::time_point`
61 /// - `SystemClock::is_steady`
62 /// - `SystemClock::now()`
63 ///
64 /// Example:
65 ///
66 /// @code
67 ///   SystemClock::time_point before = SystemClock::now();
68 ///   TakesALongTime();
69 ///   SystemClock::duration time_taken = SystemClock::now() - before;
70 ///   bool took_way_too_long = false;
71 ///   if (time_taken > std::chrono::seconds(42)) {
72 ///     took_way_too_long = true;
73 ///   }
74 /// @endcode
75 ///
76 /// This code is thread & IRQ safe, it may be NMI safe depending on is_nmi_safe.
77 ///
78 struct SystemClock {
79   using rep = int64_t;
80   /// The period must be provided by the backend.
81   using period = std::ratio<PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_NUMERATOR,
82                             PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_DENOMINATOR>;
83   /// Alias for durations representable with this clock.
84   using duration = std::chrono::duration<rep, period>;
85   using time_point = std::chrono::time_point<SystemClock>;
86   /// The epoch must be provided by the backend.
87   static constexpr Epoch epoch = backend::kSystemClockEpoch;
88 
89   /// The time points of this clock cannot decrease, however the time between
90   /// ticks of this clock may slightly vary due to sleep modes. The duration
91   /// during sleep may be ignored or backfilled with another clock.
92   static constexpr bool is_monotonic = true;
93   static constexpr bool is_steady = false;
94 
95   /// The now() function may not move forward while in a critical section or
96   /// interrupt. This must be provided by the backend.
97   static constexpr bool is_free_running = backend::kSystemClockFreeRunning;
98 
99   /// The clock must stop while in halting debug mode.
100   static constexpr bool is_stopped_in_halting_debug_mode = true;
101 
102   /// The now() function can be invoked at any time.
103   static constexpr bool is_always_enabled = true;
104 
105   /// The now() function may work in non-maskable interrupt contexts (e.g.
106   /// exception/fault handlers), depending on the backend. This must be provided
107   /// by the backend.
108   static constexpr bool is_nmi_safe = backend::kSystemClockNmiSafe;
109 
110   /// This is thread and IRQ safe. This must be provided by the backend.
nowSystemClock111   static time_point now() noexcept {
112     return time_point(duration(backend::GetSystemClockTickCount()));
113   }
114 
115   /// This is purely a helper, identical to directly using std::chrono::ceil, to
116   /// convert a duration type which cannot be implicitly converted where the
117   /// result is rounded up.
118   template <class Rep, class Period>
for_at_leastSystemClock119   static constexpr duration for_at_least(std::chrono::duration<Rep, Period> d) {
120     return std::chrono::ceil<duration>(d);
121   }
122 
123   /// Computes the nearest time_point after the specified duration has elapsed.
124   ///
125   /// This is useful for translating delay or timeout durations into deadlines.
126   ///
127   /// The time_point is computed based on now() plus the specified duration
128   /// where a singular clock tick is added to handle partial ticks. This ensures
129   /// that a duration of at least 1 tick does not result in [0,1] ticks and
130   /// instead in [1,2] ticks.
TimePointAfterAtLeastSystemClock131   static time_point TimePointAfterAtLeast(duration after_at_least) {
132     return now() + after_at_least + duration(1);
133   }
134 };
135 
136 /// An abstract interface representing a SystemClock.
137 ///
138 /// This interface allows decoupling code that uses time from the code that
139 /// creates a point in time. You can use this to your advantage by injecting
140 /// Clocks into interfaces rather than having implementations call
141 /// `SystemClock::now()` directly. However, this comes at a cost of a vtable per
142 /// implementation and more importantly passing and maintaining references to
143 /// the VirtualSystemCLock for all of the users.
144 ///
145 /// The `VirtualSystemClock::RealClock()` function returns a reference to the
146 /// real global SystemClock.
147 ///
148 /// Example:
149 ///
150 /// @code
151 ///   void DoFoo(VirtualSystemClock& system_clock) {
152 ///     SystemClock::time_point now = clock.now();
153 ///     // ... Code which consumes now.
154 ///   }
155 ///
156 ///   // Production code:
157 ///   DoFoo(VirtualSystemCLock::RealClock);
158 ///
159 ///   // Test code:
160 ///   MockClock test_clock();
161 ///   DoFoo(test_clock);
162 /// @endcode
163 ///
164 /// This interface is thread and IRQ safe.
165 class VirtualSystemClock {
166  public:
167   /// Returns a reference to the real system clock to aid instantiation.
168   static VirtualSystemClock& RealClock();
169 
170   virtual ~VirtualSystemClock() = default;
171 
172   /// Returns the current time.
173   virtual SystemClock::time_point now() = 0;
174 };
175 
176 }  // namespace pw::chrono
177 
178 // The backend can opt to include an inlined implementation of the following:
179 //   int64_t GetSystemClockTickCount();
180 #if __has_include("pw_chrono_backend/system_clock_inline.h")
181 #include "pw_chrono_backend/system_clock_inline.h"
182 #endif  // __has_include("pw_chrono_backend/system_clock_inline.h")
183 
184 #endif  // __cplusplus
185 
186 PW_EXTERN_C_START
187 
188 // C API Users should not create pw_chrono_SystemClock_Duration's directly,
189 // instead it is strongly recommended to use macros which express the duration
190 // in time units, instead of non-portable ticks.
191 //
192 // The following macros round up just like std::chrono::ceil, this is the
193 // recommended rounding to maintain the "at least" contract of timeouts and
194 // deadlines (note the *_CEIL macros are the same only more explicit):
195 //   PW_SYSTEM_CLOCK_MS(milliseconds)
196 //   PW_SYSTEM_CLOCK_S(seconds)
197 //   PW_SYSTEM_CLOCK_MIN(minutes)
198 //   PW_SYSTEM_CLOCK_H(hours)
199 //   PW_SYSTEM_CLOCK_MS_CEIL(milliseconds)
200 //   PW_SYSTEM_CLOCK_S_CEIL(seconds)
201 //   PW_SYSTEM_CLOCK_MIN_CEIL(minutes)
202 //   PW_SYSTEM_CLOCK_H_CEIL(hours)
203 //
204 // The following macros round down like std::chrono::{floor,duration_cast},
205 // these are discouraged but sometimes necessary:
206 //   PW_SYSTEM_CLOCK_MS_FLOOR(milliseconds)
207 //   PW_SYSTEM_CLOCK_S_FLOOR(seconds)
208 //   PW_SYSTEM_CLOCK_MIN_FLOOR(minutes)
209 //   PW_SYSTEM_CLOCK_H_FLOOR(hours)
210 #include "pw_chrono/internal/system_clock_macros.h"
211 
212 typedef struct {
213   int64_t ticks;
214 } pw_chrono_SystemClock_Duration;
215 
216 typedef struct {
217   pw_chrono_SystemClock_Duration duration_since_epoch;
218 } pw_chrono_SystemClock_TimePoint;
219 typedef int64_t pw_chrono_SystemClock_Nanoseconds;
220 
221 // Returns the current time, see SystemClock::now() for more detail.
222 pw_chrono_SystemClock_TimePoint pw_chrono_SystemClock_Now(void);
223 
224 // Returns the change in time between the current_time - last_time.
225 pw_chrono_SystemClock_Duration pw_chrono_SystemClock_TimeElapsed(
226     pw_chrono_SystemClock_TimePoint last_time,
227     pw_chrono_SystemClock_TimePoint current_time);
228 
229 // For lossless time unit conversion, the seconds per tick ratio that is
230 // numerator/denominator should be used:
231 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_NUMERATOR
232 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_DENOMINATOR
233 
234 // Warning, this may be lossy due to the use of std::chrono::floor,
235 // rounding towards zero.
236 pw_chrono_SystemClock_Nanoseconds pw_chrono_SystemClock_DurationToNsFloor(
237     pw_chrono_SystemClock_Duration duration);
238 
239 PW_EXTERN_C_END
240