blob: 9c6e56dfa8beb68b994e60ce7506e5e516855759 [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) {
121 mWaiting = true;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700122 constexpr auto zero = std::chrono::steady_clock::duration::zero();
Alec Mouriaadcf942022-05-11 01:22:42 +0000123 // Wait for mInterval time to check if we need to reset or drop into the idle state.
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700124 struct timespec ts;
125 calculateTimeoutTime(std::chrono::nanoseconds(mInterval), &ts);
Ady Abraham1e19ac92020-11-17 16:56:00 -0800126 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 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700132
Alec Mouriaadcf942022-05-11 01:22:42 +0000133 mWaiting = false;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700134 state = checkForResetAndStop(state);
Alec Mouriaadcf942022-05-11 01:22:42 +0000135 if (state == TimerState::STOPPED) {
136 break;
137 }
138
139 if (state == TimerState::WAITING && (triggerTime - mClock->now()) <= zero) {
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700140 triggerTimeout = true;
141 state = TimerState::IDLE;
Alec Mouriaadcf942022-05-11 01:22:42 +0000142 break;
143 }
144
145 if (state == TimerState::RESET) {
146 triggerTime = mLastResetTime.load() + mInterval;
147 state = TimerState::WAITING;
Ana Krulecfb772822018-11-30 10:44:07 +0100148 }
Ana Krulecfb772822018-11-30 10:44:07 +0100149 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700150
Ady Abrahama1a49af2019-02-07 14:36:55 -0800151 if (triggerTimeout && mTimeoutCallback) {
152 mTimeoutCallback();
153 }
Ana Krulecfb772822018-11-30 10:44:07 +0100154 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800155}
Ana Krulecfb772822018-11-30 10:44:07 +0100156
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700157OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
158 // Stop takes precedence of the reset.
159 if (mStopTriggered.exchange(false)) {
160 return TimerState::STOPPED;
Ana Krulecfb772822018-11-30 10:44:07 +0100161 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700162 // If the state was stopped, the thread was joined, and we cannot reset
163 // the timer anymore.
164 if (state != TimerState::STOPPED && mResetTriggered.exchange(false)) {
165 return TimerState::RESET;
166 }
167 return state;
168}
169
170void OneShotTimer::reset() {
Alec Mouriaadcf942022-05-11 01:22:42 +0000171 mLastResetTime = mClock->now();
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700172 mResetTriggered = true;
Alec Mouriaadcf942022-05-11 01:22:42 +0000173 // If mWaiting is true, then we are guaranteed to be in a block where we are waiting on
174 // mSemaphore for a timeout, rather than idling. So we can avoid a sem_post call since we can
175 // just check that we triggered a reset on timeout.
176 if (!mWaiting) {
177 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
178 }
Ana Krulecfb772822018-11-30 10:44:07 +0100179}
180
Dominik Laskowski49cea512019-11-12 14:13:23 -0800181std::string OneShotTimer::dump() const {
182 std::ostringstream stream;
183 stream << mInterval.count() << " ms";
184 return stream.str();
185}
186
Ana Krulecfb772822018-11-30 10:44:07 +0100187} // namespace scheduler
188} // namespace android