1 /*
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
17 #include "OneShotTimer.h"
18 #include <utils/Log.h>
19 #include <utils/Timers.h>
20 #include <chrono>
21 #include <sstream>
22 #include <thread>
23
24 namespace {
25 using namespace std::chrono_literals;
26
27 constexpr 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.
calculateTimeoutTime(std::chrono::nanoseconds timestamp,timespec * spec)32 void calculateTimeoutTime(std::chrono::nanoseconds timestamp, timespec* spec) {
33 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;
36 }
37 } // namespace
38
39 namespace android {
40 namespace scheduler {
41
OneShotTimer(std::string name,const Interval & interval,const ResetCallback & resetCallback,const TimeoutCallback & timeoutCallback,std::unique_ptr<Clock> clock)42 OneShotTimer::OneShotTimer(std::string name, const Interval& interval,
43 const ResetCallback& resetCallback,
44 const TimeoutCallback& timeoutCallback, std::unique_ptr<Clock> clock)
45 : mClock(std::move(clock)),
46 mName(std::move(name)),
47 mInterval(interval),
48 mResetCallback(resetCallback),
49 mTimeoutCallback(timeoutCallback) {
50 mLastResetTime = std::chrono::steady_clock::time_point::min();
51 LOG_ALWAYS_FATAL_IF(!mClock, "Clock must not be provided");
52 }
53
~OneShotTimer()54 OneShotTimer::~OneShotTimer() {
55 stop();
56 }
57
start()58 void OneShotTimer::start() {
59 int result = sem_init(&mSemaphore, 0, 0);
60 LOG_ALWAYS_FATAL_IF(result, "sem_init failed");
61
62 if (!mThread.joinable()) {
63 // Only create thread if it has not been created.
64 mThread = std::thread(&OneShotTimer::loop, this);
65 }
66 }
67
stop()68 void OneShotTimer::stop() {
69 mStopTriggered = true;
70 int result = sem_post(&mSemaphore);
71 LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
72
73 if (mThread.joinable()) {
74 mThread.join();
75 result = sem_destroy(&mSemaphore);
76 LOG_ALWAYS_FATAL_IF(result, "sem_destroy failed");
77 }
78 }
79
loop()80 void OneShotTimer::loop() {
81 if (pthread_setname_np(pthread_self(), mName.c_str())) {
82 ALOGW("Failed to set thread name on dispatch thread");
83 }
84
85 TimerState state = TimerState::RESET;
86 while (true) {
87 bool triggerReset = false;
88 bool triggerTimeout = false;
89
90 state = checkForResetAndStop(state);
91 if (state == TimerState::STOPPED) {
92 break;
93 }
94
95 if (state == TimerState::IDLE) {
96 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 }
102 continue;
103 }
104
105 if (state == TimerState::RESET) {
106 triggerReset = true;
107 }
108
109 if (triggerReset && mResetCallback) {
110 mResetCallback();
111 }
112
113 state = checkForResetAndStop(state);
114 if (state == TimerState::STOPPED) {
115 break;
116 }
117
118 auto triggerTime = mClock->now() + mInterval.load();
119 state = TimerState::WAITING;
120 while (true) {
121 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 }
136 // 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 }
147 }
148
149 mWaiting = false;
150 state = checkForResetAndStop(state);
151 if (state == TimerState::STOPPED) {
152 break;
153 }
154
155 if (!mPaused && state == TimerState::WAITING && (triggerTime - mClock->now()) <= 0ns) {
156 triggerTimeout = true;
157 state = TimerState::IDLE;
158 break;
159 }
160
161 if (state == TimerState::RESET) {
162 triggerTime = mLastResetTime.load() + mInterval.load();
163 state = TimerState::WAITING;
164 }
165 }
166
167 if (triggerTimeout && mTimeoutCallback) {
168 mTimeoutCallback();
169 }
170 }
171 }
172
checkForResetAndStop(TimerState state)173 OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
174 // Stop takes precedence of the reset.
175 if (mStopTriggered.exchange(false)) {
176 return TimerState::STOPPED;
177 }
178 // 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
reset()186 void OneShotTimer::reset() {
187 mLastResetTime = mClock->now();
188 mResetTriggered = true;
189 // 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 }
195 }
196
pause()197 void OneShotTimer::pause() {
198 mPaused = true;
199 }
200
resume()201 void OneShotTimer::resume() {
202 if (mPaused.exchange(false)) {
203 LOG_ALWAYS_FATAL_IF(sem_post(&mSemaphore), "sem_post failed");
204 }
205 }
206
207 } // namespace scheduler
208 } // namespace android
209