1 // 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" 23 #include "pw_sync/interrupt_spin_lock.h" 24 25 namespace pw::chrono::backend { 26 namespace { 27 28 sync::InterruptSpinLock system_clock_interrupt_spin_lock; 29 int64_t overflow_tick_count = 0; 30 uint32_t native_tick_count = 0; 31 static_assert(!SystemClock::is_nmi_safe, 32 "global state is not atomic nor double buferred"); 33 34 static_assert(sizeof(void*) == 4, "this backend only supports 32 bit targets!"); 35 GetUint32TickCount()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. 45 constexpr int64_t kNativeOverflowTickCount = 46 static_cast<int64_t>(std::numeric_limits<uint32_t>::max()) + 1; 47 48 } // namespace 49 GetSystemClockTickCount()50int64_t GetSystemClockTickCount() { 51 std::lock_guard lock(system_clock_interrupt_spin_lock); 52 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 63