1 /*
2 * Copyright (C) 2009 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 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19 #include <binder/IPCThreadState.h>
20
21 #include <utils/Log.h>
22 #include <utils/Timers.h>
23 #include <utils/threads.h>
24
25 #include <gui/DisplayEventReceiver.h>
26
27 #include "EventThread.h"
28 #include "FrameTimeline.h"
29 #include "MessageQueue.h"
30 #include "SurfaceFlinger.h"
31
32 namespace android::impl {
33
dispatchRefresh()34 void MessageQueue::Handler::dispatchRefresh() {
35 if ((mEventMask.fetch_or(eventMaskRefresh) & eventMaskRefresh) == 0) {
36 mQueue.mLooper->sendMessage(this, Message(MessageQueue::REFRESH));
37 }
38 }
39
dispatchInvalidate(int64_t vsyncId,nsecs_t expectedVSyncTimestamp)40 void MessageQueue::Handler::dispatchInvalidate(int64_t vsyncId, nsecs_t expectedVSyncTimestamp) {
41 if ((mEventMask.fetch_or(eventMaskInvalidate) & eventMaskInvalidate) == 0) {
42 mVsyncId = vsyncId;
43 mExpectedVSyncTime = expectedVSyncTimestamp;
44 mQueue.mLooper->sendMessage(this, Message(MessageQueue::INVALIDATE));
45 }
46 }
47
invalidatePending()48 bool MessageQueue::Handler::invalidatePending() {
49 constexpr auto pendingMask = eventMaskInvalidate | eventMaskRefresh;
50 return (mEventMask.load() & pendingMask) != 0;
51 }
52
handleMessage(const Message & message)53 void MessageQueue::Handler::handleMessage(const Message& message) {
54 switch (message.what) {
55 case INVALIDATE:
56 mEventMask.fetch_and(~eventMaskInvalidate);
57 mQueue.mFlinger->onMessageReceived(message.what, mVsyncId, mExpectedVSyncTime);
58 break;
59 case REFRESH:
60 mEventMask.fetch_and(~eventMaskRefresh);
61 mQueue.mFlinger->onMessageReceived(message.what, mVsyncId, mExpectedVSyncTime);
62 break;
63 }
64 }
65
66 // ---------------------------------------------------------------------------
67
init(const sp<SurfaceFlinger> & flinger)68 void MessageQueue::init(const sp<SurfaceFlinger>& flinger) {
69 mFlinger = flinger;
70 mLooper = new Looper(true);
71 mHandler = new Handler(*this);
72 }
73
74 // TODO(b/169865816): refactor VSyncInjections to use MessageQueue directly
75 // and remove the EventThread from MessageQueue
setInjector(sp<EventThreadConnection> connection)76 void MessageQueue::setInjector(sp<EventThreadConnection> connection) {
77 auto& tube = mInjector.tube;
78
79 if (const int fd = tube.getFd(); fd >= 0) {
80 mLooper->removeFd(fd);
81 }
82
83 if (connection) {
84 // The EventThreadConnection is retained when disabling injection, so avoid subsequently
85 // stealing invalid FDs. Note that the stolen FDs are kept open.
86 if (tube.getFd() < 0) {
87 connection->stealReceiveChannel(&tube);
88 } else {
89 ALOGW("Recycling channel for VSYNC injection.");
90 }
91
92 mLooper->addFd(
93 tube.getFd(), 0, Looper::EVENT_INPUT,
94 [](int, int, void* data) {
95 reinterpret_cast<MessageQueue*>(data)->injectorCallback();
96 return 1; // Keep registration.
97 },
98 this);
99 }
100
101 std::lock_guard lock(mInjector.mutex);
102 mInjector.connection = std::move(connection);
103 }
104
vsyncCallback(nsecs_t vsyncTime,nsecs_t targetWakeupTime,nsecs_t readyTime)105 void MessageQueue::vsyncCallback(nsecs_t vsyncTime, nsecs_t targetWakeupTime, nsecs_t readyTime) {
106 ATRACE_CALL();
107 // Trace VSYNC-sf
108 mVsync.value = (mVsync.value + 1) % 2;
109
110 {
111 std::lock_guard lock(mVsync.mutex);
112 mVsync.lastCallbackTime = std::chrono::nanoseconds(vsyncTime);
113 mVsync.scheduled = false;
114 }
115 mHandler->dispatchInvalidate(mVsync.tokenManager->generateTokenForPredictions(
116 {targetWakeupTime, readyTime, vsyncTime}),
117 vsyncTime);
118 }
119
initVsync(scheduler::VSyncDispatch & dispatch,frametimeline::TokenManager & tokenManager,std::chrono::nanoseconds workDuration)120 void MessageQueue::initVsync(scheduler::VSyncDispatch& dispatch,
121 frametimeline::TokenManager& tokenManager,
122 std::chrono::nanoseconds workDuration) {
123 setDuration(workDuration);
124 mVsync.tokenManager = &tokenManager;
125 mVsync.registration = std::make_unique<
126 scheduler::VSyncCallbackRegistration>(dispatch,
127 std::bind(&MessageQueue::vsyncCallback, this,
128 std::placeholders::_1,
129 std::placeholders::_2,
130 std::placeholders::_3),
131 "sf");
132 }
133
setDuration(std::chrono::nanoseconds workDuration)134 void MessageQueue::setDuration(std::chrono::nanoseconds workDuration) {
135 ATRACE_CALL();
136 std::lock_guard lock(mVsync.mutex);
137 mVsync.workDuration = workDuration;
138 if (mVsync.scheduled) {
139 mVsync.expectedWakeupTime = mVsync.registration->schedule(
140 {mVsync.workDuration.get().count(),
141 /*readyDuration=*/0, mVsync.lastCallbackTime.count()});
142 }
143 }
144
waitMessage()145 void MessageQueue::waitMessage() {
146 do {
147 IPCThreadState::self()->flushCommands();
148 int32_t ret = mLooper->pollOnce(-1);
149 switch (ret) {
150 case Looper::POLL_WAKE:
151 case Looper::POLL_CALLBACK:
152 continue;
153 case Looper::POLL_ERROR:
154 ALOGE("Looper::POLL_ERROR");
155 continue;
156 case Looper::POLL_TIMEOUT:
157 // timeout (should not happen)
158 continue;
159 default:
160 // should not happen
161 ALOGE("Looper::pollOnce() returned unknown status %d", ret);
162 continue;
163 }
164 } while (true);
165 }
166
postMessage(sp<MessageHandler> && handler)167 void MessageQueue::postMessage(sp<MessageHandler>&& handler) {
168 mLooper->sendMessage(handler, Message());
169 }
170
invalidate()171 void MessageQueue::invalidate() {
172 ATRACE_CALL();
173
174 {
175 std::lock_guard lock(mInjector.mutex);
176 if (CC_UNLIKELY(mInjector.connection)) {
177 ALOGD("%s while injecting VSYNC", __FUNCTION__);
178 mInjector.connection->requestNextVsync();
179 return;
180 }
181 }
182
183 std::lock_guard lock(mVsync.mutex);
184 mVsync.scheduled = true;
185 mVsync.expectedWakeupTime =
186 mVsync.registration->schedule({.workDuration = mVsync.workDuration.get().count(),
187 .readyDuration = 0,
188 .earliestVsync = mVsync.lastCallbackTime.count()});
189 }
190
refresh()191 void MessageQueue::refresh() {
192 mHandler->dispatchRefresh();
193 }
194
injectorCallback()195 void MessageQueue::injectorCallback() {
196 ssize_t n;
197 DisplayEventReceiver::Event buffer[8];
198 while ((n = DisplayEventReceiver::getEvents(&mInjector.tube, buffer, 8)) > 0) {
199 for (int i = 0; i < n; i++) {
200 if (buffer[i].header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
201 mHandler->dispatchInvalidate(buffer[i].vsync.vsyncId,
202 buffer[i].vsync.expectedVSyncTimestamp);
203 break;
204 }
205 }
206 }
207 }
208
nextExpectedInvalidate()209 std::optional<std::chrono::steady_clock::time_point> MessageQueue::nextExpectedInvalidate() {
210 if (mHandler->invalidatePending()) {
211 return std::chrono::steady_clock::now();
212 }
213
214 std::lock_guard lock(mVsync.mutex);
215 if (mVsync.scheduled) {
216 LOG_ALWAYS_FATAL_IF(!mVsync.expectedWakeupTime.has_value(), "callback was never scheduled");
217 const auto expectedWakeupTime = std::chrono::nanoseconds(*mVsync.expectedWakeupTime);
218 return std::optional<std::chrono::steady_clock::time_point>(expectedWakeupTime);
219 }
220
221 return std::nullopt;
222 }
223
224 } // namespace android::impl
225