blob: ce3b0c6cfaf7b515237e275998b1418f76535848 [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"
Ana Krulecfb772822018-11-30 10:44:07 +010018
Ady Abraham1e19ac92020-11-17 16:56:00 -080019#include <utils/Log.h>
20#include <utils/Timers.h>
Ana Krulecfb772822018-11-30 10:44:07 +010021#include <chrono>
Dominik Laskowski49cea512019-11-12 14:13:23 -080022#include <sstream>
Ana Krulecfb772822018-11-30 10:44:07 +010023#include <thread>
24
Ana Krulec75d4ffc2020-10-16 14:56:19 -070025namespace {
26using namespace std::chrono_literals;
27
28constexpr int64_t kNsToSeconds = std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
29
30// The syscall interface uses a pair of integers for the timestamp. The first
31// (tv_sec) is the whole count of seconds. The second (tv_nsec) is the
32// nanosecond part of the count. This function takes care of translation.
33void calculateTimeoutTime(std::chrono::nanoseconds timestamp, timespec* spec) {
Ady Abraham1e19ac92020-11-17 16:56:00 -080034 const nsecs_t timeout = systemTime(CLOCK_MONOTONIC) + timestamp.count();
35 spec->tv_sec = static_cast<__kernel_time_t>(timeout / kNsToSeconds);
36 spec->tv_nsec = timeout % kNsToSeconds;
Ana Krulec75d4ffc2020-10-16 14:56:19 -070037}
38} // namespace
39
Ana Krulecfb772822018-11-30 10:44:07 +010040namespace android {
41namespace scheduler {
42
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080043OneShotTimer::OneShotTimer(std::string name, const Interval& interval,
44 const ResetCallback& resetCallback,
Ana Krulecf2c006d2019-06-21 15:37:07 -070045 const TimeoutCallback& timeoutCallback)
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080046 : mName(std::move(name)),
47 mInterval(interval),
48 mResetCallback(resetCallback),
49 mTimeoutCallback(timeoutCallback) {}
Ana Krulecfb772822018-11-30 10:44:07 +010050
Ana Krulecf2c006d2019-06-21 15:37:07 -070051OneShotTimer::~OneShotTimer() {
Ana Krulecfb772822018-11-30 10:44:07 +010052 stop();
53}
54
Ana Krulecf2c006d2019-06-21 15:37:07 -070055void OneShotTimer::start() {
Ady Abraham1e19ac92020-11-17 16:56:00 -080056 int result = sem_init(&mSemaphore, 0, 0);
57 LOG_ALWAYS_FATAL_IF(result, "sem_init failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070058
59 if (!mThread.joinable()) {
60 // Only create thread if it has not been created.
61 mThread = std::thread(&OneShotTimer::loop, this);
Ana Krulecfb772822018-11-30 10:44:07 +010062 }
Ana Krulecfb772822018-11-30 10:44:07 +010063}
64
Ana Krulecf2c006d2019-06-21 15:37:07 -070065void OneShotTimer::stop() {
Ana Krulec75d4ffc2020-10-16 14:56:19 -070066 mStopTriggered = true;
Ady Abraham1e19ac92020-11-17 16:56:00 -080067 int result = sem_post(&mSemaphore);
68 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070069
Ana Krulecfb772822018-11-30 10:44:07 +010070 if (mThread.joinable()) {
71 mThread.join();
Ady Abraham1e19ac92020-11-17 16:56:00 -080072 result = sem_destroy(&mSemaphore);
73 LOG_ALWAYS_FATAL_IF(result, "sem_destroy failed");
Ana Krulecfb772822018-11-30 10:44:07 +010074 }
75}
76
Ana Krulecf2c006d2019-06-21 15:37:07 -070077void OneShotTimer::loop() {
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080078 if (pthread_setname_np(pthread_self(), mName.c_str())) {
79 ALOGW("Failed to set thread name on dispatch thread");
80 }
81
Ana Krulec75d4ffc2020-10-16 14:56:19 -070082 TimerState state = TimerState::RESET;
Ady Abrahama1a49af2019-02-07 14:36:55 -080083 while (true) {
84 bool triggerReset = false;
85 bool triggerTimeout = false;
Ady Abrahama1a49af2019-02-07 14:36:55 -080086
Ana Krulec75d4ffc2020-10-16 14:56:19 -070087 state = checkForResetAndStop(state);
88 if (state == TimerState::STOPPED) {
89 break;
Ady Abrahama1a49af2019-02-07 14:36:55 -080090 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -070091
92 if (state == TimerState::IDLE) {
Ady Abraham1e19ac92020-11-17 16:56:00 -080093 int result = sem_wait(&mSemaphore);
94 if (result && errno != EINTR) {
95 std::stringstream ss;
96 ss << "sem_wait failed (" << errno << ")";
97 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
98 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -070099 continue;
100 }
101
102 if (state == TimerState::RESET) {
103 triggerReset = true;
104 }
105
Ady Abrahama1a49af2019-02-07 14:36:55 -0800106 if (triggerReset && mResetCallback) {
107 mResetCallback();
108 }
109
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700110 state = checkForResetAndStop(state);
111 if (state == TimerState::STOPPED) {
112 break;
113 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800114
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700115 auto triggerTime = std::chrono::steady_clock::now() + mInterval;
116 state = TimerState::WAITING;
117 while (state == TimerState::WAITING) {
118 constexpr auto zero = std::chrono::steady_clock::duration::zero();
119 // Wait for mInterval time for semaphore signal.
120 struct timespec ts;
121 calculateTimeoutTime(std::chrono::nanoseconds(mInterval), &ts);
Ady Abraham1e19ac92020-11-17 16:56:00 -0800122 int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &ts);
123 if (result && errno != ETIMEDOUT && errno != EINTR) {
124 std::stringstream ss;
125 ss << "sem_clockwait failed (" << errno << ")";
126 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
127 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700128
129 state = checkForResetAndStop(state);
130 if (state == TimerState::RESET) {
131 triggerTime = std::chrono::steady_clock::now() + mInterval;
132 state = TimerState::WAITING;
133 } else if (state == TimerState::WAITING &&
134 (triggerTime - std::chrono::steady_clock::now()) <= zero) {
135 triggerTimeout = true;
136 state = TimerState::IDLE;
Ana Krulecfb772822018-11-30 10:44:07 +0100137 }
Ana Krulecfb772822018-11-30 10:44:07 +0100138 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700139
Ady Abrahama1a49af2019-02-07 14:36:55 -0800140 if (triggerTimeout && mTimeoutCallback) {
141 mTimeoutCallback();
142 }
Ana Krulecfb772822018-11-30 10:44:07 +0100143 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800144}
Ana Krulecfb772822018-11-30 10:44:07 +0100145
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700146OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
147 // Stop takes precedence of the reset.
148 if (mStopTriggered.exchange(false)) {
149 return TimerState::STOPPED;
Ana Krulecfb772822018-11-30 10:44:07 +0100150 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700151 // If the state was stopped, the thread was joined, and we cannot reset
152 // the timer anymore.
153 if (state != TimerState::STOPPED && mResetTriggered.exchange(false)) {
154 return TimerState::RESET;
155 }
156 return state;
157}
158
159void OneShotTimer::reset() {
160 mResetTriggered = true;
Ady Abraham1e19ac92020-11-17 16:56:00 -0800161 int result = sem_post(&mSemaphore);
162 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
Ana Krulecfb772822018-11-30 10:44:07 +0100163}
164
Dominik Laskowski49cea512019-11-12 14:13:23 -0800165std::string OneShotTimer::dump() const {
166 std::ostringstream stream;
167 stream << mInterval.count() << " ms";
168 return stream.str();
169}
170
Ana Krulecfb772822018-11-30 10:44:07 +0100171} // namespace scheduler
172} // namespace android