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 #pragma once
18 
19 #include <array>
20 #include <functional>
21 #include <mutex>
22 #include <thread>
23 
24 #include <android-base/thread_annotations.h>
25 
26 #include <scheduler/TimeKeeper.h>
27 
28 namespace android::scheduler {
29 
30 class Timer : public TimeKeeper {
31 public:
32     Timer();
33     ~Timer();
34 
35     nsecs_t now() const final;
36 
37     // NB: alarmAt and alarmCancel are threadsafe; with the last-returning function being effectual
38     //     Most users will want to serialize thes calls so as to be aware of the timer state.
39     void alarmAt(std::function<void()>, nsecs_t time) final;
40     void alarmCancel() final;
41 
42     void dump(std::string&) const final;
43 
44 protected:
45     // For unit testing
46     int mEpollFd = -1;
47 
48 private:
49     enum class DebugState {
50         Reset,
51         Running,
52         Waiting,
53         Reading,
54         InCallback,
55         Terminated,
56 
57         ftl_last = Terminated
58     };
59 
60     void reset() EXCLUDES(mMutex);
61     void cleanup() REQUIRES(mMutex);
62     void setDebugState(DebugState) EXCLUDES(mMutex);
63     void setCallback(std::function<void()>&&) REQUIRES(mMutex);
64 
65     int mTimerFd = -1;
66 
67     std::array<int, 2> mPipes = {-1, -1};
68 
69     std::thread mDispatchThread;
70     void threadMain();
71     bool dispatch();
72     void endDispatch();
73 
74     mutable std::mutex mMutex;
75 
76     std::function<void()> mCallback GUARDED_BY(mMutex);
77     bool mExpectingCallback GUARDED_BY(mMutex) = false;
78     DebugState mDebugState GUARDED_BY(mMutex);
79 };
80 
81 } // namespace android::scheduler
82