• 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     LOG_ALWAYS_FATAL_IF(!mClock, "Clock must not be provided");
51 }
52 
~OneShotTimer()53 OneShotTimer::~OneShotTimer() {
54     stop();
55 }
56 
start()57 void OneShotTimer::start() {
58     int result = sem_init(&mSemaphore, 0, 0);
59     LOG_ALWAYS_FATAL_IF(result, "sem_init failed");
60 
61     if (!mThread.joinable()) {
62         // Only create thread if it has not been created.
63         mThread = std::thread(&OneShotTimer::loop, this);
64     }
65 }
66 
stop()67 void OneShotTimer::stop() {
68     mStopTriggered = true;
69     int result = sem_post(&mSemaphore);
70     LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
71 
72     if (mThread.joinable()) {
73         mThread.join();
74         result = sem_destroy(&mSemaphore);
75         LOG_ALWAYS_FATAL_IF(result, "sem_destroy failed");
76     }
77 }
78 
loop()79 void OneShotTimer::loop() {
80     if (pthread_setname_np(pthread_self(), mName.c_str())) {
81         ALOGW("Failed to set thread name on dispatch thread");
82     }
83 
84     TimerState state = TimerState::RESET;
85     while (true) {
86         bool triggerReset = false;
87         bool triggerTimeout = false;
88 
89         state = checkForResetAndStop(state);
90         if (state == TimerState::STOPPED) {
91             break;
92         }
93 
94         if (state == TimerState::IDLE) {
95             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             }
101             continue;
102         }
103 
104         if (state == TimerState::RESET) {
105             triggerReset = true;
106         }
107 
108         if (triggerReset && mResetCallback) {
109             mResetCallback();
110         }
111 
112         state = checkForResetAndStop(state);
113         if (state == TimerState::STOPPED) {
114             break;
115         }
116 
117         auto triggerTime = mClock->now() + mInterval;
118         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);
124             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             }
130 
131             state = checkForResetAndStop(state);
132             if (state == TimerState::RESET) {
133                 triggerTime = mClock->now() + mInterval;
134                 state = TimerState::WAITING;
135             } else if (state == TimerState::WAITING && (triggerTime - mClock->now()) <= zero) {
136                 triggerTimeout = true;
137                 state = TimerState::IDLE;
138             }
139         }
140 
141         if (triggerTimeout && mTimeoutCallback) {
142             mTimeoutCallback();
143         }
144     }
145 }
146 
checkForResetAndStop(TimerState state)147 OneShotTimer::TimerState OneShotTimer::checkForResetAndStop(TimerState state) {
148     // Stop takes precedence of the reset.
149     if (mStopTriggered.exchange(false)) {
150         return TimerState::STOPPED;
151     }
152     // 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 
reset()160 void OneShotTimer::reset() {
161     mResetTriggered = true;
162     int result = sem_post(&mSemaphore);
163     LOG_ALWAYS_FATAL_IF(result, "sem_post failed");
164 }
165 
dump() const166 std::string OneShotTimer::dump() const {
167     std::ostringstream stream;
168     stream << mInterval.count() << " ms";
169     return stream.str();
170 }
171 
172 } // namespace scheduler
173 } // namespace android
174