blob: a6816a97df93085bcd125c56363883e99a937c88 [file] [log] [blame]
Ewout van Bekkum41daf162021-03-03 13:57:28 -08001// Copyright 2021 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 "RTOS.h"
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080023#include "pw_sync/interrupt_spin_lock.h"
Ewout van Bekkum41daf162021-03-03 13:57:28 -080024
25namespace pw::chrono::backend {
26namespace {
27
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080028sync::InterruptSpinLock system_clock_interrupt_spin_lock;
Ewout van Bekkum41daf162021-03-03 13:57:28 -080029int64_t overflow_tick_count = 0;
30uint32_t native_tick_count = 0;
31static_assert(!SystemClock::is_nmi_safe,
32 "global state is not atomic nor double buferred");
33
34static_assert(sizeof(void*) == 4, "this backend only supports 32 bit targets!");
35
36inline uint32_t GetUint32TickCount() {
37 // embOS returns a signed 32 bit value, however according to their developers
38 // the binary value continues to increment like an unsigned value, ergo we
39 // instead reinterpret the tick count as the raw underlying 32 bit unsigned
40 // tick count.
41 return static_cast<uint32_t>(OS_GetTime32());
42}
43
44// The tick count resets to 0, ergo the overflow count is the max count + 1.
45constexpr int64_t kNativeOverflowTickCount =
46 static_cast<int64_t>(std::numeric_limits<uint32_t>::max()) + 1;
47
48} // namespace
49
50int64_t GetSystemClockTickCount() {
Ewout van Bekkumda2a62d2021-03-12 11:34:47 -080051 std::lock_guard lock(system_clock_interrupt_spin_lock);
Ewout van Bekkum41daf162021-03-03 13:57:28 -080052 const uint32_t new_native_tick_count = GetUint32TickCount();
53 // WARNING: This must be called more than once per overflow period!
54 if (new_native_tick_count < native_tick_count) {
55 // Native tick count overflow detected!
56 overflow_tick_count += kNativeOverflowTickCount;
57 }
58 native_tick_count = new_native_tick_count;
59 return overflow_tick_count + native_tick_count;
60}
61
62} // namespace pw::chrono::backend