Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 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_timer.h" |
| 16 | |
| 17 | #include <algorithm> |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 18 | #include <mutex> |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 19 | |
| 20 | #include "FreeRTOS.h" |
| 21 | #include "pw_assert/check.h" |
| 22 | #include "pw_chrono_freertos/system_clock_constants.h" |
| 23 | #include "task.h" |
| 24 | #include "timers.h" |
| 25 | |
| 26 | namespace pw::chrono { |
| 27 | namespace { |
| 28 | |
| 29 | using State = backend::NativeSystemTimer::State; |
| 30 | |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 31 | // Instead of adding targeted locks to each instance, simply use the global |
| 32 | // scheduler critical section lock. |
| 33 | class SchedulerLock { |
| 34 | public: |
| 35 | static void lock() { vTaskSuspendAll(); } |
| 36 | static void unlock() { xTaskResumeAll(); } |
| 37 | }; |
| 38 | SchedulerLock global_timer_lock; |
| 39 | |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 40 | void HandleTimerCallback(TimerHandle_t timer_handle) { |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 41 | // The FreeRTOS timer service is always handled by a thread, ergo to ensure |
| 42 | // this API is threadsafe we simply disable task switching. |
| 43 | std::unique_lock lock(global_timer_lock); |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 44 | |
| 45 | // Because the timer control block, AKA what the timer handle points at, is |
| 46 | // the first member of the NativeSystemTimer struct we play a trick to cheaply |
| 47 | // get the native handle reference. |
| 48 | backend::NativeSystemTimer& native_type = |
| 49 | *reinterpret_cast<backend::NativeSystemTimer*>(timer_handle); |
| 50 | |
| 51 | PW_CHECK_UINT_EQ(xTimerIsTimerActive(timer_handle), |
| 52 | pdFALSE, |
| 53 | "The timer is still active while being executed"); |
| 54 | |
| 55 | if (native_type.state == State::kCancelled) { |
| 56 | // Do nothing, we were invoked while the stop command was in the queue. |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | const SystemClock::duration time_until_deadline = |
| 61 | native_type.expiry_deadline - SystemClock::now(); |
| 62 | if (time_until_deadline <= SystemClock::duration::zero()) { |
| 63 | // We have met the deadline, cancel the current state and execute the user's |
| 64 | // callback. Note we cannot update the state later as the user's callback |
| 65 | // may alter the desired state through the Invoke*() API. |
| 66 | native_type.state = State::kCancelled; |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 67 | |
| 68 | // Release the scheduler lock once we won't modify native_state any further. |
| 69 | lock.unlock(); |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 70 | native_type.user_callback(native_type.expiry_deadline); |
| 71 | return; |
| 72 | } |
| 73 | |
| 74 | // We haven't met the deadline yet, reschedule as far out as possible. |
| 75 | const SystemClock::duration period = |
| 76 | std::min(pw::chrono::freertos::kMaxTimeout, time_until_deadline); |
| 77 | PW_CHECK_UINT_EQ( |
| 78 | xTimerChangePeriod( |
| 79 | &native_type.tcb, static_cast<TickType_t>(period.count()), 0), |
| 80 | pdPASS, |
| 81 | "Timer command queue overflowed"); |
| 82 | PW_CHECK_UINT_EQ(xTimerStart(&native_type.tcb, 0), |
| 83 | pdPASS, |
| 84 | "Timer command queue overflowed"); |
| 85 | } |
| 86 | |
| 87 | constexpr TickType_t kInvalidPeriod = 1; |
| 88 | constexpr UBaseType_t kOneShotMode = pdFALSE; // Do not use auto reload. |
| 89 | |
| 90 | } // namespace |
| 91 | |
| 92 | #if configUSE_TIMERS != 1 |
| 93 | #error \ |
| 94 | "Backend requires your FreeRTOS configuration to have configUSE_TIMERS == 1" |
| 95 | #endif |
| 96 | |
| 97 | #if configSUPPORT_STATIC_ALLOCATION != 1 |
| 98 | #error \ |
| 99 | "Backend requires your FreeRTOS configuration to have configSUPPORT_STATIC_ALLOCATION == 1" |
| 100 | #endif |
| 101 | |
| 102 | SystemTimer::SystemTimer(ExpiryCallback callback) |
| 103 | : native_type_{.tcb{}, |
| 104 | .state = State::kCancelled, |
| 105 | .expiry_deadline = SystemClock::time_point(), |
| 106 | .user_callback = std::move(callback)} { |
| 107 | // Note that timer "creation" is not enqueued through the command queue and |
| 108 | // is ergo safe to do before the scheduler is running. |
| 109 | const TimerHandle_t handle = |
| 110 | xTimerCreateStatic("", // "pw::chrono::SystemTimer", |
| 111 | kInvalidPeriod, |
| 112 | kOneShotMode, |
| 113 | this, |
| 114 | HandleTimerCallback, |
| 115 | &native_type_.tcb); |
| 116 | |
| 117 | // This should never fail since the pointer provided was not null and it |
| 118 | // should return a pointer to the StaticTimer_t. |
| 119 | PW_DCHECK_PTR_EQ(handle, &native_type_.tcb); |
| 120 | } |
| 121 | |
| 122 | SystemTimer::~SystemTimer() { |
| 123 | Cancel(); |
| 124 | |
| 125 | // WARNING: This enqueues the request to delete the timer through a queue, it |
| 126 | // does not synchronously delete and disable the timer here! This means that |
| 127 | // if the timer is about to expire and the timer service thread is a lower |
| 128 | // priority that it may use the native_type_ after it is free'd. |
| 129 | PW_CHECK_UINT_EQ(pdPASS, |
| 130 | xTimerDelete(&native_type_.tcb, 0), |
| 131 | "Timer command queue overflowed"); |
| 132 | |
| 133 | // In case the timer is still active as warned above, busy yield loop until it |
| 134 | // has been removed. Note that this is safe before the scheduler has been |
| 135 | // started because the timer cannot have been added to the queue yet and ergo |
| 136 | // it shouldn't attempt to yield. |
| 137 | while (xTimerIsTimerActive(&native_type_.tcb)) { |
| 138 | taskYIELD(); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | void SystemTimer::InvokeAt(SystemClock::time_point timestamp) { |
| 143 | // The FreeRTOS timer service is always handled by a thread, ergo to ensure |
| 144 | // this API is threadsafe we simply disable task switching. |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 145 | std::lock_guard lock(global_timer_lock); |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 146 | |
| 147 | // We don't want to call Cancel which would enqueue a stop command instead of |
| 148 | // synchronously updating the state. Instead we update the expiry deadline |
| 149 | // and update the state where the one shot only fires if the expiry deadline |
| 150 | // is exceeded and the callback is executed once. |
| 151 | native_type_.expiry_deadline = timestamp; |
| 152 | |
| 153 | // Schedule the timer as far out as possible. Note that the timeout might be |
| 154 | // clamped and it may be rescheduled internally. |
| 155 | const SystemClock::duration time_until_deadline = |
| 156 | timestamp - SystemClock::now(); |
| 157 | const SystemClock::duration period = |
| 158 | std::clamp(SystemClock::duration::zero(), |
| 159 | time_until_deadline, |
| 160 | pw::chrono::freertos::kMaxTimeout); |
| 161 | |
| 162 | PW_CHECK_UINT_EQ( |
| 163 | xTimerChangePeriod( |
| 164 | &native_type_.tcb, static_cast<TickType_t>(period.count()), 0), |
| 165 | pdPASS, |
| 166 | "Timer command queue overflowed"); |
| 167 | |
| 168 | // Don't enqueue the start multiple times, schedule it once and let the |
| 169 | // callback cancel. |
| 170 | if (native_type_.state == State::kCancelled) { |
| 171 | PW_CHECK_UINT_EQ(xTimerStart(&native_type_.tcb, 0), |
| 172 | pdPASS, |
| 173 | "Timer command queue overflowed"); |
| 174 | native_type_.state = State::kScheduled; |
| 175 | } |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 176 | } |
| 177 | |
| 178 | void SystemTimer::Cancel() { |
| 179 | // The FreeRTOS timer service is always handled by a thread, ergo to ensure |
| 180 | // this API is threadsafe we simply disable task switching. |
Ewout van Bekkum | 1f43db3 | 2021-07-09 12:18:04 -0700 | [diff] [blame^] | 181 | std::lock_guard lock(global_timer_lock); |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 182 | |
| 183 | // The stop command may not be executed until later in case we're in a |
| 184 | // critical section. For this reason update the internal state in case the |
| 185 | // callback gets invoked. |
| 186 | // |
| 187 | // Note that xTimerIsTimerActive cannot be used here as the timer service |
| 188 | // daemon may be a lower priority and ergo may still execute the callback |
| 189 | // after Cancel() was invoked. This is because a single expired timer may be |
| 190 | // processed before the entire command queue is emptied. |
| 191 | native_type_.state = State::kCancelled; |
| 192 | |
| 193 | PW_CHECK_UINT_EQ(xTimerStop(&native_type_.tcb, 0), |
| 194 | pdPASS, |
| 195 | "Timer command queue overflowed"); |
Ewout van Bekkum | 4f97fdd | 2021-06-24 10:37:37 -0700 | [diff] [blame] | 196 | } |
| 197 | |
| 198 | } // namespace pw::chrono |