xref: /aosp_15_r20/external/pigweed/pw_chrono_threadx/system_clock.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 
15 #include "pw_chrono/system_clock.h"
16 
17 #include <atomic>
18 #include <chrono>
19 #include <limits>
20 #include <mutex>
21 
22 #include "pw_sync/interrupt_spin_lock.h"
23 #include "tx_api.h"
24 
25 namespace pw::chrono::backend {
26 namespace {
27 
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
31 
32 sync::InterruptSpinLock system_clock_interrupt_spin_lock;
33 int64_t overflow_tick_count = 0;
34 ULONG native_tick_count = 0;
35 static_assert(!SystemClock::is_nmi_safe,
36               "global state is not atomic nor double buferred");
37 
38 // The tick count resets to 0, ergo the overflow count is the max count + 1.
39 constexpr int64_t kNativeOverflowTickCount =
40     static_cast<int64_t>(std::numeric_limits<ULONG>::max()) + 1;
41 
42 }  // namespace
43 
GetSystemClockTickCount()44 int64_t GetSystemClockTickCount() {
45   std::lock_guard lock(system_clock_interrupt_spin_lock);
46   const ULONG new_native_tick_count = tx_time_get();
47   // WARNING: This must be called more than once per overflow period!
48   if (new_native_tick_count < native_tick_count) {
49     // Native tick count overflow detected!
50     overflow_tick_count += kNativeOverflowTickCount;
51   }
52   native_tick_count = new_native_tick_count;
53   return overflow_tick_count + native_tick_count;
54 }
55 
56 }  // namespace pw::chrono::backend
57