blob: 3c8dc64f10f822900b58ebc73ed5d6a1e1a71864 [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 Abraham018ff0b2021-04-19 23:39:36 -0700118 auto triggerTime = mClock->now() + mInterval;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700119 state = TimerState::WAITING;
Alec Mouriaadcf942022-05-11 01:22:42 +0000120 while (true) {
Alec Mourib4ad3602022-06-01 21:40:20 +0000121 // Wait until triggerTime time to check if we need to reset or drop into the idle state.
122 if (const auto triggerInterval = triggerTime - mClock->now(); triggerInterval > 0ns) {
123 mWaiting = true;
124 struct timespec ts;
125 calculateTimeoutTime(triggerInterval, &ts);
126 int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &ts);
127 if (result && errno != ETIMEDOUT && errno != EINTR) {
128 std::stringstream ss;
129 ss << "sem_clockwait failed (" << errno << ")";
130 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
131 }
Ady Abraham1e19ac92020-11-17 16:56:00 -0800132 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700133
Alec Mouriaadcf942022-05-11 01:22:42 +0000134 mWaiting = false;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700135 state = checkForResetAndStop(state);
Alec Mouriaadcf942022-05-11 01:22:42 +0000136 if (state == TimerState::STOPPED) {
137 break;
138 }
139
Alec Mourib4ad3602022-06-01 21:40:20 +0000140 if (state == TimerState::WAITING && (triggerTime - mClock->now()) <= 0ns) {
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700141 triggerTimeout = true;
142 state = TimerState::IDLE;
Alec Mouriaadcf942022-05-11 01:22:42 +0000143 break;
144 }
145
146 if (state == TimerState::RESET) {
147 triggerTime = mLastResetTime.load() + mInterval;
148 state = TimerState::WAITING;
Ana Krulecfb772822018-11-30 10:44:07 +0100149 }
Ana Krulecfb772822018-11-30 10:44:07 +0100150 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700151
Ady Abrahama1a49af2019-02-07 14:36:55 -0800152 if (triggerTimeout && mTimeoutCallback) {
153 mTimeoutCallback();
154 }
Ana Krulecfb772822018-11-30 10:44:07 +0100155 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800156}
Ana Krulecfb772822018-11-30 10:44:07 +0100157
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700158OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
159 // Stop takes precedence of the reset.
160 if (mStopTriggered.exchange(false)) {
161 return TimerState::STOPPED;
Ana Krulecfb772822018-11-30 10:44:07 +0100162 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700163 // If the state was stopped, the thread was joined, and we cannot reset
164 // the timer anymore.
165 if (state != TimerState::STOPPED && mResetTriggered.exchange(false)) {
166 return TimerState::RESET;
167 }
168 return state;
169}
170
171void OneShotTimer::reset() {
Alec Mouriaadcf942022-05-11 01:22:42 +0000172 mLastResetTime = mClock->now();
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700173 mResetTriggered = true;
Alec Mouriaadcf942022-05-11 01:22:42 +0000174 // If mWaiting is true, then we are guaranteed to be in a block where we are waiting on
175 // mSemaphore for a timeout, rather than idling. So we can avoid a sem_post call since we can
176 // just check that we triggered a reset on timeout.
177 if (!mWaiting) {
178 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
179 }
Ana Krulecfb772822018-11-30 10:44:07 +0100180}
181
Dominik Laskowski49cea512019-11-12 14:13:23 -0800182std::string OneShotTimer::dump() const {
183 std::ostringstream stream;
184 stream << mInterval.count() << " ms";
185 return stream.str();
186}
187
Ana Krulecfb772822018-11-30 10:44:07 +0100188} // namespace scheduler
189} // namespace android