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