• 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-masking interrupts, depending on the
106   /// backend. This must be provided by the backend.
107   static constexpr bool is_nmi_safe = backend::kSystemClockNmiSafe;
108 
109   /// This is thread and IRQ safe. This must be provided by the backend.
nowSystemClock110   static time_point now() noexcept {
111     return time_point(duration(backend::GetSystemClockTickCount()));
112   }
113 
114   /// This is purely a helper, identical to directly using std::chrono::ceil, to
115   /// convert a duration type which cannot be implicitly converted where the
116   /// result is rounded up.
117   template <class Rep, class Period>
for_at_leastSystemClock118   static constexpr duration for_at_least(std::chrono::duration<Rep, Period> d) {
119     return std::chrono::ceil<duration>(d);
120   }
121 
122   /// Computes the nearest time_point after the specified duration has elapsed.
123   ///
124   /// This is useful for translating delay or timeout durations into deadlines.
125   ///
126   /// The time_point is computed based on now() plus the specified duration
127   /// where a singular clock tick is added to handle partial ticks. This ensures
128   /// that a duration of at least 1 tick does not result in [0,1] ticks and
129   /// instead in [1,2] ticks.
TimePointAfterAtLeastSystemClock130   static time_point TimePointAfterAtLeast(duration after_at_least) {
131     return now() + after_at_least + duration(1);
132   }
133 };
134 
135 /// An abstract interface representing a SystemClock.
136 ///
137 /// This interface allows decoupling code that uses time from the code that
138 /// creates a point in time. You can use this to your advantage by injecting
139 /// Clocks into interfaces rather than having implementations call
140 /// `SystemClock::now()` directly. However, this comes at a cost of a vtable per
141 /// implementation and more importantly passing and maintaining references to
142 /// the VirtualSystemCLock for all of the users.
143 ///
144 /// The `VirtualSystemClock::RealClock()` function returns a reference to the
145 /// real global SystemClock.
146 ///
147 /// Example:
148 ///
149 /// @code
150 ///   void DoFoo(VirtualSystemClock& system_clock) {
151 ///     SystemClock::time_point now = clock.now();
152 ///     // ... Code which consumes now.
153 ///   }
154 ///
155 ///   // Production code:
156 ///   DoFoo(VirtualSystemCLock::RealClock);
157 ///
158 ///   // Test code:
159 ///   MockClock test_clock();
160 ///   DoFoo(test_clock);
161 /// @endcode
162 ///
163 /// This interface is thread and IRQ safe.
164 class VirtualSystemClock {
165  public:
166   /// Returns a reference to the real system clock to aid instantiation.
167   static VirtualSystemClock& RealClock();
168 
169   virtual ~VirtualSystemClock() = default;
170 
171   /// Returns the current time.
172   virtual SystemClock::time_point now() = 0;
173 };
174 
175 }  // namespace pw::chrono
176 
177 // The backend can opt to include an inlined implementation of the following:
178 //   int64_t GetSystemClockTickCount();
179 #if __has_include("pw_chrono_backend/system_clock_inline.h")
180 #include "pw_chrono_backend/system_clock_inline.h"
181 #endif  // __has_include("pw_chrono_backend/system_clock_inline.h")
182 
183 #endif  // __cplusplus
184 
185 PW_EXTERN_C_START
186 
187 // C API Users should not create pw_chrono_SystemClock_Duration's directly,
188 // instead it is strongly recommended to use macros which express the duration
189 // in time units, instead of non-portable ticks.
190 //
191 // The following macros round up just like std::chrono::ceil, this is the
192 // recommended rounding to maintain the "at least" contract of timeouts and
193 // deadlines (note the *_CEIL macros are the same only more explicit):
194 //   PW_SYSTEM_CLOCK_MS(milliseconds)
195 //   PW_SYSTEM_CLOCK_S(seconds)
196 //   PW_SYSTEM_CLOCK_MIN(minutes)
197 //   PW_SYSTEM_CLOCK_H(hours)
198 //   PW_SYSTEM_CLOCK_MS_CEIL(milliseconds)
199 //   PW_SYSTEM_CLOCK_S_CEIL(seconds)
200 //   PW_SYSTEM_CLOCK_MIN_CEIL(minutes)
201 //   PW_SYSTEM_CLOCK_H_CEIL(hours)
202 //
203 // The following macros round down like std::chrono::{floor,duration_cast},
204 // these are discouraged but sometimes necessary:
205 //   PW_SYSTEM_CLOCK_MS_FLOOR(milliseconds)
206 //   PW_SYSTEM_CLOCK_S_FLOOR(seconds)
207 //   PW_SYSTEM_CLOCK_MIN_FLOOR(minutes)
208 //   PW_SYSTEM_CLOCK_H_FLOOR(hours)
209 #include "pw_chrono/internal/system_clock_macros.h"
210 
211 typedef struct {
212   int64_t ticks;
213 } pw_chrono_SystemClock_Duration;
214 
215 typedef struct {
216   pw_chrono_SystemClock_Duration duration_since_epoch;
217 } pw_chrono_SystemClock_TimePoint;
218 typedef int64_t pw_chrono_SystemClock_Nanoseconds;
219 
220 // Returns the current time, see SystemClock::now() for more detail.
221 pw_chrono_SystemClock_TimePoint pw_chrono_SystemClock_Now(void);
222 
223 // Returns the change in time between the current_time - last_time.
224 pw_chrono_SystemClock_Duration pw_chrono_SystemClock_TimeElapsed(
225     pw_chrono_SystemClock_TimePoint last_time,
226     pw_chrono_SystemClock_TimePoint current_time);
227 
228 // For lossless time unit conversion, the seconds per tick ratio that is
229 // numerator/denominator should be used:
230 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_NUMERATOR
231 //   PW_CHRONO_SYSTEM_CLOCK_PERIOD_SECONDS_DENOMINATOR
232 
233 // Warning, this may be lossy due to the use of std::chrono::floor,
234 // rounding towards zero.
235 pw_chrono_SystemClock_Nanoseconds pw_chrono_SystemClock_DurationToNsFloor(
236     pw_chrono_SystemClock_Duration duration);
237 
238 PW_EXTERN_C_END
239