blob: 7e61dc02aa464f4c00f131ef8d781dabdd3994e8 [file] [log] [blame]
Ana Krulecfb772822018-11-30 10:44:07 +01001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ana Krulecf2c006d2019-06-21 15:37:07 -070017#include "OneShotTimer.h"
Ady Abraham1e19ac92020-11-17 16:56:00 -080018#include <utils/Log.h>
19#include <utils/Timers.h>
Ana Krulecfb772822018-11-30 10:44:07 +010020#include <chrono>
Dominik Laskowski49cea512019-11-12 14:13:23 -080021#include <sstream>
Ana Krulecfb772822018-11-30 10:44:07 +010022#include <thread>
23
Ana Krulec75d4ffc2020-10-16 14:56:19 -070024namespace {
25using namespace std::chrono_literals;
26
27constexpr int64_t kNsToSeconds = std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
28
29// The syscall interface uses a pair of integers for the timestamp. The first
30// (tv_sec) is the whole count of seconds. The second (tv_nsec) is the
31// nanosecond part of the count. This function takes care of translation.
32void calculateTimeoutTime(std::chrono::nanoseconds timestamp, timespec* spec) {
Ady Abraham1e19ac92020-11-17 16:56:00 -080033 const nsecs_t timeout = systemTime(CLOCK_MONOTONIC) + timestamp.count();
34 spec->tv_sec = static_cast<__kernel_time_t>(timeout / kNsToSeconds);
35 spec->tv_nsec = timeout % kNsToSeconds;
Ana Krulec75d4ffc2020-10-16 14:56:19 -070036}
37} // namespace
38
Ana Krulecfb772822018-11-30 10:44:07 +010039namespace android {
40namespace scheduler {
41
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080042OneShotTimer::OneShotTimer(std::string name, const Interval& interval,
43 const ResetCallback& resetCallback,
Alec Mouri07b27ce2021-04-26 16:31:44 -070044 const TimeoutCallback& timeoutCallback, std::unique_ptr<Clock> clock)
Ady Abraham018ff0b2021-04-19 23:39:36 -070045 : mClock(std::move(clock)),
46 mName(std::move(name)),
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080047 mInterval(interval),
48 mResetCallback(resetCallback),
Ady Abraham018ff0b2021-04-19 23:39:36 -070049 mTimeoutCallback(timeoutCallback) {
Alec Mouriaadcf942022-05-11 01:22:42 +000050 mLastResetTime = std::chrono::steady_clock::time_point::min();
Ady Abraham018ff0b2021-04-19 23:39:36 -070051 LOG_ALWAYS_FATAL_IF(!mClock, "Clock must not be provided");
52}
Ana Krulecfb772822018-11-30 10:44:07 +010053
Ana Krulecf2c006d2019-06-21 15:37:07 -070054OneShotTimer::~OneShotTimer() {
Ana Krulecfb772822018-11-30 10:44:07 +010055 stop();
56}
57
Ana Krulecf2c006d2019-06-21 15:37:07 -070058void OneShotTimer::start() {
Ady Abraham1e19ac92020-11-17 16:56:00 -080059 int result = sem_init(&mSemaphore, 0, 0);
60 LOG_ALWAYS_FATAL_IF(result, "sem_init failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070061
62 if (!mThread.joinable()) {
63 // Only create thread if it has not been created.
64 mThread = std::thread(&OneShotTimer::loop, this);
Ana Krulecfb772822018-11-30 10:44:07 +010065 }
Ana Krulecfb772822018-11-30 10:44:07 +010066}
67
Ana Krulecf2c006d2019-06-21 15:37:07 -070068void OneShotTimer::stop() {
Ana Krulec75d4ffc2020-10-16 14:56:19 -070069 mStopTriggered = true;
Ady Abraham1e19ac92020-11-17 16:56:00 -080070 int result = sem_post(&mSemaphore);
71 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070072
Ana Krulecfb772822018-11-30 10:44:07 +010073 if (mThread.joinable()) {
74 mThread.join();
Ady Abraham1e19ac92020-11-17 16:56:00 -080075 result = sem_destroy(&mSemaphore);
76 LOG_ALWAYS_FATAL_IF(result, "sem_destroy failed");
Ana Krulecfb772822018-11-30 10:44:07 +010077 }
78}
79
Ana Krulecf2c006d2019-06-21 15:37:07 -070080void OneShotTimer::loop() {
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080081 if (pthread_setname_np(pthread_self(), mName.c_str())) {
82 ALOGW("Failed to set thread name on dispatch thread");
83 }
84
Ana Krulec75d4ffc2020-10-16 14:56:19 -070085 TimerState state = TimerState::RESET;
Ady Abrahama1a49af2019-02-07 14:36:55 -080086 while (true) {
87 bool triggerReset = false;
88 bool triggerTimeout = false;
Ady Abrahama1a49af2019-02-07 14:36:55 -080089
Ana Krulec75d4ffc2020-10-16 14:56:19 -070090 state = checkForResetAndStop(state);
91 if (state == TimerState::STOPPED) {
92 break;
Ady Abrahama1a49af2019-02-07 14:36:55 -080093 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -070094
95 if (state == TimerState::IDLE) {
Ady Abraham1e19ac92020-11-17 16:56:00 -080096 int result = sem_wait(&mSemaphore);
97 if (result && errno != EINTR) {
98 std::stringstream ss;
99 ss << "sem_wait failed (" << errno << ")";
100 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
101 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700102 continue;
103 }
104
105 if (state == TimerState::RESET) {
106 triggerReset = true;
107 }
108
Ady Abrahama1a49af2019-02-07 14:36:55 -0800109 if (triggerReset && mResetCallback) {
110 mResetCallback();
111 }
112
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700113 state = checkForResetAndStop(state);
114 if (state == TimerState::STOPPED) {
115 break;
116 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800117
Ady Abraham67231722024-03-21 18:06:21 -0700118 auto triggerTime = mClock->now() + mInterval.load();
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700119 state = TimerState::WAITING;
Alec Mouriaadcf942022-05-11 01:22:42 +0000120 while (true) {
Ady Abraham67231722024-03-21 18:06:21 -0700121 if (mPaused) {
122 mWaiting = true;
123 int result = sem_wait(&mSemaphore);
124 if (result && errno != EINTR) {
125 std::stringstream ss;
126 ss << "sem_wait failed (" << errno << ")";
127 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
128 }
129
130 mWaiting = false;
131 state = checkForResetAndStop(state);
132 if (state == TimerState::STOPPED) {
133 break;
134 }
135 }
Alec Mourib4ad3602022-06-01 21:40:20 +0000136 // Wait until triggerTime time to check if we need to reset or drop into the idle state.
137 if (const auto triggerInterval = triggerTime - mClock->now(); triggerInterval > 0ns) {
138 mWaiting = true;
139 struct timespec ts;
140 calculateTimeoutTime(triggerInterval, &ts);
141 int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &ts);
142 if (result && errno != ETIMEDOUT && errno != EINTR) {
143 std::stringstream ss;
144 ss << "sem_clockwait failed (" << errno << ")";
145 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
146 }
Ady Abraham1e19ac92020-11-17 16:56:00 -0800147 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700148
Alec Mouriaadcf942022-05-11 01:22:42 +0000149 mWaiting = false;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700150 state = checkForResetAndStop(state);
Alec Mouriaadcf942022-05-11 01:22:42 +0000151 if (state == TimerState::STOPPED) {
152 break;
153 }
154
Ady Abraham67231722024-03-21 18:06:21 -0700155 if (!mPaused && state == TimerState::WAITING && (triggerTime - mClock->now()) <= 0ns) {
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700156 triggerTimeout = true;
157 state = TimerState::IDLE;
Alec Mouriaadcf942022-05-11 01:22:42 +0000158 break;
159 }
160
161 if (state == TimerState::RESET) {
Ady Abraham67231722024-03-21 18:06:21 -0700162 triggerTime = mLastResetTime.load() + mInterval.load();
Alec Mouriaadcf942022-05-11 01:22:42 +0000163 state = TimerState::WAITING;
Ana Krulecfb772822018-11-30 10:44:07 +0100164 }
Ana Krulecfb772822018-11-30 10:44:07 +0100165 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700166
Ady Abrahama1a49af2019-02-07 14:36:55 -0800167 if (triggerTimeout && mTimeoutCallback) {
168 mTimeoutCallback();
169 }
Ana Krulecfb772822018-11-30 10:44:07 +0100170 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800171}
Ana Krulecfb772822018-11-30 10:44:07 +0100172
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700173OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
174 // Stop takes precedence of the reset.
175 if (mStopTriggered.exchange(false)) {
176 return TimerState::STOPPED;
Ana Krulecfb772822018-11-30 10:44:07 +0100177 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700178 // If the state was stopped, the thread was joined, and we cannot reset
179 // the timer anymore.
180 if (state != TimerState::STOPPED && mResetTriggered.exchange(false)) {
181 return TimerState::RESET;
182 }
183 return state;
184}
185
186void OneShotTimer::reset() {
Alec Mouriaadcf942022-05-11 01:22:42 +0000187 mLastResetTime = mClock->now();
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700188 mResetTriggered = true;
Alec Mouriaadcf942022-05-11 01:22:42 +0000189 // If mWaiting is true, then we are guaranteed to be in a block where we are waiting on
190 // mSemaphore for a timeout, rather than idling. So we can avoid a sem_post call since we can
191 // just check that we triggered a reset on timeout.
192 if (!mWaiting) {
193 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
194 }
Ana Krulecfb772822018-11-30 10:44:07 +0100195}
196
Ady Abraham67231722024-03-21 18:06:21 -0700197void OneShotTimer::pause() {
198 mPaused = true;
199}
200
201void OneShotTimer::resume() {
202 if (mPaused.exchange(false)) {
203 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
204 }
205}
206
Ana Krulecfb772822018-11-30 10:44:07 +0100207} // namespace scheduler
208} // namespace android