• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 #undef LOG_TAG
18 #define LOG_TAG "SchedulerTimer"
19 
20 #include <chrono>
21 #include <cstdint>
22 
23 #include <sys/epoll.h>
24 #include <sys/timerfd.h>
25 #include <sys/unistd.h>
26 
27 #include <ftl/concat.h>
28 #include <ftl/enum.h>
29 #include <log/log.h>
30 #include <utils/Trace.h>
31 
32 #include <scheduler/Timer.h>
33 
34 namespace android::scheduler {
35 
36 constexpr size_t kReadPipe = 0;
37 constexpr size_t kWritePipe = 1;
38 
39 Clock::~Clock() = default;
40 TimeKeeper::~TimeKeeper() = default;
41 
Timer()42 Timer::Timer() {
43     reset();
44     mDispatchThread = std::thread([this]() { threadMain(); });
45 }
46 
~Timer()47 Timer::~Timer() {
48     endDispatch();
49     mDispatchThread.join();
50     cleanup();
51 }
52 
reset()53 void Timer::reset() {
54     std::function<void()> cb;
55     {
56         std::lock_guard lock(mMutex);
57         if (mExpectingCallback && mCallback) {
58             cb = mCallback;
59         }
60 
61         cleanup();
62         mTimerFd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
63         mEpollFd = epoll_create1(EPOLL_CLOEXEC);
64         if (pipe2(mPipes.data(), O_CLOEXEC | O_NONBLOCK)) {
65             ALOGE("could not create TimerDispatch mPipes");
66         }
67     }
68     if (cb) {
69         setDebugState(DebugState::InCallback);
70         cb();
71         setDebugState(DebugState::Running);
72     }
73     setDebugState(DebugState::Reset);
74 }
75 
cleanup()76 void Timer::cleanup() {
77     if (mTimerFd != -1) {
78         close(mTimerFd);
79         mTimerFd = -1;
80     }
81 
82     if (mEpollFd != -1) {
83         close(mEpollFd);
84         mEpollFd = -1;
85     }
86 
87     if (mPipes[kReadPipe] != -1) {
88         close(mPipes[kReadPipe]);
89         mPipes[kReadPipe] = -1;
90     }
91 
92     if (mPipes[kWritePipe] != -1) {
93         close(mPipes[kWritePipe]);
94         mPipes[kWritePipe] = -1;
95     }
96     mExpectingCallback = false;
97     mCallback = {};
98 }
99 
endDispatch()100 void Timer::endDispatch() {
101     static constexpr unsigned char end = 'e';
102     write(mPipes[kWritePipe], &end, sizeof(end));
103 }
104 
now() const105 nsecs_t Timer::now() const {
106     return systemTime(SYSTEM_TIME_MONOTONIC);
107 }
108 
alarmAt(std::function<void ()> callback,nsecs_t time)109 void Timer::alarmAt(std::function<void()> callback, nsecs_t time) {
110     std::lock_guard lock(mMutex);
111     using namespace std::literals;
112     static constexpr int ns_per_s =
113             std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
114 
115     mCallback = std::move(callback);
116     mExpectingCallback = true;
117 
118     struct itimerspec old_timer;
119     struct itimerspec new_timer {
120         .it_interval = {.tv_sec = 0, .tv_nsec = 0},
121         .it_value = {.tv_sec = static_cast<long>(time / ns_per_s),
122                      .tv_nsec = static_cast<long>(time % ns_per_s)},
123     };
124 
125     if (timerfd_settime(mTimerFd, TFD_TIMER_ABSTIME, &new_timer, &old_timer)) {
126         ALOGW("Failed to set timerfd %s (%i)", strerror(errno), errno);
127     }
128 }
129 
alarmCancel()130 void Timer::alarmCancel() {
131     std::lock_guard lock(mMutex);
132 
133     struct itimerspec old_timer;
134     struct itimerspec new_timer {
135         .it_interval = {.tv_sec = 0, .tv_nsec = 0},
136         .it_value = {
137                 .tv_sec = 0,
138                 .tv_nsec = 0,
139         },
140     };
141 
142     if (timerfd_settime(mTimerFd, 0, &new_timer, &old_timer)) {
143         ALOGW("Failed to disarm timerfd");
144     }
145 }
146 
threadMain()147 void Timer::threadMain() {
148     while (dispatch()) {
149         reset();
150     }
151 }
152 
dispatch()153 bool Timer::dispatch() {
154     setDebugState(DebugState::Running);
155     struct sched_param param = {0};
156     param.sched_priority = 2;
157     if (pthread_setschedparam(pthread_self(), SCHED_FIFO, &param) != 0) {
158         ALOGW("Failed to set SCHED_FIFO on dispatch thread");
159     }
160 
161     if (pthread_setname_np(pthread_self(), "TimerDispatch")) {
162         ALOGW("Failed to set thread name on dispatch thread");
163     }
164 
165     enum DispatchType : uint32_t { TIMER, TERMINATE, MAX_DISPATCH_TYPE };
166     epoll_event timerEvent;
167     timerEvent.events = EPOLLIN;
168     timerEvent.data.u32 = DispatchType::TIMER;
169     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mTimerFd, &timerEvent) == -1) {
170         ALOGE("Error adding timer fd to epoll dispatch loop");
171         return true;
172     }
173 
174     epoll_event terminateEvent;
175     terminateEvent.events = EPOLLIN;
176     terminateEvent.data.u32 = DispatchType::TERMINATE;
177     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mPipes[kReadPipe], &terminateEvent) == -1) {
178         ALOGE("Error adding control fd to dispatch loop");
179         return true;
180     }
181 
182     uint64_t iteration = 0;
183 
184     while (true) {
185         setDebugState(DebugState::Waiting);
186         epoll_event events[DispatchType::MAX_DISPATCH_TYPE];
187         int nfds = epoll_wait(mEpollFd, events, DispatchType::MAX_DISPATCH_TYPE, -1);
188 
189         setDebugState(DebugState::Running);
190         if (ATRACE_ENABLED()) {
191             ftl::Concat trace("TimerIteration #", iteration++);
192             ATRACE_NAME(trace.c_str());
193         }
194 
195         if (nfds == -1) {
196             if (errno != EINTR) {
197                 ALOGE("Error waiting on epoll: %s", strerror(errno));
198                 return true;
199             }
200         }
201 
202         for (auto i = 0; i < nfds; i++) {
203             if (events[i].data.u32 == DispatchType::TIMER) {
204                 static uint64_t mIgnored = 0;
205                 setDebugState(DebugState::Reading);
206                 read(mTimerFd, &mIgnored, sizeof(mIgnored));
207                 setDebugState(DebugState::Running);
208                 std::function<void()> cb;
209                 {
210                     std::lock_guard lock(mMutex);
211                     cb = mCallback;
212                     mExpectingCallback = false;
213                 }
214                 if (cb) {
215                     setDebugState(DebugState::InCallback);
216                     cb();
217                     setDebugState(DebugState::Running);
218                 }
219             }
220             if (events[i].data.u32 == DispatchType::TERMINATE) {
221                 ALOGE("Terminated");
222                 setDebugState(DebugState::Running);
223                 return false;
224             }
225         }
226     }
227 }
228 
setDebugState(DebugState state)229 void Timer::setDebugState(DebugState state) {
230     std::lock_guard lock(mMutex);
231     mDebugState = state;
232 }
233 
dump(std::string & result) const234 void Timer::dump(std::string& result) const {
235     std::lock_guard lock(mMutex);
236     result.append("\t\tDebugState: ");
237     result.append(ftl::enum_string(mDebugState));
238     result.push_back('\n');
239 }
240 
241 } // namespace android::scheduler
242