• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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;
119         state = TimerState::WAITING;
120         while (true) {
121             // 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                 }
132             }
133 
134             mWaiting = false;
135             state = checkForResetAndStop(state);
136             if (state == TimerState::STOPPED) {
137                 break;
138             }
139 
140             if (state == TimerState::WAITING && (triggerTime - mClock->now()) <= 0ns) {
141                 triggerTimeout = true;
142                 state = TimerState::IDLE;
143                 break;
144             }
145 
146             if (state == TimerState::RESET) {
147                 triggerTime = mLastResetTime.load() + mInterval;
148                 state = TimerState::WAITING;
149             }
150         }
151 
152         if (triggerTimeout && mTimeoutCallback) {
153             mTimeoutCallback();
154         }
155     }
156 }
157 
checkForResetAndStop(TimerState state)158 OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
159     // Stop takes precedence of the reset.
160     if (mStopTriggered.exchange(false)) {
161         return TimerState::STOPPED;
162     }
163     // 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 
reset()171 void OneShotTimer::reset() {
172     mLastResetTime = mClock->now();
173     mResetTriggered = true;
174     // 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     }
180 }
181 
dump() const182 std::string OneShotTimer::dump() const {
183     std::ostringstream stream;
184     stream << mInterval.count() << " ms";
185     return stream.str();
186 }
187 
188 } // namespace scheduler
189 } // namespace android
190