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 #include <gui/DisplayEventReceiver.h>
21 #include <utils/Log.h>
22 #include <utils/Timers.h>
23 #include <utils/threads.h>
24
25 #include <scheduler/interface/ICompositor.h>
26
27 #include "EventThread.h"
28 #include "FrameTimeline.h"
29 #include "MessageQueue.h"
30
31 namespace android::impl {
32
dispatchFrame(VsyncId vsyncId,TimePoint expectedVsyncTime)33 void MessageQueue::Handler::dispatchFrame(VsyncId vsyncId, TimePoint expectedVsyncTime) {
34 if (!mFramePending.exchange(true)) {
35 mVsyncId = vsyncId;
36 mExpectedVsyncTime = expectedVsyncTime;
37 mQueue.mLooper->sendMessage(sp<MessageHandler>::fromExisting(this), Message());
38 }
39 }
40
isFramePending() const41 bool MessageQueue::Handler::isFramePending() const {
42 return mFramePending.load();
43 }
44
handleMessage(const Message &)45 void MessageQueue::Handler::handleMessage(const Message&) {
46 mFramePending.store(false);
47 mQueue.onFrameSignal(mQueue.mCompositor, mVsyncId, mExpectedVsyncTime);
48 }
49
MessageQueue(ICompositor & compositor)50 MessageQueue::MessageQueue(ICompositor& compositor)
51 : MessageQueue(compositor, sp<Handler>::make(*this)) {}
52
53 constexpr bool kAllowNonCallbacks = true;
54
MessageQueue(ICompositor & compositor,sp<Handler> handler)55 MessageQueue::MessageQueue(ICompositor& compositor, sp<Handler> handler)
56 : mCompositor(compositor),
57 mLooper(sp<Looper>::make(kAllowNonCallbacks)),
58 mHandler(std::move(handler)) {}
59
vsyncCallback(nsecs_t vsyncTime,nsecs_t targetWakeupTime,nsecs_t readyTime)60 void MessageQueue::vsyncCallback(nsecs_t vsyncTime, nsecs_t targetWakeupTime, nsecs_t readyTime) {
61 ATRACE_CALL();
62 // Trace VSYNC-sf
63 mVsync.value = (mVsync.value + 1) % 2;
64
65 const auto expectedVsyncTime = TimePoint::fromNs(vsyncTime);
66 {
67 std::lock_guard lock(mVsync.mutex);
68 mVsync.lastCallbackTime = expectedVsyncTime;
69 mVsync.scheduledFrameTime.reset();
70 }
71
72 const auto vsyncId = VsyncId{mVsync.tokenManager->generateTokenForPredictions(
73 {targetWakeupTime, readyTime, vsyncTime})};
74
75 mHandler->dispatchFrame(vsyncId, expectedVsyncTime);
76 }
77
initVsync(std::shared_ptr<scheduler::VSyncDispatch> dispatch,frametimeline::TokenManager & tokenManager,std::chrono::nanoseconds workDuration)78 void MessageQueue::initVsync(std::shared_ptr<scheduler::VSyncDispatch> dispatch,
79 frametimeline::TokenManager& tokenManager,
80 std::chrono::nanoseconds workDuration) {
81 std::unique_ptr<scheduler::VSyncCallbackRegistration> oldRegistration;
82 {
83 std::lock_guard lock(mVsync.mutex);
84 mVsync.workDuration = workDuration;
85 mVsync.tokenManager = &tokenManager;
86 oldRegistration = onNewVsyncScheduleLocked(std::move(dispatch));
87 }
88
89 // See comments in onNewVsyncSchedule. Today, oldRegistration should be
90 // empty, but nothing prevents us from calling initVsync multiple times, so
91 // go ahead and destruct it outside the lock for safety.
92 oldRegistration.reset();
93 }
94
onNewVsyncSchedule(std::shared_ptr<scheduler::VSyncDispatch> dispatch)95 void MessageQueue::onNewVsyncSchedule(std::shared_ptr<scheduler::VSyncDispatch> dispatch) {
96 std::unique_ptr<scheduler::VSyncCallbackRegistration> oldRegistration;
97 {
98 std::lock_guard lock(mVsync.mutex);
99 oldRegistration = onNewVsyncScheduleLocked(std::move(dispatch));
100 }
101
102 // The old registration needs to be deleted after releasing mVsync.mutex to
103 // avoid deadlock. This is because the callback may be running on the timer
104 // thread. In that case, timerCallback sets
105 // VSyncDispatchTimerQueueEntry::mRunning to true, then attempts to lock
106 // mVsync.mutex. But if it's already locked, the VSyncCallbackRegistration's
107 // destructor has to wait until VSyncDispatchTimerQueueEntry::mRunning is
108 // set back to false, but it won't be until mVsync.mutex is released.
109 oldRegistration.reset();
110 }
111
onNewVsyncScheduleLocked(std::shared_ptr<scheduler::VSyncDispatch> dispatch)112 std::unique_ptr<scheduler::VSyncCallbackRegistration> MessageQueue::onNewVsyncScheduleLocked(
113 std::shared_ptr<scheduler::VSyncDispatch> dispatch) {
114 const bool reschedule = mVsync.registration &&
115 mVsync.registration->cancel() == scheduler::CancelResult::Cancelled;
116 auto oldRegistration = std::move(mVsync.registration);
117 mVsync.registration = std::make_unique<
118 scheduler::VSyncCallbackRegistration>(std::move(dispatch),
119 std::bind(&MessageQueue::vsyncCallback, this,
120 std::placeholders::_1,
121 std::placeholders::_2,
122 std::placeholders::_3),
123 "sf");
124 if (reschedule) {
125 mVsync.scheduledFrameTime =
126 mVsync.registration->schedule({.workDuration = mVsync.workDuration.get().count(),
127 .readyDuration = 0,
128 .earliestVsync = mVsync.lastCallbackTime.ns()});
129 }
130 return oldRegistration;
131 }
132
destroyVsync()133 void MessageQueue::destroyVsync() {
134 std::lock_guard lock(mVsync.mutex);
135 mVsync.tokenManager = nullptr;
136 mVsync.registration.reset();
137 }
138
setDuration(std::chrono::nanoseconds workDuration)139 void MessageQueue::setDuration(std::chrono::nanoseconds workDuration) {
140 ATRACE_CALL();
141 std::lock_guard lock(mVsync.mutex);
142 mVsync.workDuration = workDuration;
143 mVsync.scheduledFrameTime =
144 mVsync.registration->update({.workDuration = mVsync.workDuration.get().count(),
145 .readyDuration = 0,
146 .earliestVsync = mVsync.lastCallbackTime.ns()});
147 }
148
waitMessage()149 void MessageQueue::waitMessage() {
150 do {
151 IPCThreadState::self()->flushCommands();
152 int32_t ret = mLooper->pollOnce(-1);
153 switch (ret) {
154 case Looper::POLL_WAKE:
155 case Looper::POLL_CALLBACK:
156 continue;
157 case Looper::POLL_ERROR:
158 ALOGE("Looper::POLL_ERROR");
159 continue;
160 case Looper::POLL_TIMEOUT:
161 // timeout (should not happen)
162 continue;
163 default:
164 // should not happen
165 ALOGE("Looper::pollOnce() returned unknown status %d", ret);
166 continue;
167 }
168 } while (true);
169 }
170
postMessage(sp<MessageHandler> && handler)171 void MessageQueue::postMessage(sp<MessageHandler>&& handler) {
172 mLooper->sendMessage(handler, Message());
173 }
174
postMessageDelayed(sp<MessageHandler> && handler,nsecs_t uptimeDelay)175 void MessageQueue::postMessageDelayed(sp<MessageHandler>&& handler, nsecs_t uptimeDelay) {
176 mLooper->sendMessageDelayed(uptimeDelay, handler, Message());
177 }
178
scheduleConfigure()179 void MessageQueue::scheduleConfigure() {
180 struct ConfigureHandler : MessageHandler {
181 explicit ConfigureHandler(ICompositor& compositor) : compositor(compositor) {}
182
183 void handleMessage(const Message&) override { compositor.configure(); }
184
185 ICompositor& compositor;
186 };
187
188 // TODO(b/241285876): Batch configure tasks that happen within some duration.
189 postMessage(sp<ConfigureHandler>::make(mCompositor));
190 }
191
scheduleFrame()192 void MessageQueue::scheduleFrame() {
193 ATRACE_CALL();
194
195 std::lock_guard lock(mVsync.mutex);
196 mVsync.scheduledFrameTime =
197 mVsync.registration->schedule({.workDuration = mVsync.workDuration.get().count(),
198 .readyDuration = 0,
199 .earliestVsync = mVsync.lastCallbackTime.ns()});
200 }
201
getScheduledFrameTime() const202 auto MessageQueue::getScheduledFrameTime() const -> std::optional<Clock::time_point> {
203 if (mHandler->isFramePending()) {
204 return Clock::now();
205 }
206
207 std::lock_guard lock(mVsync.mutex);
208 if (const auto time = mVsync.scheduledFrameTime) {
209 return Clock::time_point(std::chrono::nanoseconds(*time));
210 }
211
212 return std::nullopt;
213 }
214
215 } // namespace android::impl
216