blob: 16f041ae3152d3b8a53f4939843fe6926a364e1b [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) {
50 LOG_ALWAYS_FATAL_IF(!mClock, "Clock must not be provided");
51}
Ana Krulecfb772822018-11-30 10:44:07 +010052
Ana Krulecf2c006d2019-06-21 15:37:07 -070053OneShotTimer::~OneShotTimer() {
Ana Krulecfb772822018-11-30 10:44:07 +010054 stop();
55}
56
Ana Krulecf2c006d2019-06-21 15:37:07 -070057void OneShotTimer::start() {
Ady Abraham1e19ac92020-11-17 16:56:00 -080058 int result = sem_init(&mSemaphore, 0, 0);
59 LOG_ALWAYS_FATAL_IF(result, "sem_init failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070060
61 if (!mThread.joinable()) {
62 // Only create thread if it has not been created.
63 mThread = std::thread(&OneShotTimer::loop, this);
Ana Krulecfb772822018-11-30 10:44:07 +010064 }
Ana Krulecfb772822018-11-30 10:44:07 +010065}
66
Ana Krulecf2c006d2019-06-21 15:37:07 -070067void OneShotTimer::stop() {
Ana Krulec75d4ffc2020-10-16 14:56:19 -070068 mStopTriggered = true;
Ady Abraham1e19ac92020-11-17 16:56:00 -080069 int result = sem_post(&mSemaphore);
70 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
Ana Krulec75d4ffc2020-10-16 14:56:19 -070071
Ana Krulecfb772822018-11-30 10:44:07 +010072 if (mThread.joinable()) {
73 mThread.join();
Ady Abraham1e19ac92020-11-17 16:56:00 -080074 result = sem_destroy(&mSemaphore);
75 LOG_ALWAYS_FATAL_IF(result, "sem_destroy failed");
Ana Krulecfb772822018-11-30 10:44:07 +010076 }
77}
78
Ana Krulecf2c006d2019-06-21 15:37:07 -070079void OneShotTimer::loop() {
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080080 if (pthread_setname_np(pthread_self(), mName.c_str())) {
81 ALOGW("Failed to set thread name on dispatch thread");
82 }
83
Ana Krulec75d4ffc2020-10-16 14:56:19 -070084 TimerState state = TimerState::RESET;
Ady Abrahama1a49af2019-02-07 14:36:55 -080085 while (true) {
86 bool triggerReset = false;
87 bool triggerTimeout = false;
Ady Abrahama1a49af2019-02-07 14:36:55 -080088
Ana Krulec75d4ffc2020-10-16 14:56:19 -070089 state = checkForResetAndStop(state);
90 if (state == TimerState::STOPPED) {
91 break;
Ady Abrahama1a49af2019-02-07 14:36:55 -080092 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -070093
94 if (state == TimerState::IDLE) {
Ady Abraham1e19ac92020-11-17 16:56:00 -080095 int result = sem_wait(&mSemaphore);
96 if (result && errno != EINTR) {
97 std::stringstream ss;
98 ss << "sem_wait failed (" << errno << ")";
99 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
100 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700101 continue;
102 }
103
104 if (state == TimerState::RESET) {
105 triggerReset = true;
106 }
107
Ady Abrahama1a49af2019-02-07 14:36:55 -0800108 if (triggerReset && mResetCallback) {
109 mResetCallback();
110 }
111
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700112 state = checkForResetAndStop(state);
113 if (state == TimerState::STOPPED) {
114 break;
115 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800116
Ady Abraham018ff0b2021-04-19 23:39:36 -0700117 auto triggerTime = mClock->now() + mInterval;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700118 state = TimerState::WAITING;
119 while (state == TimerState::WAITING) {
120 constexpr auto zero = std::chrono::steady_clock::duration::zero();
121 // Wait for mInterval time for semaphore signal.
122 struct timespec ts;
123 calculateTimeoutTime(std::chrono::nanoseconds(mInterval), &ts);
Ady Abraham1e19ac92020-11-17 16:56:00 -0800124 int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &ts);
125 if (result && errno != ETIMEDOUT && errno != EINTR) {
126 std::stringstream ss;
127 ss << "sem_clockwait failed (" << errno << ")";
128 LOG_ALWAYS_FATAL("%s", ss.str().c_str());
129 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700130
131 state = checkForResetAndStop(state);
132 if (state == TimerState::RESET) {
Ady Abraham018ff0b2021-04-19 23:39:36 -0700133 triggerTime = mClock->now() + mInterval;
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700134 state = TimerState::WAITING;
Ady Abraham018ff0b2021-04-19 23:39:36 -0700135 } else if (state == TimerState::WAITING && (triggerTime - mClock->now()) <= zero) {
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700136 triggerTimeout = true;
137 state = TimerState::IDLE;
Ana Krulecfb772822018-11-30 10:44:07 +0100138 }
Ana Krulecfb772822018-11-30 10:44:07 +0100139 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700140
Ady Abrahama1a49af2019-02-07 14:36:55 -0800141 if (triggerTimeout && mTimeoutCallback) {
142 mTimeoutCallback();
143 }
Ana Krulecfb772822018-11-30 10:44:07 +0100144 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800145}
Ana Krulecfb772822018-11-30 10:44:07 +0100146
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700147OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
148 // Stop takes precedence of the reset.
149 if (mStopTriggered.exchange(false)) {
150 return TimerState::STOPPED;
Ana Krulecfb772822018-11-30 10:44:07 +0100151 }
Ana Krulec75d4ffc2020-10-16 14:56:19 -0700152 // If the state was stopped, the thread was joined, and we cannot reset
153 // the timer anymore.
154 if (state != TimerState::STOPPED && mResetTriggered.exchange(false)) {
155 return TimerState::RESET;
156 }
157 return state;
158}
159
160void OneShotTimer::reset() {
161 mResetTriggered = true;
Ady Abraham1e19ac92020-11-17 16:56:00 -0800162 int result = sem_post(&mSemaphore);
163 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
Ana Krulecfb772822018-11-30 10:44:07 +0100164}
165
Dominik Laskowski49cea512019-11-12 14:13:23 -0800166std::string OneShotTimer::dump() const {
167 std::ostringstream stream;
168 stream << mInterval.count() << " ms";
169 return stream.str();
170}
171
Ana Krulecfb772822018-11-30 10:44:07 +0100172} // namespace scheduler
173} // namespace android