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"
23 #include "pw_interrupt/context.h"
24 #include "pw_sync/spin_lock.h"
27 namespace pw::chrono::backend {
30 // Extension wrapping pw::SpinLock to allow an atomic to be used to determine
31 // whether it has been constructed and is ready to be used.
32 class ConstructionSignalingSpinLock : public sync::SpinLock {
34 ConstructionSignalingSpinLock(std::atomic<bool>& constructed_signal)
36 // Note that the memory order is relaxed because C++ global static
37 // construction is a single threaded environment.
38 constructed_signal.store(true, std::memory_order_relaxed);
42 // This is POD, meaning this atomic is available before static C++ global
43 // constructors are run.
44 std::atomic<bool> system_clock_spin_lock_constructed = {false};
46 ConstructionSignalingSpinLock system_clock_spin_lock(
47 system_clock_spin_lock_constructed);
49 int64_t overflow_tick_count = 0;
50 TickType_t native_tick_count = 0;
51 static_assert(!SystemClock::is_nmi_safe,
52 "global state is not atomic nor double buferred");
54 // The tick count resets to 0, ergo the overflow count is the max count + 1.
55 constexpr int64_t kNativeOverflowTickCount =
56 static_cast<int64_t>(std::numeric_limits<TickType_t>::max()) + 1;
60 int64_t GetSystemClockTickCount() {
61 // Note that the memory order is relaxed because C++ global static
62 // construction is a single threaded environment.
63 if (!system_clock_spin_lock_constructed.load(std::memory_order_relaxed)) {
64 return interrupt::InInterruptContext() ? xTaskGetTickCountFromISR()
65 : xTaskGetTickCount();
68 std::lock_guard lock(system_clock_spin_lock);
69 const TickType_t new_native_tick_count = interrupt::InInterruptContext()
70 ? xTaskGetTickCountFromISR()
71 : xTaskGetTickCount();
72 // WARNING: This must be called more than once per overflow period!
73 if (new_native_tick_count < native_tick_count) {
74 // Native tick count overflow detected!
75 overflow_tick_count += kNativeOverflowTickCount;
77 native_tick_count = new_native_tick_count;
78 return overflow_tick_count + native_tick_count;
81 } // namespace pw::chrono::backend