blob: bcb5792f8258d2330d58eedfbf3e52bf5dcecb1f [file] [log] [blame]
Ewout van Bekkumf7e38b32020-11-16 11:56:41 -08001// 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
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080022#include "pw_sync/interrupt_spin_lock.h"
Ewout van Bekkumf7e38b32020-11-16 11:56:41 -080023#include "tx_api.h"
24
25namespace pw::chrono::backend {
26namespace {
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
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080032sync::InterruptSpinLock system_clock_interrupt_spin_lock;
Ewout van Bekkumf7e38b32020-11-16 11:56:41 -080033int64_t overflow_tick_count = 0;
34ULONG native_tick_count = 0;
35static_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.
39constexpr int64_t kNativeOverflowTickCount =
40 static_cast<int64_t>(std::numeric_limits<ULONG>::max()) + 1;
41
42} // namespace
43
44int64_t GetSystemClockTickCount() {
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080045 std::lock_guard lock(system_clock_interrupt_spin_lock);
Ewout van Bekkumf7e38b32020-11-16 11:56:41 -080046 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