1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
15 #include "pw_chrono/system_clock.h"
22 #include "pw_sync/spin_lock.h"
25 namespace pw::chrono::backend {
28 #if defined(TX_NO_TIMER) && TX_NO_TIMER
29 #error "This backend is not compatible with TX_NO_TIMER"
30 #endif // defined(TX_NO_TIMER) && TX_NO_TIMER
32 // Extension wrapping pw::SpinLock to allow an atomic to be used to determine
33 // whether it has been constructed and is ready to be used.
34 class ConstructionSignalingSpinLock : public sync::SpinLock {
36 ConstructionSignalingSpinLock(std::atomic<bool>& constructed_signal)
38 // Note that the memory order is relaxed because C++ global static
39 // construction is a single threaded environment.
40 constructed_signal.store(true, std::memory_order_relaxed);
44 // This is POD, meaning this atomic is available before static C++ global
45 // constructors are run.
46 std::atomic<bool> system_clock_spin_lock_constructed = {false};
48 ConstructionSignalingSpinLock system_clock_spin_lock(
49 system_clock_spin_lock_constructed);
51 int64_t overflow_tick_count = 0;
52 ULONG native_tick_count = 0;
53 static_assert(!SystemClock::is_nmi_safe,
54 "global state is not atomic nor double buferred");
56 // The tick count resets to 0, ergo the overflow count is the max count + 1.
57 constexpr int64_t kNativeOverflowTickCount =
58 static_cast<int64_t>(std::numeric_limits<ULONG>::max()) + 1;
62 int64_t GetSystemClockTickCount() {
63 // Note that the memory order is relaxed because C++ global static
64 // construction is a single threaded environment.
65 if (!system_clock_spin_lock_constructed.load(std::memory_order_relaxed)) {
69 std::lock_guard lock(system_clock_spin_lock);
70 const ULONG new_native_tick_count = tx_time_get();
71 // WARNING: This must be called more than once per overflow period!
72 if (new_native_tick_count < native_tick_count) {
73 // Native tick count overflow detected!
74 overflow_tick_count += kNativeOverflowTickCount;
76 native_tick_count = new_native_tick_count;
77 return overflow_tick_count + native_tick_count;
80 } // namespace pw::chrono::backend